text
stringlengths
1
1.05M
<filename>lib/options.js const path = require('path') const metadata = require('read-metadata') const exists = require('fs').existsSync /** * Read prompts metadata. * * @param {String} dir * @return {Object} */ module.exports = function options (name, dir) { const opts = getMetadata(name, dir) return opts } /** * Gets the metadata from either a meta.json or meta.js file. * * @param {String} dir * @return {Object} */ function getMetadata (name, dir) { const json = path.join(dir, `idea.${name}.meta.json`) const js = path.join(dir, `idea.${name}.meta.js`) let opts = {} if (exists(json)) { opts = metadata.sync(json) } else if (exists(js)) { const req = require(path.resolve(js)) if (req !== Object(req)) { throw new Error(`idea.${name}.meta.js needs to expose an object`) } opts = req } return opts }
import Foundation struct Record { var uid: String var createdTime: Date var recordId: String var recordName: String var recordRef: String init() { self.uid = "" self.createdTime = Date() self.recordId = "" self.recordName = "" self.recordRef = "" } func checkRecordValidity() -> String { if recordName.isEmpty && recordRef.isEmpty { return "Record name and reference are empty." } else if recordName.isEmpty || recordRef.isEmpty { return "Record name/reference is empty." } else { return "Record is valid." } } } // Test the checkRecordValidity method let emptyRecord = Record() print(emptyRecord.checkRecordValidity()) // Output: Record name and reference are empty. let invalidRecord = Record(recordName: "Name", recordRef: "") print(invalidRecord.checkRecordValidity()) // Output: Record name/reference is empty. let validRecord = Record(recordName: "Name", recordRef: "Reference") print(validRecord.checkRecordValidity()) // Output: Record is valid.
// Custom exception class class UnknownReaderTypeException extends IllegalArgumentException { public UnknownReaderTypeException(String unknownType) { super(String.format("Unable to create a Reader: Unknown Reader type in Source specification: %s", unknownType)); } } // Reader class class Reader { public void createReader(String sourceSpec) { // Check for unknown reader type in source specification if (sourceSpec.contains("unknownType")) { throw new UnknownReaderTypeException("unknownType"); } else { // Create the reader System.out.println("Reader created successfully for source specification: " + sourceSpec); } } } // Main program to demonstrate custom exception usage public class Main { public static void main(String[] args) { Reader reader = new Reader(); try { // Attempt to create a reader with a known type reader.createReader("knownType"); // Attempt to create a reader with an unknown type reader.createReader("unknownType"); } catch (UnknownReaderTypeException e) { System.out.println("Custom exception caught: " + e.getMessage()); } } }
#!/bin/bash #params: # - ref dpnd location # - tested dpnd location # - ref blockchain folder location # - tested blockchain folder location # - path to directory, where non-empty logs should be generated # - stop replay at block # - number of jobs (optional) # - --dont-copy-config (optional), if passed config.init files are not copied from test directories # # WARNING: use absolute paths instead of relative! # # sudo ./docker_build_and_run.sh ~/dpnit/dpn/build/Release/programs/dpnd ~/dpnit/dpn/build/Release/programs/dpnd ~/dpnit/dpnd_data/dpnnet ~/dpnit/dpnd_data/dpnnet ~/dpnit/logs 5000000 12 if [ $# -lt 6 -o $# -gt 8 ] then echo "Usage: reference_dpnd_location tested_dpnd_location ref_blockchain_folder_location tested_blockchain_folder_location" echo " logs_dir stop_replay_at_block [jobs [--dont-copy-config]" echo "Example: ~/dpnit/ref_dpnd ~/dpnit/dpn/build/Release/programs/dpnd ~/dpnit/dpnnet ~/dpnit/testnet" echo " ~/dpnit/logs 5000000 12" echo " if <jobs> not passed, <nproc> will be used." exit -1 fi echo $* JOBS=0 if [ $# -eq 7 ] then JOBS=$7 fi docker build -t smoketest ../ -f Dockerfile [ $? -ne 0 ] && echo docker build FAILED && exit -1 docker system prune -f if [ -e $5 ]; then rm -rf $5/* else mkdir -p $5 fi docker run -v $1:/reference -v $2:/tested -v $3:/ref_blockchain -v $4:/tested_blockchain -v $5:/logs_dir -v /run:/run \ -e STOP_REPLAY_AT_BLOCK=$6 -e JOBS=$JOBS -e COPY_CONFIG=$8 -p 8090:8090 -p 8091:8091 smoketest:latest
<reponame>ilariom/wildcat<gh_stars>10-100 #ifndef _WKT_SCENE_GRAPH_H #define _WKT_SCENE_GRAPH_H #include "managers/ECSContext.h" #include "components/Node.h" #include "graphics/SurfaceCache.h" #include "graphics/Camera.h" #include "graphics/Director.h" #include "systems/RenderSystem.h" #include "systems/TransformUpdateSystem.h" #include "config.h" #include <memory> namespace wkt { namespace scene { class SceneGraph final : public wkt::managers::ECSContext { public: inline SceneGraph(); SceneGraph(const SceneGraph&) = delete; SceneGraph(SceneGraph&&) = default; ~SceneGraph() = default; SceneGraph& operator=(const SceneGraph&) = delete; SceneGraph& operator=(SceneGraph&&) = default; public: void setRoot(std::shared_ptr<wkt::components::Node> node) { this->node = node; } std::shared_ptr<wkt::components::Node> root() const { return this->node; } void setDirector(wkt::gph::Director* dir) { this->dir = dir; } wkt::gph::Director* director() const { return this->dir; } wkt::gph::Camera& camera() { return this->cam; } inline void runAllSystems(); inline void render(); void setActive(bool enable) { this->active = enable; } bool isActive() const { return this->active; } private: std::shared_ptr<wkt::components::Node> node; std::unique_ptr<wkt::systems::RenderSystem> renderSystem; wkt::gph::Camera cam; wkt::gph::Director* dir = nullptr; bool active = true; }; inline SceneGraph::SceneGraph() { // this->cam.setSize({640.f, 480.f}); // this->cam.setPosition({300.f, 0.f}); this->cam.setSize({ static_cast<float>(getStartupConfig().windowWidth), static_cast<float>(getStartupConfig().windowHeight) }); this->renderSystem = std::make_unique<wkt::systems::RenderSystem>(); auto& sm = systemsManager(); sm += std::make_unique<wkt::systems::TransformUpdateSystem>(); } inline void SceneGraph::runAllSystems() { if(!isActive()) return; runComponentSystems(); if(root()) { systemsManager().run(*root()); } } inline void SceneGraph::render() { if(!root() || !isActive()) return; this->dir->setCamera(&this->cam); this->renderSystem->setDirector(this->dir); this->renderSystem->bindRoot(*root()); this->renderSystem->run(); } }} #endif
SELECT u.user_id, u.username, a.first_name, a.last_name FROM user u INNER JOIN address a ON u.user_id = a.user_id;
import random def coin_toss(): head = 0 tail = 0 print("Let's simulate a coin toss...") for _ in range(5): toss = random.randint(0,1) if toss == 0: head += 1 print("It's Heads") else: tail += 1 print("It's Tails") print(f"Heads: {head}") print(f"Tails: {tail}")
#!/usr/bin/env bash # # Copyright (c) 2019-2020 The Beans Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. export LC_ALL=C.UTF-8 export HOST=s390x-linux-gnu # The host arch is unknown, so we run the tests through qemu. # If the host is s390x and wants to run the tests natively, it can set QEMU_USER_CMD to the empty string. if [ -z ${QEMU_USER_CMD+x} ]; then export QEMU_USER_CMD="${QEMU_USER_CMD:-"qemu-s390x"}"; fi export PACKAGES="python3-zmq" if [ -n "$QEMU_USER_CMD" ]; then # Likely cross-compiling, so install the needed gcc and qemu-user export DPKG_ADD_ARCH="s390x" export PACKAGES="$PACKAGES g++-s390x-linux-gnu qemu-user libc6:s390x libstdc++6:s390x libfontconfig1:s390x libxcb1:s390x" fi # Use debian to avoid 404 apt errors export CONTAINER_NAME=ci_s390x export DOCKER_NAME_TAG="debian:buster" export RUN_UNIT_TESTS=true export TEST_RUNNER_ENV="LC_ALL=C" export RUN_FUNCTIONAL_TESTS=true export GOAL="install" export BEANS_CONFIG="--enable-reduce-exports --with-incompatible-bdb --enable-external-signer"
const fs = require("fs"); const path = require("path"); const { promises: fsPromises } = fs; const contactsPath = path.join(__dirname, "./db/contacts.json"); let currentId = 10; async function listContacts() { await fsPromises .readFile(contactsPath, "utf-8") .then((contacts) => { console.table(JSON.parse(contacts)); }) .catch((err) => console.warn(err)); } async function getContactById(contactId) { await fsPromises .readFile(contactsPath, "utf-8") .then((contacts) => JSON.parse(contacts).find((contact) => contact.id === contactId) ) .then((contact) => console.table(contact)) .catch((err) => console.warn(err)); } async function removeContact(contactId) { await fsPromises .readFile(contactsPath, "utf-8") .then((contacts) => JSON.parse(contacts)) .then((contacts) => contacts.filter((contact) => contact.id !== contactId)) .then((contacts) => JSON.stringify(contacts)) .then((contacts) => fsPromises.writeFile(contactsPath, contacts)) .then(() => fsPromises.readFile(contactsPath, "utf-8")) .then((contacts) => console.table(JSON.parse(contacts))) .catch((err) => console.warn(err)); } async function addContact(name, email, phone) { currentId += 1; await fsPromises .readFile(contactsPath, "utf-8") .then((contacts) => JSON.parse(contacts)) .then((contacts) => [ ...contacts, { id: currentId, name, email, phone, }, ]) .then((contacts) => JSON.stringify(contacts)) .then((contacts) => fsPromises.writeFile(contactsPath, contacts)) .then(() => fsPromises.readFile(contactsPath, "utf-8")) .then((contacts) => console.table(JSON.parse(contacts))) .catch((err) => console.warn(err)); } module.exports = { listContacts, getContactById, removeContact, addContact, };
import React from "react" import renderer from "react-test-renderer" import { SectionContent } from "./section" describe("sectionContent", () => { it("should not add mb2 className when children is only a text string", () => { const tree = renderer.create(<SectionContent>aaaa</SectionContent>).toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > aaaa </div> `) }) it("should not add mb2 className on p when it is the last element", () => { const tree = renderer .create( <SectionContent> aaaa <p>Test</p> </SectionContent> ) .toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > aaaa <p> Test </p> </div> `) }) it("should add mb2 className on first p", () => { const tree = renderer .create( <SectionContent> <p>Abc</p> <p>Test</p> </SectionContent> ) .toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > <p className="mb2 " > Abc </p> <p> Test </p> </div> `) }) it("should add mb2 className and keep other provided className on first p", () => { const tree = renderer .create( <SectionContent> <p className="foo">Abc</p> <p>Test</p> </SectionContent> ) .toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > <p className="mb2 foo" > Abc </p> <p> Test </p> </div> `) }) it("should add mb2 className on all p but last one", () => { const tree = renderer .create( <SectionContent> <p>Abc</p> <p>345</p> <p>678</p> <p>Test</p> </SectionContent> ) .toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > <p className="mb2 " > Abc </p> <p className="mb2 " > 345 </p> <p className="mb2 " > 678 </p> <p> Test </p> </div> `) }) it("should add mb2 className on first ul", () => { const tree = renderer .create( <SectionContent> <ul>Abc</ul> <p>Test</p> </SectionContent> ) .toJSON() expect(tree).toMatchInlineSnapshot(` .emotion-0 { line-height: 1.5em; margin-bottom: 1.45rem; } <div className=" f5 section-content tj emotion-0" > <ul className="mb2 " > Abc </ul> <p> Test </p> </div> `) }) })
#!/usr/bin/env bash #Build logos.json before commit (cd ./source && ./buildLogos.js) if [[ $? -eq 1 ]]; then echo "Error build logos.json"; exit 1; fi; #Run directory.js before commit node directory.js if [[ $? -eq 1 ]]; then echo "Error with run directory.js"; exit 1; fi; # Build buildInfo.json ID="$(git rev-list --count HEAD)"; cd ./static && echo {'"buildId"': $ID} > buildInfo.json; # Commit COMMIT_NAME=$(openssl dgst -sha256 buildInfo.json | sed 's/^.* //'); git add . git commit -a -m "Commit id: $COMMIT_NAME"
""" Develop a code that takes a text string as input and returns the longest word in the text string """ def longest_word(text): words = text.split() longest_word = "" max_length = 0 for word in words: if len(word) > max_length: max_length = len(word) longest_word = word return longest_word if __name__ == '__main__': text = "Hello this is a random text" print(longest_word(text))
#!/bin/bash unameOut="$(uname -s)" case "${unameOut}" in Linux*) machine=Linux;; Darwin*) machine=Mac;; CYGWIN*) machine=Cygwin;; MINGW*) machine=MinGw;; *) machine="UNKNOWN:${unameOut}" esac # make sure node is installed if ! command -v node;then echo "Install node and npm first then re-run script" echo "Go to https://nodejs.org/en/download/ to download and install" exit fi # if yarn isn't installed install it if ! command -v yarn;then npm -g install yarn fi git clone https://github.com/elmsln/HAXcms.git cd HAXcms/ # install docker if not installed if ! command -v docker;then curl -fsSL https://get.docker.com -o get-docker.sh sudo sh get-docker.sh fi windows_ddev() { # make sure chocolatey is installed if ! command -v choco;then echo "Please install Chocolatey then run again script again" echo "(https://chocolatey.org/install)" else choco install ddev git fi } linux_ddev() { if ! command -v ddev;then curl -LO https://raw.githubusercontent.com/drud/ddev/master/scripts/install_ddev.sh && bash install_ddev.sh fi } if [ "${machine}" == "Cygwin" ]; then windows_ddev elif [ "${machine}" == "MinGw" ]; then windows_ddev else if ! command -v docker-compose;then sudo curl -L "https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose sudo chmod +x /usr/local/bin/docker-compose sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose fi linux_ddev fi
from typing import List, Dict, Any import instaloader def download_instagram_posts(usernames: List[str]) -> Dict[str, List[Dict[str, Any]]]: result = {} L = instaloader.Instaloader(download_videos=False, download_video_thumbnails=False, download_geotags=False, download_comments=False, save_metadata=True, post_metadata_txt_pattern="") for username in usernames: try: profile = instaloader.Profile.from_username(L.context, username) posts = profile.get_posts() user_posts = [] for post in posts: post_data = { 'id': post.shortcode, 'timestamp': post.date_utc.strftime('%Y-%m-%d %H:%M:%S'), 'likes': post.likes, 'comments': post.comments, 'caption': post.caption } user_posts.append(post_data) result[username] = user_posts except instaloader.exceptions.ProfileNotExistsException: result[username] = "Error: Profile not found" except instaloader.exceptions.QueryReturnedNotFoundException: result[username] = "Error: Profile not found" except instaloader.exceptions.ConnectionException: result[username] = "Error: Connection error" except Exception as e: result[username] = f"Error: {str(e)}" return result
sudo apt-get update -y sudo apt-get install git python-pip python-dev -y vagrant_pkg_url=https://dl.bintray.com/mitchellh/vagrant/vagrant_1.7.2_x86_64.deb wget ${vagrant_pkg_url} sudo dpkg -i $(basename ${vagrant_pkg_url}) sudo apt-get install libxslt-dev libxml2-dev libvirt-dev build-essential qemu-utils qemu-kvm libvirt-bin virtinst -y sudo service libvirt-bin restart vagrant plugin install vagrant-libvirt vagrant plugin install vagrant-mutate precise_box_vb_url=https://cloud-images.ubuntu.com/vagrant/precise/current/precise-server-cloudimg-amd64-vagrant-disk1.box precise_box_vb_filename=$(basename ${precise_box_vb_url}) centos65_box_vb_url=https://developer.nrel.gov/downloads/vagrant-boxes/CentOS-6.5-x86_64-v20140504.box centos65_box_vb_filename=$(basename ${centos65_box_vb_url}) wget ${precise_box_vb_url} wget ${centos65_box_vb_url} mv ${precise_box_vb_filename} precise64.box mv ${centos65_box_vb_filename} centos65.box vagrant mutate precise64.box libvirt vagrant mutate centos65.box libvirt sudo pip install ansible git clone http://git.openstack.org/openstack/compass-install cd compass-install function join { local IFS="$1"; shift; echo "$*"; } if [[ ! -z $VIRT_NUMBER ]]; then mac_array=$(ci/mac_generator.sh $VIRT_NUMBER) mac_list=$(join , $mac_array) echo "pxe_boot_macs: [${mac_list}]" >> install/group_vars/all echo "test: true" >> install/group_vars/all fi sudo vagrant up compass_vm if [[ $? != 0 ]]; then sudo vagrant provision compass_vm if [[ $? != 0 ]]; then echo "provisioning of compass failed" exit 1 fi fi echo "compass is up" if [[ -n $mac_array ]] echo "bringing up pxe boot vms" i=0 for mac in "$mac_array"; do virsh list |grep pxe${i} if [[ $? == 0 ]]; then virsh destroy pxe${i} virsh undefine pxe${i} fi virsh list --all |grep pxe${i} if [[ $? == 0 ]]; then virsh undefine pxe${i} fi echo "creating vm disk for instance pxe${i}" sudo qemu-img create -f raw /home/pxe${i}.raw ${VIRT_DISK} sudo virt-install --accelerate --hvm --connect qemu:///system \ --name pxe$i --ram=$VIRT_MEM --pxe --disk /home/pxe$i.raw,format=raw \ --vcpus=$VIRT_CPUS --graphics vnc,listen=0.0.0.0 \ --network=bridge:virbr2,mac=$mac \ --network=bridge:virbr2 --network=bridge:virbr2 --network=bridge:virbr2 --noautoconsole --autostart --os-type=linux --os-variant=rhel6 if [[ $? != 0 ]]; then echo "launching pxe${i} failed" exit 1 fi echo "checking pxe${i} state" state=$(virsh domstate pxe${i}) if [[ "$state" == "running" ]]; then echo "pxe${i} is running" sudo virsh destroy pxe${i} fi echo "add network boot option and make pxe${i} reboot if failing" sudo sed -i "/<boot dev='hd'\/>/ a\ <boot dev='network'\/>" /etc/libvirt/qemu/pxe${i}.xml sudo sed -i "/<boot dev='network'\/>/ a\ <bios useserial='yes' rebootTimeout='0'\/>" /etc/libvirt/qemu/pxe${i}.xml sudo virsh define /etc/libvirt/qemu/pxe${i}.xml sudo virsh start pxe${i} let i=i+1 done fi rm -rf compass-core git clone http://git.openstack.org/openstack/compass-core -b dev/experimental cd compass-core virtualenv venv source venv/bin/activate pip install -e . if [[ ! -f /var/log/compass ]]; then sudo mkdir /var/log/compass sudo chown -R 777 /var/log/compass fi if [[ ! -f /etc/compass ]]; then sudo mkdir /etc/compass sudo cp -rf conf/setting /etc/compass/. fi cp bin/switch_virtualenv.py.template bin/switch_virtualenv.py sed -i "s|\$PythonHome|$VIRTUAL_ENV|g" /opt/compass/bin/switch_virtualenv.py source ../compass-install/ci/allinone.conf bin/client.py --logfile= --loglevel=debug --logdir= --compass_server="${COMPASS_SERVER_URL}" \ --compass_user_email="${COMPASS_USER_EMAIL}" --compass_user_password="${COMPASS_USER_PASSWORD}" \ --cluster_name="${CLUSTER_NAME}" --language="${LANGUAGE}" --timezone="${TIMEZONE}" \ --hostnames="${HOSTNAMES}" --partitions="${PARTITIONS}" --subnets="${SUBNETS}" \ --adapter_os_pattern="${ADAPTER_OS_PATTERN}" --adapter_name="${ADAPTER_NAME}" \ --adapter_flavor_pattern="${ADAPTER_FLAVOR_PATTERN}" \ --http_proxy="${PROXY}" --https_proxy="${PROXY}" --no_proxy="${IGNORE_PROXY}" \ --ntp_server="${NTP_SERVER}" --dns_servers="${NAMESERVERS}" --domain="${DOMAIN}" \ --search_path="${SEARCH_PATH}" --default_gateway="${GATEWAY}" \ --server_credential="${SERVER_CREDENTIAL}" --local_repo_url="${LOCAL_REPO_URL}" \ --os_config_json_file="${OS_CONFIG_FILENAME}" --service_credentials="${SERVICE_CREDENTIALS}" \ --console_credentials="${CONSOLE_CREDENTIALS}" --host_networks="${HOST_NETWORKS}" \ --network_mapping="${NETWORK_MAPPING}" --package_config_json_file="${PACKAGE_CONFIG_FILENAME}" \ --host_roles="${HOST_ROLES}" --default_roles="${DEFAULT_ROLES}" --switch_ips="${SWITCH_IPS}" \ --machines="${machines}" --switch_credential="${SWITCH_CREDENTIAL}" \ --deployment_timeout="${DEPLOYMENT_TIMEOUT}" --${POLL_SWITCHES_FLAG} --dashboard_url="${DASHBOARD_URL}" #sudo vagrant up regtest_vm #if [[ $? != 0 ]]; then # sudo vagrant provision regtest_vm # if [[ $? != 0 ]]; then # echo "deployment of cluster failed" # exit 1 # fi #fi #echo "deployment of cluster complete"
#include <string> #include <system_error> namespace detail { template<typename String> struct string_traits { static const char* c_str(const String& str) { return str.c_str(); } }; } void binder(const char* host, unsigned port, std::error_code& ec) { // Implementation of the binder function is not provided // Assume it binds the network socket to the specified host and port // and sets the error code if any error occurs } template<typename String> void bind(const String& host, unsigned port, std::error_code& ec) noexcept { binder(detail::string_traits<String>::c_str(host), port, ec); }
<gh_stars>1-10 import { GET_ALL_EMPLOYEE_START, GET_ALL_EMPLOYEE_SUCCESS, GET_ALL_EMPLOYEE_FAIL, GET_ALL_EMPLOYEE_RESOLVE, GET_EMPLOYEE_START, GET_EMPLOYEE_SUCCESS, GET_EMPLOYEE_FAIL, GET_EMPLOYEE_RESOLVE, ADD_EMPLOYEE_START, ADD_EMPLOYEE_SUCCESS, ADD_EMPLOYEE_FAIL, ADD_EMPLOYEE_RESOLVE, EDIT_EMPLOYEE_START, EDIT_EMPLOYEE_SUCCESS, EDIT_EMPLOYEE_FAIL, EDIT_EMPLOYEE_RESOLVE, DELETE_EMPLOYEE_START, DELETE_EMPLOYEE_SUCCESS, DELETE_EMPLOYEE_FAIL, DELETE_EMPLOYEE_RESOLVE, } from '../actions/employeeActions'; // Initial Employee State export const initialEmployeeState = { employees: [], employee: null, status: 'Resolved', change: '', error: '', }; export const employeeReducer = (state = initialEmployeeState, action) => { switch (action.type) { //Get All Employees case GET_ALL_EMPLOYEE_START: return { ...state, status: 'Pending...', }; case GET_ALL_EMPLOYEE_SUCCESS: // console.log(action.payload, 'payload inside reducer'); return { ...state, employees: action.payload, status: 'Success', }; case GET_ALL_EMPLOYEE_FAIL: return { ...state, status: 'Failed', error: action.payload, }; case GET_ALL_EMPLOYEE_RESOLVE: // console.log(state.employees, 'state inside reducer'); return { ...state, status: 'Resolved', }; // Get Employee By Id case GET_EMPLOYEE_START: return { ...state, status: 'Pending...', }; case GET_EMPLOYEE_SUCCESS: return { ...state, employee: action.payload, status: 'Success', }; case GET_EMPLOYEE_FAIL: return { ...state, status: 'Failed', error: action.payload, }; case GET_EMPLOYEE_RESOLVE: return { ...state, status: 'Resolved', }; //Add Employee case ADD_EMPLOYEE_START: return { ...state, status: 'Pending...', }; case ADD_EMPLOYEE_SUCCESS: return { ...state, status: 'Success', change: 'added', }; case ADD_EMPLOYEE_FAIL: return { ...state, status: 'Failed', error: action.payload, }; case ADD_EMPLOYEE_RESOLVE: return { ...state, status: 'Resolved', change: '', }; //Edit Employee case EDIT_EMPLOYEE_START: return { ...state, status: 'Pending...', }; case EDIT_EMPLOYEE_SUCCESS: return { ...state, status: 'Success', change: 'edited', }; case EDIT_EMPLOYEE_FAIL: return { ...state, status: 'Failed', error: action.payload, }; case EDIT_EMPLOYEE_RESOLVE: return { ...state, status: 'Resolved', change: '', }; // Delete Employee case DELETE_EMPLOYEE_START: return { ...state, status: 'Pending...', }; case DELETE_EMPLOYEE_SUCCESS: return { ...state, status: 'Success', change: 'deleted', }; case DELETE_EMPLOYEE_FAIL: return { ...state, status: 'Failed', error: action.payload, }; case DELETE_EMPLOYEE_RESOLVE: return { ...state, status: 'Resolved', change: '', }; //Default default: return state; } };
import {_, Autowired, Component, PostConstruct} from "@ag-grid-community/core"; import {ChartMenu} from "./menu/chartMenu"; import {Chart} from "ag-charts-community"; import {ChartTranslator} from "./chartTranslator"; import {ChartProxy} from "./chartProxies/chartProxy"; type BBox = { x: number; y: number; width: number; height: number }; export class TitleEdit extends Component { private static TEMPLATE = /* html */ `<input class="ag-chart-title-edit" style="padding:0; border:none; border-radius: 0; min-height: 0; text-align: center;" /> `; @Autowired('chartTranslator') private chartTranslator: ChartTranslator; private chartProxy: ChartProxy<Chart, any>; private destroyableChartListeners: (() => void)[]; constructor(private readonly chartMenu: ChartMenu) { super(TitleEdit.TEMPLATE); } @PostConstruct public init(): void { this.addManagedListener(this.getGui(), 'keypress', (e: KeyboardEvent) => { if (e.key === 'Enter') { this.endEditing(); } }); this.addManagedListener(this.getGui(), 'blur', this.endEditing.bind(this)); } /* should be called when the containing component changes to a new chart proxy */ public setChartProxy(chartProxy: ChartProxy<Chart, any>) { if (this.chartProxy) { for (let i = 0; i++; i < this.destroyableChartListeners.length) { this.destroyableChartListeners[i](); } this.destroyableChartListeners = []; } this.chartProxy = chartProxy; const chart = this.chartProxy.getChart(); const canvas = chart.scene.canvas.element; const destroyDbleClickListener = this.addManagedListener(canvas, 'dblclick', event => { const { title } = chart; if (title && title.node.containsPoint(event.offsetX, event.offsetY)) { const bbox = title.node.computeBBox(); const xy = title.node.inverseTransformPoint(bbox.x, bbox.y); this.startEditing({ ...bbox, ...xy }); } }); const destroyMouseMoveListener = this.addManagedListener(canvas, 'mousemove', event => { const { title } = chart; const inTitle = title && title.node.containsPoint(event.offsetX, event.offsetY); canvas.style.cursor = inTitle ? 'pointer' : ''; }); this.destroyableChartListeners = [ destroyDbleClickListener, destroyMouseMoveListener ]; } private startEditing(titleBBox: BBox): void { if (this.chartMenu && this.chartMenu.isVisible()) { // currently we ignore requests to edit the chart title while the chart menu is showing // because the click to edit the chart will also close the chart menu, making the position // of the title change. return; } const minimumTargetInputWidth: number = 300; const maximumInputWidth: number = this.chartProxy.getChart().width; const inputWidth = Math.max(Math.min(titleBBox.width + 20, maximumInputWidth), minimumTargetInputWidth); const inputElement = this.getGui() as HTMLInputElement; _.addCssClass(inputElement, 'currently-editing'); const inputStyle = inputElement.style; // match style of input to title that we're editing inputStyle.fontFamily = this.chartProxy.getTitleOption('fontFamily'); inputStyle.fontWeight = this.chartProxy.getTitleOption('fontWeight'); inputStyle.fontStyle = this.chartProxy.getTitleOption('fontStyle'); inputStyle.fontSize = this.chartProxy.getTitleOption('fontSize') + 'px'; inputStyle.color = this.chartProxy.getTitleOption('color'); // populate the input with the title, unless the title is the placeholder: const oldTitle = this.chartProxy.getTitleOption('text'); const inputValue = oldTitle === this.chartTranslator.translate('titlePlaceholder') ? '' : oldTitle; inputElement.value = inputValue; const inputRect = inputElement.getBoundingClientRect(); inputStyle.left = Math.round(titleBBox.x + titleBBox.width / 2 - inputWidth / 2) + 'px'; inputStyle.top = Math.round(titleBBox.y + titleBBox.height / 2 - inputRect.height / 2) + 'px'; inputStyle.width = Math.round(inputWidth) + 'px'; inputElement.focus(); } private endEditing(): void { const value = (this.getGui() as HTMLInputElement).value; this.chartProxy.setTitleOption('text', value); this.eventService.dispatchEvent({'type': 'chartTitleEdit'}); _.removeCssClass(this.getGui(), 'currently-editing'); } }
#!/bin/bash # Copyright 2018-2020 Daniel Povey # 2018-2020 Yiming Wang # This recipe uses E2E LF-MMI training which doesn't require GMM training to obtain alignments. # Its performance is slightly better than those based on alignments (cross-entropy or regular LF-MMI) # on this dataset. stage=0 . ./cmd.sh . ./path.sh . utils/parse_options.sh set -euo pipefail if [ $stage -le 0 ]; then local/mobvoi_data_download.sh echo "$0: Extracted all datasets into data/download/" fi if [ $stage -le 1 ]; then echo "$0: Splitting datasets..." local/split_datasets.sh echo "$0: text and utt2spk have been generated in data/{train|dev|eval}." fi if [ $stage -le 2 ]; then echo "$0: Preparing wav.scp..." local/prepare_wav.py data echo "wav.scp has been generated in data/{train|dev|eval}." fi if [ $stage -le 3 ]; then echo "$0: Extracting MFCC..." for folder in train dev eval; do dir=data/$folder utils/fix_data_dir.sh $dir steps/make_mfcc.sh --cmd "$train_cmd" --nj 16 $dir steps/compute_cmvn_stats.sh $dir utils/fix_data_dir.sh $dir utils/data/get_utt2dur.sh $dir utils/validate_data_dir.sh $dir done fi if [ $stage -le 4 ]; then echo "$0: Post processing transcripts..." for folder in train dev eval; do dir=data/$folder export LC_ALL=en_US.UTF-8 cat $dir/text | awk '{if ($2=="嗨小问" || $2=="嗨小问嗨小问") {print $1,"嗨小问";} else {print $1,"FREETEXT"}}' > $dir/text.tmp || exit 1 export LC_ALL=C cat $dir/text.tmp > $dir/text || exit 1 rm -f $dir/text.tmp 2>/dev/null || true done fi if [ $stage -le 5 ]; then echo "$0: Preparing dictionary and lang..." local/prepare_dict.sh utils/prepare_lang.sh --num-sil-states 1 --num-nonsil-states 4 --sil-prob 0.5 \ --position-dependent-phones false \ data/local/dict "<sil>" data/lang/temp data/lang fi if [ $stage -le 6 ]; then id_sil=`cat data/lang/words.txt | grep "<sil>" | awk '{print $2}'` id_freetext=`cat data/lang/words.txt | grep "FREETEXT" | awk '{print $2}'` export LC_ALL=en_US.UTF-8 id_word=`cat data/lang/words.txt | grep "嗨小问" | awk '{print $2}'` export LC_ALL=C mkdir -p data/lang/lm cat <<EOF > data/lang/lm/fst.txt 0 1 $id_sil $id_sil 0 4 $id_sil $id_sil 7.0 1 4 $id_freetext $id_freetext 0.0 4 0 $id_sil $id_sil 1 2 $id_word $id_word 1.1 2 0 $id_sil $id_sil 0 EOF fstcompile data/lang/lm/fst.txt data/lang/G.fst set +e fstisstochastic data/lang/G.fst set -e utils/validate_lang.pl data/lang fi if [ $stage -le 7 ]; then echo "$0: subsegmenting for the training data..." srcdir=data/train utils/data/convert_data_dir_to_whole.sh $srcdir ${srcdir}_whole utils/data/get_segments_for_data.sh $srcdir > ${srcdir}_whole/segments utils/filter_scp.pl <(awk '{if ($2 == "FREETEXT") print $1}' ${srcdir}_whole/text) \ ${srcdir}_whole/segments >${srcdir}_whole/neg_segments utils/filter_scp.pl --exclude ${srcdir}_whole/neg_segments ${srcdir}_whole/segments \ >${srcdir}_whole/pos_segments utils/filter_scp.pl ${srcdir}_whole/pos_segments ${srcdir}_whole/utt2dur >${srcdir}_whole/pos_utt2dur local/get_random_subsegments.py --overlap-duration=0.3 --max-remaining-duration=0.3 \ ${srcdir}_whole/neg_segments ${srcdir}_whole/pos_utt2dur | \ cat ${srcdir}_whole/pos_segments - | sort >${srcdir}_whole/sub_segments utils/data/subsegment_data_dir.sh ${srcdir}_whole \ ${srcdir}_whole/sub_segments data/train_segmented awk '{print $1,$2}' ${srcdir}_whole/sub_segments | \ utils/apply_map.pl -f 2 ${srcdir}_whole/text >data/train_segmented/text utils/data/extract_wav_segments_data_dir.sh --nj 50 --cmd "$train_cmd" \ data/train_segmented data/train_shorter steps/compute_cmvn_stats.sh data/train_shorter utils/fix_data_dir.sh data/train_shorter utils/validate_data_dir.sh data/train_shorter fi # In this section, we augment the training data with reverberation, # noise, music, and babble, and combined it with the clean data. if [ $stage -le 8 ]; then utils/data/get_utt2dur.sh data/train_shorter cp data/train_shorter/utt2dur data/train_shorter/reco2dur # Download the package that includes the real RIRs, simulated RIRs, isotropic noises and point-source noises [ ! -f rirs_noises.zip ] && wget --no-check-certificate http://www.openslr.org/resources/28/rirs_noises.zip [ ! -d "RIRS_NOISES" ] && unzip rirs_noises.zip # Make a version with reverberated speech rvb_opts=() rvb_opts+=(--rir-set-parameters "0.5, RIRS_NOISES/simulated_rirs/smallroom/rir_list") rvb_opts+=(--rir-set-parameters "0.5, RIRS_NOISES/simulated_rirs/mediumroom/rir_list") # Make a reverberated version of the SWBD+SRE list. Note that we don't add any # additive noise here. steps/data/reverberate_data_dir.py \ "${rvb_opts[@]}" \ --speech-rvb-probability 1 \ --prefix "rev" \ --pointsource-noise-addition-probability 0 \ --isotropic-noise-addition-probability 0 \ --num-replications 1 \ --source-sampling-rate 16000 \ data/train_shorter data/train_shorter_reverb cat data/train_shorter/utt2dur | awk -v name=rev1 '{print name"-"$0}' >data/train_shorter_reverb/utt2dur # Prepare the MUSAN corpus, which consists of music, speech, and noise # suitable for augmentation. steps/data/make_musan.sh /export/corpora/JHU/musan data # Get the duration of the MUSAN recordings. This will be used by the # script augment_data_dir.py. for name in speech noise music; do utils/data/get_utt2dur.sh data/musan_${name} cp data/musan_${name}/utt2dur data/musan_${name}/reco2dur done # Augment with musan_noise export LC_ALL=en_US.UTF-8 steps/data/augment_data_dir.py --utt-prefix "noise" --modify-spk-id true --fg-interval 1 --fg-snrs "15:10:5:0" --fg-noise-dir "data/musan_noise" data/train_shorter data/train_shorter_noise # Augment with musan_music steps/data/augment_data_dir.py --utt-prefix "music" --modify-spk-id true --bg-snrs "15:10:8:5" --num-bg-noises "1" --bg-noise-dir "data/musan_music" data/train_shorter data/train_shorter_music # Augment with musan_speech steps/data/augment_data_dir.py --utt-prefix "babble" --modify-spk-id true --bg-snrs "20:17:15:13" --num-bg-noises "3:4:5:6:7" --bg-noise-dir "data/musan_speech" data/train_shorter data/train_shorter_babble export LC_ALL=C fi if [ $stage -le 9 ]; then # Now make MFCC features for name in reverb noise music babble; do steps/make_mfcc.sh --nj 16 --cmd "$train_cmd" \ data/train_shorter_${name} || exit 1; steps/compute_cmvn_stats.sh data/train_shorter_${name} utils/fix_data_dir.sh data/train_shorter_${name} utils/validate_data_dir.sh data/train_shorter_${name} done fi combined_train_set=train_shorter_combined aug_affix="reverb noise music babble" if [ $stage -le 10 ]; then aug_affix="reverb noise music babble" eval utils/combine_data.sh data/${combined_train_set} data/train_shorter_{$(echo $aug_affix | sed 's/ /,/g')} fi if [ -f data/${combined_train_set}_spe2e_hires/feats.scp ]; then echo "$0: It seems that features for the perturbed training data already exist." echo "If you want to extract them anyway, remove them first and run this" echo "stage again. Skipping this stage..." else if [ $stage -le 11 ]; then echo "$0: perturbing the training data to allowed lengths..." utils/data/get_utt2dur.sh data/${combined_train_set} # necessary for the next command # 12 in the following command means the allowed lengths are spaced # by 12% change in length. utils/data/perturb_speed_to_allowed_lengths.py --speed-perturb false 12 data/${combined_train_set} \ data/${combined_train_set}_e2e_hires cat data/${combined_train_set}_e2e_hires/utt2dur | \ awk '{print $1 " " substr($1,5)}' >data/${combined_train_set}_e2e_hires/utt2uniq.tmp utils/apply_map.pl -f 2 data/${combined_train_set}/utt2uniq \ <data/${combined_train_set}_e2e_hires/utt2uniq.tmp >data/${combined_train_set}_e2e_hires/utt2uniq rm -f data/${combined_train_set}_e2e_hires/utt2uniq.tmp 2>/dev/null || true utils/fix_data_dir.sh data/${combined_train_set}_e2e_hires utils/data/get_utt2dur.sh data/train_shorter # necessary for the next command utils/data/perturb_speed_to_allowed_lengths.py 12 data/train_shorter data/train_shorter_spe2e_hires cat data/train_shorter_spe2e_hires/utt2dur | \ awk '{print $1 " " substr($1,5)}' >data/train_shorter_spe2e_hires/utt2uniq utils/fix_data_dir.sh data/train_shorter_spe2e_hires utils/combine_data.sh data/${combined_train_set}_spe2e_hires data/${combined_train_set}_e2e_hires data/train_shorter_spe2e_hires cat data/train_shorter_spe2e_hires/allowed_lengths.txt >data/${combined_train_set}_spe2e_hires/allowed_lengths.txt fi if [ $stage -le 12 ]; then echo "$0: extracting MFCC features for the training data..." mfccdir=data/${combined_train_set}_spe2e_hires/data if [[ $(hostname -f) == *.clsp.jhu.edu ]] && [ ! -d $mfccdir/storage ]; then utils/create_split_dir.pl /export/b0{5,6,7,8}/$USER/kaldi-data/egs/mobvoi-$(date +'%m_%d_%H_%M')/v1/$mfccdir/storage $mfccdir/storage fi steps/make_mfcc.sh --nj 50 --mfcc-config conf/mfcc_hires.conf \ --cmd "$train_cmd" \ data/${combined_train_set}_spe2e_hires || exit 1; steps/compute_cmvn_stats.sh data/${combined_train_set}_spe2e_hires || exit 1; utils/fix_data_dir.sh data/${combined_train_set}_spe2e_hires utils/validate_data_dir.sh data/${combined_train_set}_spe2e_hires fi fi if [ $stage -le 13 ]; then if [ -f data/eval_hires/feats.scp ]; then echo "$0: It seems that features for the test sets already exist." echo "skipping this stage..." else echo "$0: extracting MFCC features for the test sets" for datadir in dev eval; do utils/copy_data_dir.sh data/$datadir data/${datadir}_hires steps/make_mfcc.sh --cmd "$train_cmd" --nj 50 --mfcc-config conf/mfcc_hires.conf \ --cmd "$train_cmd" data/${datadir}_hires || exit 1; steps/compute_cmvn_stats.sh data/${datadir}_hires || exit 1; utils/fix_data_dir.sh data/${datadir}_hires || exit 1; done fi fi if [ $stage -le 14 ]; then local/chain/run_e2e_tdnn.sh --train-set ${combined_train_set}_spe2e fi combined_train_set=train_shorter_sp_combined if [ -f data/${combined_train_set}_hires/feats.scp ]; then echo "$0: It seems that features for the perturbed training data already exist." echo "If you want to extract them anyway, remove them first and run this" echo "stage again. Skipping this stage..." else if [ $stage -le 15 ]; then echo "$0: preparing for speed-perturbed data" utils/data/perturb_data_dir_speed_3way.sh data/train_shorter data/train_shorter_sp_hires echo "$0: creating high-resolution MFCC features for speed-perturbed data" mfccdir=data/train_shorter_sp_hires/data if [[ $(hostname -f) == *.clsp.jhu.edu ]] && [ ! -d $mfccdir/storage ]; then utils/create_split_dir.pl /export/b0{5,6,7,8}/$USER/kaldi-data/egs/mobvoi-$(date +'%m_%d_%H_%M')/v1/$mfccdir/storage $mfccdir/storage fi # do volume-perturbation on the training data prior to extracting hires # features; this helps make trained nnets more invariant to test data volume. utils/data/perturb_data_dir_volume.sh data/train_shorter_sp_hires || exit 1; steps/make_mfcc.sh --nj 50 --mfcc-config conf/mfcc_hires.conf \ --cmd "$train_cmd" data/train_shorter_sp_hires || exit 1; steps/compute_cmvn_stats.sh data/train_shorter_sp_hires || exit 1; utils/fix_data_dir.sh data/train_shorter_sp_hires || exit 1; fi if [ $stage -le 16 ]; then for name in $aug_affix; do echo "$0: creating high-resolution MFCC features for train_shorter_${name}" mfccdir=data/train_shorter_${name}_hires/data if [[ $(hostname -f) == *.clsp.jhu.edu ]] && [ ! -d $mfccdir/storage ]; then utils/create_split_dir.pl /export/b0{5,6,7,8}/$USER/kaldi-data/egs/mobvoi-$(date +'%m_%d_%H_%M')/v1/$mfccdir/storage $mfccdir/storage fi utils/copy_data_dir.sh data/train_shorter_${name} data/train_shorter_${name}_hires steps/make_mfcc.sh --nj 50 --mfcc-config conf/mfcc_hires.conf \ --cmd "$train_cmd" data/train_shorter_${name}_hires || exit 1; steps/compute_cmvn_stats.sh data/train_shorter_${name}_hires || exit 1; utils/fix_data_dir.sh data/train_shorter_${name}_hires || exit 1; done eval utils/combine_data.sh data/${combined_train_set}_hires data/train_shorter_sp_hires \ data/train_shorter_{$(echo $aug_affix | sed 's/ /,/g')}_hires fi fi if [ $stage -le 17 ]; then echo "$0: Aligning the training data using the e2e chain model..." steps/nnet3/align.sh --nj 50 --cmd "$train_cmd" \ --use-gpu false \ --scale-opts '--transition-scale=1.0 --self-loop-scale=1.0 --acoustic-scale=1.0' \ data/${combined_train_set}_hires data/lang exp/chain/e2e_tdnn_1a exp/chain/e2e_ali_${combined_train_set} fi if [ $stage -le 18 ]; then echo "$0: Building a tree and training a regular chain model using the e2e alignments..." local/chain/run_tdnn_e2eali.sh --train-set ${combined_train_set} --e2echain-model-dir exp/chain/e2e_tdnn_1a fi exit 0
#!/bin/sh docker-compose up -d sleep 10 sensible-browser http://localhost:18080/zap
package ru.job4j.user; import org.junit.Test; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * SortUserTest * * @author <NAME> (<EMAIL>) * @version $Id$ * @since 0.1 */ public class SortUserTest { @Test public void whenNoAnyUsersThenEmptyTreeSet() { List<User> users = new ArrayList<User>(); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); assertThat(tree.isEmpty(), is(true)); } @Test public void whenOneUserThenOneElementInTreeSet() { List<User> users = new ArrayList<User>(); users.add(new User("Maria", 21)); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); Set<User> expected = Set.of( new User("Maria", 21) ); assertThat(expected.equals(tree), is(true)); } @Test public void whenTwoAgeSortedUsersThenTwoAgeSortedUsersInTreeSet() { List<User> users = new ArrayList<User>(); users.add(new User("Maria", 21)); users.add(new User("Ivan", 27)); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); Set<User> expected = Set.of( new User("Maria", 21), new User("Ivan", 27) ); assertThat(expected.equals(tree), is(true)); } @Test public void whenTwoNonAgeSortedUsersThenTwoAgeSortedUsersInTreeSet() { List<User> users = new ArrayList<User>(); users.add(new User("Ivan", 27)); users.add(new User("Maria", 21)); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); Set<User> expected = Set.of( new User("Maria", 21), new User("Ivan", 27) ); assertThat(expected.equals(tree), is(true)); } @Test public void whenThreeNonAgeSortedUsersThenThreeAgeSortedUsersInTreeSet() { List<User> users = new ArrayList<User>(); users.add(new User("Ivan", 27)); users.add(new User("Maria", 21)); users.add(new User("Nick", 32)); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); Set<User> expected = Set.of( new User("Maria", 21), new User("Ivan", 27), new User("Nick", 32) ); assertThat(expected.equals(tree), is(true)); } @Test public void whenTwoUsersWithEqualAgeThenReturnedInSetOnlyFirstUser() { List<User> users = new ArrayList<>(); users.add(new User("Jim", 30)); users.add(new User("Vlad", 30)); Set<User> tree = new TreeSet<>(new SortUser().sort(users)); Set<User> expected = Set.of( new User("Jim", 30) ); assertThat(expected.equals(tree), is(true)); } @Test public void whenThreeUsersWithDifferentNamesThenSortedByNameLength() { List<User> users = new ArrayList<User>(); users.add(new User("Karina")); users.add(new User("Jim")); users.add(new User("Vlad")); new SortUser().sortNameLength(users); List<User> expected = List.of( new User("Jim"), new User("Vlad"), new User("Karina") ); assertThat(expected.equals(users), is(true)); } @Test public void whenFourUsersWithDifferentNamesAndAgesThenSortedByAllFields() { List<User> users = new ArrayList<User>(); users.add(new User("Sergey", 25)); users.add(new User("Ivan", 30)); users.add(new User("Sergey", 20)); users.add(new User("Ivan", 25)); new SortUser().sortByAllFields(users); List<User> expected = List.of( new User("Ivan", 25), new User("Ivan", 30), new User("Sergey", 20), new User("Sergey", 25) ); assertThat(expected.equals(users), is(true)); } }
cd cd documents/github/striper-snake/run open engine_run.command open snake_run.command open http://0.0.0.0:3010
package org.egovframe.rte.fdl.cmmn.aspectj; import java.util.Date; public class Order { public int orderId; public String orderStatus; public String securityCode; public String description; public Date orderDate; public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getOrderStatus() { return orderStatus; } public void setOrderStatus(String orderStatus) { this.orderStatus = orderStatus; } public String getSecurityCode() { return securityCode; } public void setSecurityCode(String securityCode) { this.securityCode = securityCode; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
package dbr.antoine.pixviewer.features.common; /** * Created by antoine on 7/7/17. */ public interface Presenter { void register(); void unregister(); }
#!/bin/bash set -e export GTEST_COLOR=1 export CTEST_OUTPUT_ON_FAILURE=true CMAKE_LINKER_OPTS="-DCMAKE_EXE_LINKER='-fuse-ld=gold'" CMAKE_CONFIG_OPTS="-DHUNTER_CONFIGURATION_TYPES=Debug -DCMAKE_BUILD_TYPE=Debug" CMAKE_TOOLCHAIN_OPTS="-DCMAKE_TOOLCHAIN_FILE='`pwd`/tools/polly/gcc-pic-cxx17.cmake'" CMAKE_OPTS="$CMAKE_LINKER_OPTS $CMAKE_CONFIG_OPTS $CMAKE_TOOLCHAIN_OPTS" cmake -H. -B_builds $CMAKE_OPTS -DBUILD_COVERAGE=ON cmake --build _builds cmake --build _builds --target test cmake --build _builds --target gcov cmake --build _builds --target lcov gcovr -r .
package com.kafka.consumer.avro; import java.io.ByteArrayInputStream; import java.util.Map; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.BinaryDecoder; import org.apache.avro.io.DecoderFactory; import org.apache.kafka.common.serialization.Deserializer; public class AvroValueDeserializer implements Deserializer<GenericRecord> { @Override public void configure(Map<String, ?> configs, boolean isKey) { } @Override public GenericRecord deserialize(String topic, byte[] data) { GenericDatumReader<GenericRecord> datumReader = new GenericDatumReader<>(); GenericRecord record = null; try (ByteArrayInputStream bis = new ByteArrayInputStream(data)) { BinaryDecoder binaryDecoder = DecoderFactory.get().binaryDecoder(bis, null); record = datumReader.read(null, binaryDecoder); return record; } catch (Exception e) { e.printStackTrace(); } return record; } @Override public void close() { } }
<gh_stars>1-10 document.addEventListener("DOMContentLoaded", function () { $(".top-menu-tools-settingbutton").on("click", function () { var req = new XMLHttpRequest(); req.onerror = function () { }; req.onload = function () { if (req.readyState === 4) { window.location = "http://localhost/ExchangeWebsite/backend/login.php"; } }; req.open("GET","http://localhost/ExchangeWebsite/backend/auth.php?command=logout"); req.send(); }); $('.bottom-menu-item').on("click", function () { $('.bottom-menu-item').removeClass("bottom-menu-item-active"); $(this).toggleClass("bottom-menu-item-active"); }); }); function validurl(url) { try { var ok = new URL(url); return true; } catch { return false; } }
/* TITLE Rectangle and Polygone Chapter12Exercise1.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Draw a rectangle using class Rectangle (red lines) and class Polygon (blue lines). Input: - Output: Graph on screen. Author: <NAME> Date: 17. 08. 2015 */ #include <iostream> #include "Simple_window.h" int main() { try { // create a window in the center of the screen int windowHeigth = 600; int windowWidth = 600; Point centerOfScreen(x_max()/2 - windowHeigth / 2, y_max()/2 - windowWidth / 2); Simple_window sw(centerOfScreen, windowWidth, windowHeigth, "Chapter12 Exercise 1"); // draw a rectangle Point windowLeftCenter(sw.x_max()/2 - 150, sw.y_max() - 250); Graph_lib::Rectangle rect(windowLeftCenter, 300, 200); rect.set_color(Color::dark_blue); sw.attach(rect); // draw a polygon: points added clockwise Graph_lib::Polygon poly; // upper left poly.add(Point(sw.x_max()/2 - 150, sw.y_max()/2 - 250)); // upper right poly.add(Point(sw.x_max()/2 + 150, sw.y_max()/2 - 250)); // lower right poly.add(Point(sw.x_max()/2 + 150, sw.y_max()/2 - 50)); // lower left poly.add(Point(sw.x_max()/2 - 150, sw.y_max()/2 - 50)); poly.set_color(Color::dark_red); sw.attach(poly); sw.wait_for_button(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; } catch(...) { std::cerr << "Default exception!" << std::endl; } }
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { AgenciesRoutingModule } from './agencies-routing.module'; import { AgenciesComponent } from './agencies.component'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { NgxPaginationModule } from 'ngx-pagination'; import { NgSelectModule } from '@ng-select/ng-select'; import { RatingModule } from 'ng-starrating'; import { EditAgencyComponent } from '../../modals/edit-agency/edit-agency.component'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { EditAgencyModule } from '../../modals/edit-agency/edit-agency.module'; import {SharedModule} from '../../modals/shared.module'; import {RatingsReviewComponent} from '../../modals/ratings-review/ratings-review.component'; @NgModule({ declarations: [AgenciesComponent], imports: [ CommonModule, AgenciesRoutingModule, ReactiveFormsModule, FormsModule, NgxPaginationModule, NgSelectModule, SharedModule, RatingModule, EditAgencyModule, NgbModule.forRoot(), ], entryComponents: [EditAgencyComponent, RatingsReviewComponent] }) export class AgenciesModule { }
Object.defineProperty(exports, "__esModule", { value: true }); var lie_ts_1 = require("lie-ts"); exports.Promise = (function () { return typeof window !== "undefined" && window["Promise"] ? window["Promise"] : typeof global !== "undefined" && global["Promise"] ? global["Promise"] : lie_ts_1.Promise; })(); /** * Object.assign, but better. * * @param {*} obj * @returns */ exports._assign = function (obj) { return obj ? JSON.parse(JSON.stringify(obj)) : null; }; /** * Quickly and efficiently fire asyncrounous operations in sequence, returns once all operations complete. * * @param {any[]} items * @param {(item: any, i: number, next: (result?: any) => void) => void} callback * @returns {Promise<any[]>} */ exports.fastCHAIN = function (items, callback) { return new exports.Promise(function (res, rej) { if (!items || !items.length) { res([]); return; } var results = []; var step = function () { if (results.length < items.length) { callback(items[results.length], results.length, function (result) { results.push(result); lie_ts_1.setFast(step); }); } else { res(results); } }; step(); }); }; /** * Quickly and efficiently fire asyncrounous operations in parallel, returns once any operation completes. * * @param {any[]} items * @param {(item: any, i: number, next: (result?: any) => void) => void} callback * @returns {Promise<any[]>} */ exports.fastRACE = function (items, callback) { return new exports.Promise(function (res, rej) { if (!items || !items.length) { res([]); return; } var resolved = false; var counter = 0; var step = function () { if (counter < items.length) { callback(items[counter], counter, function (result) { if (!resolved) { resolved = true; res([result]); } }); counter++; step(); } }; step(); }); }; /** * Quickly and efficiently fire asyncrounous operations in parallel, returns once all operations are complete. * * @param {any[]} items * @param {(item: any, i: number, done: (result?: any) => void) => void} callback * @returns {Promise<any[]>} */ exports.fastALL = function (items, callback) { return exports.Promise.all((items || []).map(function (item, i) { return new exports.Promise(function (res, rej) { callback(item, i, function (result) { res(result); }); }); })); }; var ua = typeof window === "undefined" ? "" : (navigator.userAgent || ""); // Detects iOS device OR Safari running on desktop exports.isSafari = ua.length === 0 ? false : (/^((?!chrome|android).)*safari/i.test(ua)) || (/iPad|iPhone|iPod/.test(ua) && !window["MSStream"]); // Detect Edge or Internet Explorer exports.isMSBrowser = ua.length === 0 ? false : ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0 || ua.indexOf("Edge/") > 0; // Detect Android Device exports.isAndroid = /Android/.test(ua); /** * Generate a random 16 bit number using strongest crypto available. * * @returns {number} */ exports.random16Bits = function () { if (typeof crypto === "undefined") { return Math.round(Math.random() * Math.pow(2, 16)); // Less random fallback. } else { if (crypto.getRandomValues) { // Browser crypto var buf = new Uint16Array(1); crypto.getRandomValues(buf); return buf[0]; } else if (typeof global !== "undefined" && global._crypto.randomBytes) { // NodeJS crypto return global._crypto.randomBytes(2).reduce(function (prev, cur) { return cur * prev; }); } else { return Math.round(Math.random() * Math.pow(2, 16)); // Less random fallback. } } }; /** * Generate a TimeID for use in the database. * * @param {boolean} [ms] * @returns {string} */ exports.timeid = function (ms) { var time = Math.round((new Date().getTime()) / (ms ? 1 : 1000)).toString(); while (time.length < (ms ? 13 : 10)) { time = "0" + time; } return time + "-" + (exports.random16Bits() + exports.random16Bits()).toString(16); }; /** * See if two arrays intersect. * * @param {any[]} arr1 * @param {any[]} arr2 * @returns {boolean} */ exports.intersect = function (arr1, arr2) { if (!arr1 || !arr2) return false; if (!arr1.length || !arr2.length) return false; return (arr1 || []).filter(function (item) { return (arr2 || []).indexOf(item) !== -1; }).length > 0; }; /** * Generates a valid V4 UUID using the strongest crypto available. * * @returns {string} */ exports.uuid = function () { var r, s, b = ""; return [b, b, b, b, b, b, b, b].reduce(function (prev, cur, i) { r = exports.random16Bits(); s = (i === 3 ? 4 : (i === 4 ? (r % 16 & 0x3 | 0x8).toString(16) : b)); r = r.toString(16); while (r.length < 4) r = "0" + r; return prev + ([2, 3, 4, 5].indexOf(i) > -1 ? "-" : b) + (s + r).slice(0, 4); }, b); }; var idTypes = { "int": function (value) { return value; }, "uuid": exports.uuid, "timeId": function () { return exports.timeid(); }, "timeIdms": function () { return exports.timeid(true); } }; /** * A quick and dirty hashing function, turns a string into a md5 style hash. * stolen from https://github.com/darkskyapp/string-hash * * @param {string} str * @returns {string} */ exports.hash = function (str) { var hash = 5381, i = str.length; while (i) { hash = (hash * 33) ^ str.charCodeAt(--i); } return (hash >>> 0).toString(16); }; /** * Generate a row ID given the primary key type. * * @param {string} primaryKeyType * @param {number} [incrimentValue] * @returns {*} */ exports.generateID = function (primaryKeyType, incrimentValue) { return idTypes[primaryKeyType] ? idTypes[primaryKeyType](incrimentValue || 1) : ""; }; /** * Clean the arguments from an object given an array of arguments and their types. * * @param {string[]} argDeclarations * @param {StdObject<any>} args * @returns {StdObject<any>} */ exports.cleanArgs = function (argDeclarations, args) { var a = {}; var i = argDeclarations.length; while (i--) { var k2 = argDeclarations[i].split(":"); if (k2.length > 1) { a[k2[0]] = exports.cast(k2[1], args[k2[0]] || undefined); } else { a[k2[0]] = args[k2[0]] || undefined; } } return a; }; /** * Determine if a given value is a javascript object or not. Exludes Arrays, Functions, Null, Undefined, etc. * * @param {*} val * @returns {boolean} */ exports.isObject = function (val) { return Object.prototype.toString.call(val) === "[object Object]"; }; /** * Cast a javascript variable to a given type. Supports typescript primitives and more specific types. * * @param {string} type * @param {*} [val] * @returns {*} */ exports.cast = function (type, val) { if (type === "any" || type === "blob") return val; var t = typeof val; if (t === "undefined" || val === null) { return val; } var entityMap = { "&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;", "`": "&#x60;", "=": "&#x3D;" }; var types = function (type, val) { switch (type) { case "safestr": return types("string", val).replace(/[&<>"'`=\/]/gmi, function (s) { return entityMap[s]; }); case "int": return (t !== "number" || val % 1 !== 0) ? parseInt(val || 0) : val; case "number": case "float": return t !== "number" ? parseFloat(val || 0) : val; case "any[]": case "array": return Array.isArray(val) ? val : []; case "uuid": case "timeId": case "timeIdms": case "string": return t !== "string" ? String(val) : val; case "object": case "obj": case "map": return exports.isObject(val) ? val : {}; case "boolean": case "bool": return val === true; } return val; }; var newVal = types(String(type || "").toLowerCase(), val); if (type.indexOf("[]") !== -1) { var arrayOf_1 = type.slice(0, type.lastIndexOf("[]")); return (val || []).map(function (v) { return exports.cast(arrayOf_1, v); }); } else if (newVal !== undefined) { if (["int", "float", "number"].indexOf(type) > -1) { return isNaN(newVal) ? 0 : newVal; } else { return newVal; } } return undefined; }; /** * Insert a value into a sorted array, efficiently gaurantees records are sorted on insert. * * @param {any[]} arr * @param {*} value * @param {number} [startVal] * @param {number} [endVal] * @returns {any[]} */ exports.sortedInsert = function (arr, value, startVal, endVal) { if (arr.length) { arr.splice(exports.binarySearch(arr, value), 0, value); return arr; } else { arr.push(value); return arr; } }; /** * Given a sorted array and a value, find where that value fits into the array. * * @param {any[]} arr * @param {*} value * @param {number} [startVal] * @param {number} [endVal] * @returns {number} */ exports.binarySearch = function (arr, value, startVal, endVal) { var length = arr.length; var start = startVal || 0; var end = endVal !== undefined ? endVal : length - 1; if (length === 0) { return 0; } if (value > arr[end]) { return end + 1; } if (value < arr[start]) { return start; } if (start >= end) { return 0; } var m = start + Math.floor((end - start) / 2); if (value < arr[m]) { return exports.binarySearch(arr, value, start, m - 1); } if (value > arr[m]) { return exports.binarySearch(arr, value, m + 1, end); } return 0; }; /** * Quickly removes duplicates from a sorted array. * * @param {any[]} arr * @returns {any[]} */ exports.removeDuplicates = function (arr) { if (!arr.length) return []; var newarr = [arr[0]]; for (var i = 1; i < arr.length; i++) { if (arr[i] !== arr[i - 1]) newarr.push(arr[i]); } return newarr; }; /** * Recursively freeze a javascript object to prevent it from being modified. * * @param {*} obj * @returns */ exports.deepFreeze = function (obj) { Object.getOwnPropertyNames(obj || {}).forEach(function (name) { var prop = obj[name]; if (typeof prop === "object" && prop !== null) { obj[name] = exports.deepFreeze(prop); } }); // Freeze self (no-op if already frozen) return Object.freeze(obj); }; var objectPathCache = {}; /** * Take an object and a string describing a path like "value.length" or "val[length]" and safely get that value in the object. * * @param {string} pathQuery * @param {*} object * @param {boolean} [ignoreFirstPath] * @returns {*} */ exports.objQuery = function (pathQuery, object, ignoreFirstPath) { var val; var safeGet = function (getPath, pathIdx, object) { if (!getPath[pathIdx] || !object) return object; return safeGet(getPath, pathIdx + 1, object[getPath[pathIdx]]); }; var cacheKey = pathQuery + (ignoreFirstPath ? "1" : "0"); // cached path arrays, skips subsequent identical path requests. if (objectPathCache[cacheKey]) { return safeGet(objectPathCache[cacheKey], 0, object); } var path = []; // need to turn path into array of strings, ie value[hey][there].length => [value, hey, there, length]; path = pathQuery.indexOf("[") > -1 ? // handle complex mix of dots and brackets like "users.value[meta][value].length" [].concat.apply([], pathQuery.split(".").map(function (v) { return v.match(/([^\[]+)|\[([^\]]+)\]\[/gmi) || v; })).map(function (v) { return v.replace(/\[|\]/gmi, ""); }) : // handle simple dot paths like "users.meta.value.length" pathQuery.split("."); // handle joins where each row is defined as table.column if (ignoreFirstPath) { var firstPath = path.shift() + "." + path.shift(); path.unshift(firstPath); } objectPathCache[cacheKey] = path; return safeGet(objectPathCache[cacheKey], 0, object); };
#!/bin/bash -f xv_path="/opt/Xilinx/Vivado/2015.3" ExecStep() { "$@" RETVAL=$? if [ $RETVAL -ne 0 ] then exit $RETVAL fi } ExecStep $xv_path/bin/xelab -wto e3a711b46ac549c798dc1c692e5c281e -m64 --debug typical --relax --mt 8 --maxdelay -L xil_defaultlib -L simprims_ver -L secureip --snapshot fourBitCLASim_time_impl -transport_int_delays -pulse_r 0 -pulse_int_r 0 xil_defaultlib.fourBitCLASim xil_defaultlib.glbl -log elaborate.log
<gh_stars>1-10 name "btsync" maintainer "<NAME>" maintainer_email "<EMAIL>" license "GPL 3.0" description "Installs/Configures Bittorrent P2P Synchronization Service" long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version "0.1" %w{ ubuntu debian }.each do |os| supports os end attribute "btsync/bootstrap", :display_name => "Bootstrap server for Btsync", :description => "True if this machine is the seeder for the torrent", :type => 'string', :default => "false"
#!/usr/bin/env bats load test_helper @test "autoon: file with explicity entered env" { rm -f ./.envirius run nv autoon test_env1 assert_success # file should be created [ -e ./.envirius ] # file should content environment name assert_equal "test_env1" "`cat ./.envirius`" rm ./.envirius } @test "autoon: show help if env not activated, file not created" { rm -f ./.envirius run nv autoon assert_success # file should not be created [ ! -e ./.envirius ] [ "${lines[0]}" = "`nv_bold Usage`: nv autoon [<env-name>]" ] [ "${lines[1]}" = "`nv_bold Description`: Mark current directory for environment auto activating" ] [ "${lines[2]}" = " If environment's name is not entered then used current" ] [ "${lines[3]}" = " (active) environment. If environment is not activated" ] [ "${lines[4]}" = " then environment's name is required." ] rm -f ./.envirius } @test "autoon: file with activated environment name" { rm -f ./.envirius nv mk empty_env nv on empty_env --same-shell nv autoon # file should be created [ -e ./.envirius ] # file should content environment name assert_equal "empty_env" "`cat ./.envirius`" rm ./.envirius }
//dependencies const express = require("express"); const path = require("path"); const fs = require("fs"); //create express server const app = express(); //sets initial port for listeners const PORT = process.env.PORT || 8000; const database = require("./db/db.json"); const { dirname } = require("path"); // Sets up the Express app to handle data parsing app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(express.static("public")); // * GET `/notes` - Should return the `notes.html` file. app.get("/notes", function(req, res){ res.sendFile(path.join(__dirname, "./public/notes.html")) }) // //* GET `/api/notes` - Should read the `db.json` file and return all saved notes as JSON. app.get("/api/notes", function(req, res) { return res.json(database); }); app.get("/api/notes/:id", function(req, res) { let savedNotes = JSON.parse(fs.readFileSync(database, "utf8")); res.json(savedNotes[Number(req.params.id)]); }); //* GET `*` - Should return the `index.html` file app.get("*", function(req,res){ res.sendFile(path.join(__dirname, "./public/index.html")) }) // * POST `/api/notes` - Should receive a new note to save on the request body, // add it to the `db.json` file, and then return the new note to the client. app.post("/api/notes",function (req,res) { let newNote = req.body; let newNoteId = database.length newNote.id = newNoteId database.push(newNote) fs.writeFile("./db/db.json", JSON.stringify(database), function (err) { if (err) { return console.log(err); } console.log("Note saved to db.json. Content: ", newNote); }); res.json(newNote) }) //* DELETE `/api/notes/:id` - Should receive a query parameter containing the id of a note to delete. //This means you'll need to find a way to give each note a unique `id` when it's saved. //In order to delete a note, you'll need to read all notes from the `db.json` file, //remove the note with the given `id` property, and then rewrite the notes to the `db.json` file. app.delete("/api/notes/:id", function (req, res) { // request to delete note by id. for (let i = 0; i < database.length; i++) { if (database[i].id == req.params.id) { // Splice takes i position, and then deletes the 1 note. database.splice(i, 1); break; } } // Write the db.json file again. fs.writeFileSync("./db/db.json", JSON.stringify(database), function (err) { if (err) { return console.log(err); } console.log("Your note was deleted!"); }); res.json(database); }); // Starts the server to begin listening // ============================================================= app.listen(PORT, function () { console.log("App listening on PORT " + PORT); });
# Runs prior to every test setup() { # Load our script file. source ./src/scripts/install.sh } @test '1: test CPU detection' { # Mock environment variables or functions by exporting them (after the script has been sourced) # export PARAM_TO="World" # Capture the output of our "Greet" function result=$(get_cpu) [ "$result" == "amd64" ] } @test '2: test Arch detection' { result=$(get_arch) [ "$result" == "linux" ] }
# Stop and exit on error set -e VERSION="1.3.0" cd .. sed 's/$VERSION/'$VERSION'/g' tools/README.template.md > README.md # Generate documentation dub --build=docs mkdir docs/$VERSION mv docs/weather_forecast.html docs/$VERSION/index.html git add docs/$VERSION/ # Create release git commit -a -m "Release $VERSION" git push # Create and push tag git tag v$VERSION -m "Release $VERSION" git push --tags
#!/usr/bin/env bash # # Created by vcernomschi on 10/06/2015 # path=$(cd $(dirname $0); pwd -P) npm=`which npm` eslint=`which eslint` tslint=`which tslint` if [ -z ${eslint} ]; then ${npm} -g install eslint fi if [ -z ${tslint} ]; then ${npm} -g install tslint fi if [ -f ${path}/../.git/hooks/pre-commit ]; then cp ${path}/../.git/hooks/pre-commit ${path}/../.git/hooks/pre-commit_$(date +%F-%H%M%S).bak fi cp ${path}/pre-commit ${path}/../.git/hooks/.
/* * Copyright (c) 2021 Target Brands, Inc. All rights reserved. * Use of this source code is governed by the LICENSE file in this repository. */ context('Deployment', () => { context('server returning deployment', () => { beforeEach(() => { cy.server(); cy.route( 'GET', '*api/v1/secrets/native/repo/github/octocat/password*', 'fixture:secret_repo.json', ); cy.route( 'POST', '*api/v1/deployments/github/octocat', 'fixture:deployment.json', ); cy.login('/github/octocat/add-deployment'); }); it('Add Parameter button should be disabled', () => { cy.get('[data-test=add-parameter-button]') .should('exist') .should('not.be.enabled') .contains('Add'); }); it('Add Parameter should work as intended', () => { cy.get('[data-test=parameters-list]') .should('exist') .children() .first() .should('contain.text', 'No Parameters defined'); cy.get('[data-test=parameter-key-input]').should('exist').type('key1'); cy.get('[data-test=parameter-value-input]').should('exist').type('val1'); cy.get('[data-test=add-parameter-button]') .should('exist') .should('be.enabled') .contains('Add') .click(); it('toast should show', () => { cy.get('[data-test=alerts]').should('exist').contains('Success'); }); cy.get('[data-test=parameters-list]') .should('exist') .children() .first() .children() .first() .should('contain.text', 'key1=val1'); cy.get('[data-test=parameter-key-input]') .should('exist') .should('have.value', ''); cy.get('[data-test=parameter-value-input]') .should('exist') .should('have.value', ''); }); }); });
<reponame>jloh02/valorant-chat-client export const GAME_MODE: Map<string, string> = new Map([ ["", "Custom"], ["ggteam", "Escalation"], ["onefa", "Replication"], ["Spikerush", "Spike Rush"], ]); export const SCREEN_DEFAULTS = { mainWidth: 1200, mainHeight: 800, minWidth: 750, minHeight: 500, }; export const LOCKFILE_POLLING_RATE = 5000; //in ms export const NOTIFICATION_TIMEOUT = 5000; //in ms
<gh_stars>0 #include "GuildInfoManager.h" #include <Core/Resource/Resource.h> namespace Lunia { namespace XRated { namespace Database { namespace Info { void GuildInfoManager::Load(bool xml) { Resource::SerializerStreamReader reader; if (xml == true) { reader = Resource::ResourceSystemInstance().CreateSerializerXmlStreamReader(L"Database/Guild/GuildInfo.xml"); } else { reader = Resource::ResourceSystemInstance().CreateSerializerStructuredBinaryStreamReader(L"Database/GuildInfo.b"); } reader->Read(L"General", general); reader->Read(L"LevelInfos", levelInfos); reader->Read(L"RankInfos", rankInfos); } void GuildInfoManager::Save(bool xml) { Resource::SerializerStreamWriter writer; if (xml == true) { writer = Resource::ResourceSystemInstance().CreateSerializerXmlStreamWriter(L"Database/Guild/GuildInfo.xml"); } else { writer = Resource::ResourceSystemInstance().CreateSerializerStructuredBinaryStreamWriter(L"Database/GuildInfo.b"); } writer->Write(L"General", general); writer->Write(L"LevelInfos", levelInfos); writer->Write(L"RankInfos", rankInfos); } void GuildInfoManager::Init(bool xml) { Load(xml); } const GuildInfo::Level* GuildInfoManager::GetLevelInfo(uint8 level) const { if (level - 1 < 0) { LoggerInstance().Exception(L"Invalid Guild Level - Under 1"); } if (levelInfos.size() > level - 1) { return &(levelInfos.at(level - 1)); } return NULL; } const GuildInfo::Rank* GuildInfoManager::GetRankInfo(uint32 rank) const { if (rankInfos.empty()) return NULL; RankInfoList::const_iterator iter = rankInfos.find(rank); if (iter != rankInfos.end()) { return &iter->second; } return NULL; } const GuildInfo::General& GuildInfoManager::GetGeneral() const { return general; } uint32 GuildInfoManager::GetMaxGuildPoint(uint8 currentLevel) const { if (currentLevel - 1 < 0) { LoggerInstance().Exception(L"Invalid Guild Level - Under 1"); return 0; } return general.MaxGuildPoints.at(static_cast<int>(currentLevel) - 1); } uint32 GuildInfoManager::GetMaxGuildUserPerLevel(uint8 currentLevel) const { if (static_cast<int>(currentLevel) - 1 < 0) { LoggerInstance().Exception(L"Invalid Guild Level - Under 1"); return 0; } if (static_cast<uint32>(currentLevel) > general.MaxGuildUser.size()) { LoggerInstance().Exception(L"Invalid Guild Level - {0}", currentLevel); return 0; } return general.MaxGuildUser.at(static_cast<int>(currentLevel) - 1); } std::pair<bool, uint32> GuildInfoManager::GetNextLevelExp(uint8 currentLevel) const { if (currentLevel - 1 < 0) { LoggerInstance().Exception(L"Invalid Guild Level - Under 1"); return std::pair<bool, uint32>(false, 0); } std::pair<bool, uint32> returnValue(false, 0); if (general.LevelUpExps.size() > currentLevel - 1) { returnValue.first = true; returnValue.second = general.LevelUpExps.at(currentLevel - 1); return returnValue; } return returnValue; } DateTime GuildInfoManager::GetGuildUserExpAddTime(DateTime startTime, float userExp) const { if (general.MinuteForExp > userExp) { uint32 needMinute = general.MinuteForExp - static_cast<uint32>(userExp); startTime.Add(DateTime::Unit::Second, needMinute * 60); return startTime; } return DateTime::Now(); } float GuildInfoManager::GetShopDiscountRate(uint16 rank) const { if (rank < 1 || rank > general.DiscountRate.size()) return 1.0f; return general.DiscountRate.at(rank - 1); } std::pair<float, uint32> GuildInfoManager::CalculdateCurrentUserExp(DateTime start, DateTime currentTime, float oldPlayTime) const { static uint32 secondForExp = general.MinuteForExp * 60; float playTime = CalculatePlayTime(start, currentTime, oldPlayTime); std::pair<float, uint32> result; result.first = float((uint64)playTime % secondForExp); result.second = (uint32)(playTime / secondForExp); return result; } float GuildInfoManager::CalculatePlayTime(DateTime start, DateTime now, float oldPlayTime) { const static int secondOfDay = 60 * 60 * 24; oldPlayTime += (float)now.GetTime().GetCumulatedSec() - (float)start.GetTime().GetCumulatedSec(); oldPlayTime += (float)(now.GetDate().GetCumulatedDay() - start.GetDate().GetCumulatedDay()) * secondOfDay; return oldPlayTime; } void GuildInfoManager::SortSellItemList() { { //Level levelToSellItems.clear(); levelToSellItems.resize(levelInfos.size()); LevelToSellItemList::iterator levelToSellItemIter = levelToSellItems.begin(); LevelInfoList::const_iterator iter = levelInfos.begin(); LevelInfoList::const_iterator end = levelInfos.end(); while (iter != end) { SellItemLists& items = *levelToSellItemIter; ShopInfo::CategoryList::const_iterator categoryIter = (*iter).ShopCategorys.begin(); ShopInfo::CategoryList::const_iterator categoryEnd = (*iter).ShopCategorys.end(); while (categoryIter != categoryEnd) { ShopInfo::Category::ItemList::const_iterator itemIter = (*categoryIter).Items.begin(); ShopInfo::Category::ItemList::const_iterator itemEnd = (*categoryIter).Items.end(); while (itemIter != itemEnd) { items.push_back((*itemIter).ItemHash); ++itemIter; } ++categoryIter; } ++iter; ++levelToSellItemIter; } } { //Rank rankToSellItems.clear(); RankInfoList::const_iterator rankIter = rankInfos.begin(); RankInfoList::const_iterator rankEnd = rankInfos.end(); while (rankIter != rankEnd) { SellItemLists items; ShopInfo::CategoryList::const_iterator categoryIter = rankIter->second.ShopCategorys.begin(); ShopInfo::CategoryList::const_iterator categoryEnd = rankIter->second.ShopCategorys.end(); while (categoryIter != categoryEnd) { ShopInfo::Category::ItemList::const_iterator itemIter = (*categoryIter).Items.begin(); ShopInfo::Category::ItemList::const_iterator itemEnd = (*categoryIter).Items.end(); while (itemIter != itemEnd) { items.push_back((*itemIter).ItemHash); ++itemIter; } ++categoryIter; } rankToSellItems[rankIter->first] = items; ++rankIter; } } } bool GuildInfoManager::IsShopItem(uint8 guildLevel, uint32 guildRank, uint32 hash) const { if (levelToSellItems.size() > guildLevel - 1) { const SellItemLists& sellItems = (levelToSellItems.at(guildLevel - 1)); SellItemLists::const_iterator iter = std::find(sellItems.begin(), sellItems.end(), hash); if (iter != sellItems.end()) { return true; } } if (rankToSellItems.empty()) return false; RankToSellItemList::const_iterator iter = rankToSellItems.find(guildRank); if (iter != rankToSellItems.end()) { SellItemLists::const_iterator itemIter = std::find(iter->second.begin(), iter->second.end(), hash); if (itemIter != iter->second.end()) { return true; } } return false; } } } } }
<gh_stars>10-100 import { Injectable } from '@angular/core'; import { CrudService } from '../../../shared/services/crud.service'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class OptionValuesService { constructor( private crudService: CrudService ) { } getListOfOptionValues(params): Observable<any> { return this.crudService.get(`/v1/private/product/options/values`, params); } deleteOptionValue(id): Observable<any> { return this.crudService.delete(`/v1/private/product/option/value/${id}`); } getOptionValueById(id): Observable<any> { const params = { lang: '_all' }; return this.crudService.get(`/v1/private/product/option/value/${id}`, params); } createOptionValue(option): Observable<any> { return this.crudService.post(`/v1/private/product/option/value`, option); } updateOptionValue(id, option): Observable<any> { return this.crudService.put(`/v1/private/product/option/value/${id}`, option); } checkOptionValueCode(code): Observable<any> { const params = { 'code': code, }; return this.crudService.get(`/v1/private/product/option/value/unique`, params); } }
<reponame>fourier11/interview<filename>javapractice/sort/MergeSortFromWiki.java package sort; import java.util.Arrays; /** * 归并排序,更加简洁的版本,就是临时变量有点多 */ public class MergeSortFromWiki { private static void mergeSortRecursive(int[] arr, int[] result, int start, int end) { if (start >= end) { return; } int len = end - start; int mid = start + len / 2; int start1 = start; int end1 = mid; int start2 = mid + 1; int end2 = end; mergeSortRecursive(arr, result, start1, end1); mergeSortRecursive(arr, result, start2, end2); int k = start; while (start1 <= end1 && start2 <= end2) { result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; } while (start1 <= end1) { result[k++] = arr[start1++]; } while (start2 <= end2) { result[k++] = arr[start2++]; } for (k = start; k <= end; k++) { arr[k] = result[k]; } } public static void mergeSort(int[] arr) { int len = arr.length; // 这里result变量命名有点问题,实际结果仍然是原数组 int[] result = new int[len]; mergeSortRecursive(arr, result, 0, len - 1); } public static void main(String[] args) { int[] arr = new int[] { 1, 4, 8, 2, 55, 3, 4, 8, 6, 4, 0, 11, 34, 90, 23, 54, 77, 9, 2, 9, 4, 10 }; mergeSort(arr); System.out.println(Arrays.toString(arr)); } }
TERMUX_PKG_HOMEPAGE=https://www.gnupg.org/related_software/libassuan/ TERMUX_PKG_DESCRIPTION="Library implementing the Assuan IPC protocol used between most newer GnuPG components" TERMUX_PKG_LICENSE="GPL-2.0" TERMUX_PKG_VERSION=2.5.4 TERMUX_PKG_SRCURL=https://www.gnupg.org/ftp/gcrypt/libassuan/libassuan-${TERMUX_PKG_VERSION}.tar.bz2 TERMUX_PKG_SHA256=c080ee96b3bd519edd696cfcebdecf19a3952189178db9887be713ccbcb5fbf0 TERMUX_PKG_DEPENDS="libgpg-error" TERMUX_PKG_BREAKS="libassuan-dev" TERMUX_PKG_REPLACES="libassuan-dev"
# other imports import numpy as np import os from tqdm import tqdm from sklearn.metrics import confusion_matrix import h5py # torch imports import torch import torch.nn.functional as F import torch.utils.data from s3dis_dataset import DatasetTrainVal as Dataset import lightconvpoint.utils.metrics as metrics from lightconvpoint.utils import get_network # SACRED from sacred import Experiment from sacred import SETTINGS from sacred.utils import apply_backspaces_and_linefeeds from sacred.config import save_config_file SETTINGS.CAPTURE_MODE = "sys" # for tqdm ex = Experiment("S3DIS") ex.captured_out_filter = apply_backspaces_and_linefeeds # for tqdm ex.add_config("s3dis.yaml") ###### class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' # wrap blue / green def wblue(str): return bcolors.OKBLUE+str+bcolors.ENDC def wgreen(str): return bcolors.OKGREEN+str+bcolors.ENDC @ex.automain def main(_run, _config): print(_config) savedir_root = _config['training']['savedir'] device = torch.device(_config['misc']['device']) # save the config file os.makedirs(savedir_root, exist_ok=True) save_config_file(eval(str(_config)), os.path.join( savedir_root, "config.yaml")) # create the path to data rootdir = os.path.join(_config['dataset']['datasetdir'], _config['dataset']['dataset']) N_CLASSES = 13 # create the network print("Creating the network...", end="", flush=True) def network_function(): return get_network( _config["network"]["model"], in_channels=3, out_channels=N_CLASSES, backend_conv=_config["network"]["backend_conv"], backend_search=_config["network"]["backend_search"], config=_config ) net = network_function() net.to(device) print("Done") # create the filelits (train / val) according to area print("Create filelist...", end="") filelist_train = [] filelist_test = [] for area_idx in range(1 ,7): folder = os.path.join(rootdir, f"Area_{area_idx}") datasets = [os.path.join(f"Area_{area_idx}", dataset) for dataset in os.listdir(folder)] if area_idx == _config['dataset']['area']: filelist_test = filelist_test + datasets else: filelist_train = filelist_train + datasets filelist_train.sort() filelist_test.sort() print(f"done, {len(filelist_train)} train files, {len(filelist_test)} test files") print("Creating dataloader and optimizer...", end="", flush=True) ds = Dataset(filelist_train, rootdir, training=True, block_size=_config['dataset']['pillar_size'], npoints=_config['dataset']['npoints'], iteration_number=_config['training']['batchsize']*_config['training']['epoch_iter'], jitter=_config['training']['jitter'], scaling_param=_config['training']['scaling_param'], rgb_dropout=_config['training']['rgb_dropout'], rgb=_config['training']['rgb'], network_function=network_function) train_loader = torch.utils.data.DataLoader(ds, batch_size=_config['training']['batchsize'], shuffle=True, num_workers=_config['misc']['threads'] ) ds_val = Dataset(filelist_test, rootdir, training=False, block_size=_config['dataset']['pillar_size'], npoints=_config['dataset']['npoints'], iteration_number=_config['training']['batchsize']*100, rgb=_config['training']['rgb'], network_function=network_function) test_loader = torch.utils.data.DataLoader(ds_val, batch_size=_config['training']['batchsize'], shuffle=False, num_workers=_config['misc']['threads'] ) print("Done") print("Creating optimizer...", end="", flush=True) optimizer = torch.optim.Adam(net.parameters(), lr=_config['training']['lr_start']) print("done") print("Weights") if _config['training']['weights']: # computed on the train set if _config['area']==1: weights = torch.Tensor([0.7615, 0.3969, 0.4546, 0.2727, 6.7376, 4.1650, 1.6270, 3.2547, 2.3042, 2.1289, 17.7709, 1.1333, 6.7996]) elif _config['area']==2: weights = torch.Tensor([ 0.7366, 0.4071, 0.4866, 0.2736, 4.0031, 3.3682, 1.6507, 2.5912, 2.0347, 3.0115, 17.2155, 1.1268, 5.9607]) elif _config['area']==3: weights = torch.Tensor([0.7499, 0.3991, 0.4636, 0.2758, 4.4585, 3.7786, 1.6039, 2.9821, 2.2443, 2.1931, 20.1374, 1.2197, 6.2980]) elif _config['area']==4: weights = torch.Tensor([0.7543, 0.3921, 0.4622, 0.2818, 3.8026, 3.8313, 1.7192, 3.0418, 2.1892, 2.1827, 19.7227, 1.2032, 5.5455]) elif _config['area']==5: weights = torch.Tensor([0.7045, 0.4006, 0.4644, 0.2815, 3.1686, 3.6080, 1.4001, 3.6230, 2.3671, 1.8859, 15.7542, 1.6276, 6.0848]) elif _config['area']==6: weights = torch.Tensor([0.7508, 0.3955, 0.4576, 0.2720, 5.9368, 4.1264, 1.6474, 3.0501, 2.5304, 2.2307, 18.0194, 1.1336, 6.5966]) else: raise Exception('Unknown area') else: weights = torch.ones(N_CLASSES).float() weights=weights.to(device) print("Done") # iterate over epochs for epoch in range(0, _config['training']['epoch_nbr']): ####### # training net.train() count=0 train_loss = 0 cm = np.zeros((N_CLASSES, N_CLASSES)) t = tqdm(train_loader, ncols=100, desc="Epoch {}".format(epoch), disable=_config['misc']['disable_tqdm']) for data in t: pts = data['pts'].to(device) features = data['features'].to(device) seg = data['target'].to(device) net_ids = data["net_indices"] net_pts = data["net_support"] for i in range(len(net_ids)): net_ids[i] = net_ids[i].to(device) for i in range(len(net_pts)): net_pts[i] = net_pts[i].to(device) optimizer.zero_grad() outputs = net(features, pts, indices=net_ids, support_points=net_pts) loss = F.cross_entropy(outputs, seg, weight=weights) loss.backward() optimizer.step() output_np = np.argmax(outputs.cpu().detach().numpy(), axis=1).copy() target_np = seg.cpu().numpy().copy() cm_ = confusion_matrix(target_np.ravel(), output_np.ravel(), labels=list(range(N_CLASSES))) cm += cm_ oa = f"{metrics.stats_overall_accuracy(cm):.5f}" aa = f"{metrics.stats_accuracy_per_class(cm)[0]:.5f}" iou = f"{metrics.stats_iou_per_class(cm)[0]:.5f}" train_loss += loss.detach().cpu().item() t.set_postfix(OA=wblue(oa), AA=wblue(aa), IOU=wblue(iou), LOSS=wblue(f"{train_loss/cm.sum():.4e}")) ###### ## validation net.eval() cm_test = np.zeros((N_CLASSES, N_CLASSES)) test_loss = 0 t = tqdm(test_loader, ncols=80, desc=" Test epoch {}".format(epoch), disable=_config['misc']['disable_tqdm']) with torch.no_grad(): for data in t: pts = data['pts'].to(device) features = data['features'].to(device) seg = data['target'].to(device) net_ids = data["net_indices"] net_pts = data["net_support"] for i in range(len(net_ids)): net_ids[i] = net_ids[i].to(device) for i in range(len(net_pts)): net_pts[i] = net_pts[i].to(device) outputs = net(features, pts, indices=net_ids, support_points=net_pts) loss = F.cross_entropy(outputs, seg) output_np = np.argmax(outputs.cpu().detach().numpy(), axis=1).copy() target_np = seg.cpu().numpy().copy() cm_ = confusion_matrix(target_np.ravel(), output_np.ravel(), labels=list(range(N_CLASSES))) cm_test += cm_ oa_val = f"{metrics.stats_overall_accuracy(cm_test):.5f}" aa_val = f"{metrics.stats_accuracy_per_class(cm_test)[0]:.5f}" iou_val = f"{metrics.stats_iou_per_class(cm_test)[0]:.5f}" test_loss += loss.detach().cpu().item() t.set_postfix(OA=wgreen(oa_val), AA=wgreen(aa_val), IOU=wgreen(iou_val), LOSS=wgreen(f"{test_loss/cm_test.sum():.4e}")) # create the root folder os.makedirs(savedir_root, exist_ok=True) # save the checkpoint torch.save({ 'epoch': epoch + 1, 'state_dict': net.state_dict(), 'optimizer' : optimizer.state_dict(), }, os.path.join(savedir_root, "checkpoint.pth")) # write the logs logs = open(os.path.join(savedir_root, "logs.txt"), "a+") logs.write(f"{epoch} {oa} {aa} {iou} {oa_val} {aa_val} {iou_val}\n") logs.close() # log train values _run.log_scalar("trainOA", oa, epoch) _run.log_scalar("trainAA", aa, epoch) _run.log_scalar("trainIoU", iou, epoch) _run.log_scalar("testOA", oa_val, epoch) _run.log_scalar("testAA", aa_val, epoch) _run.log_scalar("testAIoU", iou_val, epoch)
import axios from 'axios'; const API_URL = 'http://localhost:8000/products'; const fetchData = async() => { const response = await axios.get(API_URL); return response.data; }; const renderTable = (data) => { const table = document.createElement('table'); const headerRow = document.createElement('tr'); const columnNames = Object.keys(data[0]); columnNames.forEach(name => { const headerCell = document.createElement('th'); headerCell.textContent = name; headerRow.appendChild(headerCell); }); table.appendChild(headerRow); data.forEach(rowData => { const dataRow = document.createElement('tr'); columnNames.forEach(name => { const dataCell = document.createElement('td'); dataCell.textContent = rowData[name]; dataRow.appendChild(dataCell); }); table.appendChild(dataRow); }); return table; }; const main = async () => { const data = await fetchData(); const table = renderTable(data); document.body.appendChild(table); }; main();
class RecordingDevice: def __init__(self, can_record): self._can_record = can_record self._is_recording = False self._recorded_audio = [] def record_audio(self, duration): if self._can_record: print(f"Recording audio for {duration} seconds") self._is_recording = True # Simulate recording audio # Assume audio is recorded and stored in some format # For example, appending to a list for simplicity self._recorded_audio.append(f"Audio recorded for {duration} seconds") else: print("Device cannot record audio") def stop_recording(self): if self._is_recording: print("Recording stopped") self._is_recording = False else: print("No ongoing recording") def playback_audio(self): if self._recorded_audio: print("Playing back recorded audio:") for audio in self._recorded_audio: print(audio) else: print("No recorded audio to playback") @property def can_record(self): return self._can_record
<filename>modules/caas/api/src/main/java/io/cattle/platform/api/instance/ContainerLogsActionHandler.java package io.cattle.platform.api.instance; import com.netflix.config.DynamicStringProperty; import io.cattle.platform.archaius.util.ArchaiusUtil; import io.cattle.platform.core.constants.InstanceConstants; import io.cattle.platform.core.model.Host; import io.cattle.platform.core.model.Instance; import io.cattle.platform.docker.api.model.ContainerLogs; import io.cattle.platform.docker.api.model.HostAccess; import io.cattle.platform.docker.util.DockerUtils; import io.cattle.platform.hostapi.HostApiAccess; import io.cattle.platform.hostapi.HostApiService; import io.cattle.platform.object.ObjectManager; import io.cattle.platform.util.type.CollectionUtils; import io.github.ibuildthecloud.gdapi.request.ApiRequest; import io.github.ibuildthecloud.gdapi.request.resource.ActionHandler; import java.util.Map; public class ContainerLogsActionHandler implements ActionHandler { private static final DynamicStringProperty HOST_LOGS_PATH = ArchaiusUtil.getString("host.logs.path"); HostApiService apiService; ObjectManager objectManager; public ContainerLogsActionHandler(HostApiService apiService, ObjectManager objectManager) { super(); this.apiService = apiService; this.objectManager = objectManager; } @Override public Object perform(Object obj, ApiRequest request) { Host host = null; Instance container = null; if (obj instanceof Instance) { container = (Instance) obj; host = DockerUtils.getHostFromContainer(objectManager, container, null); } if (host == null) { return null; } ContainerLogs logs = request.proxyRequestObject(ContainerLogs.class); String dockerId = DockerUtils.getDockerIdentifier(container); Map<String, Object> data = CollectionUtils.asMap(InstanceConstants.DOCKER_CONTAINER, dockerId, "Lines", logs.getLines(), "Follow", logs.getFollow()); HostApiAccess apiAccess = apiService.getAccess(request, host.getId(), CollectionUtils.asMap("logs", data), HOST_LOGS_PATH.get()); if (apiAccess == null) { return null; } HostAccess access = new HostAccess(apiAccess.getUrl(), apiAccess.getAuthenticationToken()); return access; } }
import random rand_num = random.randint(10000, 99999) print(rand_num)
/** * There are 4 different ways to call a function * 1) fn() * 2) fn.call() * 3) fn.apply() * 4) new fn() */ function add(a, b) { return a + b; } var x = add(1,2); //-> 3 var y = add.call(null, 1, 2); //-> 3 var z = add.apply(null, [1,2]); //-> 3 var w = new add(1,2); //-> new object (discussed later)
<reponame>htruong/M5Paper_FactoryTest #include <WiFi.h> #include <ArduinoJson.h> #include <HTTPClient.h> #include <MD5Builder.h> #include "frame_feedcontent.h" #include "frame_urlreader.h" #include "../utils/urlencoder.h" #define MAX_BTN_NUM 12 void key_feedcontent_feed_cb(epdgui_args_vector_t &args) { Frame_Base *frame = new Frame_urlReader(((EPDGUI_Button*)(args[0]))->GetCustomString()); EPDGUI_PushFrame(frame); *((int*)(args[1])) = 0; log_d("%s", ((EPDGUI_Button*)(args[0]))->GetCustomString().c_str()); } void key_feedcontent_exit_cb(epdgui_args_vector_t &args) { EPDGUI_PopFrame(true); *((int*)(args[0])) = 0; } Frame_FeedContent::Frame_FeedContent(String url) { _frame_name = "Frame_FeedContent"; _url = url; uint8_t language = GetLanguage(); _canvas_title->setTextDatum(CR_DATUM); if (language == LANGUAGE_JA) { exitbtn("ホーム"); } else if (language == LANGUAGE_ZH) { exitbtn("主页"); } else { exitbtn("Back"); } _canvas_title->drawString("Items Index", 540 - 15, 34); _key_exit->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, (void *)(&_is_run)); _key_exit->Bind(EPDGUI_Button::EVENT_RELEASED, &key_feedcontent_exit_cb); } bool Frame_FeedContent::downloadFeed() { if (WiFi.status() != WL_CONNECTED) { log_e("URL %s is not cached and you're not connected to the internet, gave up.", _url.c_str()); return false; } HTTPClient http; http.begin("http://article-proxy.tnhh.net/feed/?url=" + URLEncoder::urlencode(_url)); int httpCode = http.GET(); if (httpCode == HTTP_CODE_OK) { DynamicJsonDocument doc(4096); StaticJsonDocument<200> filter; filter["items"][0]["title"] = true; filter["items"][0]["url"] = true; DeserializationError error = deserializeJson(doc, http.getStream(), DeserializationOption::Filter(filter)); if (error != DeserializationError::Ok) { log_e("URL %s cache error: %s.", _url.c_str(), error.c_str()); return false; } log_d("URL %s cached successfully.", _url.c_str()); /* char buf [1000]; serializeJson(doc["items"], buf, 10000); log_d("JSON: %s", buf); */ JsonArray RSSItems = doc["items"].as<JsonArray>(); int item_count = 0; log_d("Begin %llu, end %llu", RSSItems.begin(), RSSItems.end()); for (JsonArray::iterator it=RSSItems.begin(); it!=RSSItems.end(); ++it) { log_d("Item %llu: %s at %s", it, (*it)["title"].as<char*>(), (*it)["url"].as<char*>()); struct rssItem_t item; item.name = String((*it)["title"].as<char*>()); item.url = String((*it)["url"].as<char*>()); _feed.push_back(item); } } else { log_e("URL %s caching failed.", _url.c_str()); return false; } return true; } void Frame_FeedContent::listFeeds() { if (! downloadFeed()) { log_e ("Cannot download feed %s.", _url); return; } for(int n = 0; n < _feed.size(); n++) { if(_key_feed.size() > MAX_BTN_NUM) { break; } EPDGUI_Button *btn = new EPDGUI_Button(4, 100 + _key_feed.size() * 60, 532, 61); _key_feed.push_back(btn); btn->CanvasNormal()->fillCanvas(0); btn->CanvasNormal()->drawRect(0, 0, 532, 61, 15); btn->CanvasNormal()->setTextSize(26); btn->CanvasNormal()->setTextDatum(CL_DATUM); btn->CanvasNormal()->setTextColor(15); btn->CanvasNormal()->drawString(_feed[n].name, 47 + 13, 35); btn->SetCustomString(_feed[n].url); btn->CanvasNormal()->setTextDatum(CR_DATUM); btn->CanvasNormal()->pushImage(15, 14, 32, 32, ImageResource_item_icon_file_floder_32x32); btn->CanvasNormal()->pushImage(532 - 15 - 32, 14, 32, 32, ImageResource_item_icon_arrow_r_32x32); *(btn->CanvasPressed()) = *(btn->CanvasNormal()); btn->CanvasPressed()->ReverseColor(); btn->AddArgs(EPDGUI_Button::EVENT_RELEASED, 0, btn); btn->AddArgs(EPDGUI_Button::EVENT_RELEASED, 1, (void*)(&_is_run)); btn->Bind(EPDGUI_Button::EVENT_RELEASED, key_feedcontent_feed_cb); } } Frame_FeedContent::~Frame_FeedContent(void) { for(int i = 0; i < _key_feed.size(); i++) { delete _key_feed[i]; } } int Frame_FeedContent::init(epdgui_args_vector_t &args) { _is_run = 1; if(_key_feed.size() == 0) { listFeeds(); } M5.EPD.WriteFullGram4bpp(GetWallpaper()); _canvas_title->pushCanvas(0, 8, UPDATE_MODE_NONE); EPDGUI_AddObject(_key_exit); for(int i = 0; i < _key_feed.size(); i++) { EPDGUI_AddObject(_key_feed[i]); } return 3; }
#!/bin/bash ################################################################################################### ### Configuration ################################################################################################### VBB_LIST=( 0.0 3.0 6.0 ) # in V I_THR_LIST=( 51 100 ) # in DAC V_CASN_LIST=( 50 105 135 ) # in DAC V_CLIP_LIST=( 0 60 100 ) # in DAC V_RESETD_LIST=( 147 170 170 ) # in DAC # how many V_CASN values to process per back-bias voltage V_CASN_PER_VBB=$(echo "${#V_CASN_LIST[@]} / ${#VBB_LIST[@]}" | bc) MODE_LIST=( 0 1 ) # chip readout mode (0=triggered, 1=continuous) STROBEB_LIST=( 4 20 0 ) # continuous integration: 0, # different from 0: multiple of 25ns clock cycles TRG_FREQ_LIST=( 20000 50000 100000 200000 500000 1000000 ) # in Hz TRG_TRAIN_LENGTH=( 100 ) # number of consecutive triggers HAMEG=/dev/ttyHAMEG0 CURR=( 0.8 0.0 0.02 ) # 5V, unconnected, Vbb ################################################################################################### ################################################################################################### # setup environment / load functions ROOT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) # determine where this script is located source ${ROOT_DIR}/common/functions.sh ################################################################################################### ### determine 'run conditions' eval $(determine_run_conditions) ################################################################################################### ### execution if [ "$#" -lt 1 ] then # ask for chip ID echo "Please enter the name of the chip followed by [ENTER]:" read CHIPNAME else CHIPNAME=$1 fi # is ROOT available? check_root # create output folder FULLPATH=${ROOT_DIR}/../Data/rate_dependence_${DATE}_${GIT_INFO}${SUFFIX} create_output_folder $FULLPATH LOGFILE=${FULLPATH}/log.txt # store the chip name touch ${FULLPATH}/${CHIPNAME} # store git diff store_git_diff $FULLPATH >> $LOGFILE 2>&1 DATAPATH=${FULLPATH}/data mkdir $DATAPATH ################################################################################################### ### initialise all power supplies ################################################################################################### ${ROOT_DIR}/common/pulser.py -1.0 # deactivate pulser which could lead to an input signal above VDDA and VDDD ${ROOT_DIR}/common/hameg2030.py ${HAMEG} 0 ${CURR[@]} ################################################################################################### #### start the measurment itself ################################################################################################### i_VBB=0 for VBB in "${VBB_LIST[@]}" do # set the back-bias voltage echo "setting back-bias voltage to ${VBB}V" | tee -a $LOGFILE ${ROOT_DIR}/common/hameg2030.py ${HAMEG} 1 3 ${VBB} VBB_OLD=${VBB} sleep 1 ${ROOT_DIR}/common/hameg2030.py ${HAMEG} 4 if [ $? -eq 1 ] then echo "back-bias current too high, stopping measurement" ${ROOT_DIR}/common/hameg2030.py ${HAMEG} 4 exit 1 fi V_CLIP=${V_CLIP_LIST[${i_VBB}]} V_RESETD=${V_RESETD_LIST[${i_VBB}]} for I_THR in "${I_THR_LIST[@]}" do echo "I_THR="${I_THR}"DAC" | tee -a $LOGFILE for i_V_CASN in $(seq 0 $((${V_CASN_PER_VBB} - 1))) #for V_CASN in "${V_CASN_LIST[@]}" do V_CASN=${V_CASN_LIST[$(( i_VBB*${V_CASN_PER_VBB} + i_V_CASN ))]} V_CASN2=$(( ${V_CASN} + 12 )) echo "V_CASN="${V_CASN}"DAC" | tee -a $LOGFILE for MODE in "${MODE_LIST[@]}" do echo "READOUT MODE=$MODE" | tee -a $LOGFILE for TRG_FREQ in "${TRG_FREQ_LIST[@]}" do echo "TRG_FREQ="${TRG_FREQ}"Hz" | tee -a $LOGFILE ${ROOT_DIR}/common/pulser.py 1 ${TRG_FREQ} ${TRG_TRAIN_LENGTH} | tee -a $LOGFILE for STROBEB in "${STROBEB_LIST[@]}" do if [ "${STROBEB}" -eq 0 ] then STROBEB=$(bc <<< "40000000/${TRG_FREQ}-10" ) echo "Continuous integration mode, STROBEB="$(bc <<< "${STROBEB}*25")"ns" | tee -a $LOGFILE else echo "Fixed length STROBEB="$(bc <<< "${STROBEB}*25")"ns" | tee -a $LOGFILE fi ########################################################################### ### write config file ########################################################################### cd ${ROOT_DIR} cat <<EOF > Config.cfg # First line has to be DEVICE (Values: CHIP, TELESCOPE, MODULE, STAVE, CHIPMOSAIC) DEVICE CHIP # as of firmware version 247e0611 the DAQboard version (v2 or v3) must be defined; 0 -> v2; 1 -> v3; BOARDVERSION 1 ITHR ${I_THR} VCASN2 ${V_CASN2} VCASN ${V_CASN} VCLIP ${V_CLIP} VRESETD ${V_RESETD} IDB 29 VCASP 86 IBIAS 64 STROBEDURATION ${STROBEB} READOUTMODE ${MODE} EOF mv Config.cfg ../ CURR_DATAPATH=$(printf "$DATAPATH/VBB-%0.1f/ITHR%0.3d/VCASN%0.3d/MODE%c/TRG_FREQ%0.6d/STROBEB%0.6d" \ ${VBB} ${V_RST} ${I_THR} ${V_CASN} ${MODE} ${TRG_FREQ} ${STROBEB}) SUBFOLDER=${CURR_DATAPATH}/FHR mkdir -p ${SUBFOLDER} cp ../Config.cfg ${SUBFOLDER} ########################################################################### ### start the acquisition ########################################################################### cd ${ROOT_DIR}/../ ./test_noiseocc_ext | tee -a $LOGFILE # moving the data mv -v Data/$(ls -1tr Data | grep NoiseOccupancyExt | tail -n 1) ${SUBFOLDER} mv -v Data/$(ls -1tr Data | grep ScanConfig | tail -n 1) ${SUBFOLDER} done done done done done let i_VBB+=1 done ################################################################################################### ### power down everything ################################################################################################### ${ROOT_DIR}/common/pulser.py -1.0 # deactivate pulser which could lead to an input signal above VDDA and VDDD ${ROOT_DIR}/common/hameg2030.py ${HAMEG} 6 # turn off the PSU git checkout ${ROOT_DIR}/../Config.cfg
from torch.optim import Optimizer import math import torch import time class AdamW(Optimizer): """Implements AdamW algorithm. It has been proposed in `Fixing Weight Decay Regularization in Adam`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) .. Fixing Weight Decay Regularization in Adam: https://arxiv.org/abs/1711.05101 """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(AdamW, self).__init__(params, defaults) def __setstate__(self, state): super(AdamW, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: beta1, beta2 = group['betas'] lr, eps, amsgrad = group['lr'], group['eps'], group['amsgrad'] for p in group['params']: if p.grad is None: continue if group['weight_decay'] != 0: p.data.mul_(1. - lr * group['weight_decay']) grad = p.grad.data if grad.is_sparse: raise RuntimeError('AdamW does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if 'step' not in state: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of learning rates state['exp_avg_lr_1'] = 0. state['exp_avg_lr_2'] = 0. # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p.data) state['PopArt_rescale'] = 1. exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] if amsgrad: if not 'max_exp_avg_sq' in state: state['max_exp_avg_sq'] = torch.zeros_like(p.data) max_exp_avg_sq = state['max_exp_avg_sq'] state['step'] += 1 # We incorporate the term group['lr'] into the momentum, and define the bias_correction1 such that it respects the possibly moving group['lr'] state['exp_avg_lr_1'] = state['exp_avg_lr_1'] * beta1 + (1. - beta1) * lr state['exp_avg_lr_2'] = state['exp_avg_lr_2'] * beta2 + (1. - beta2) #bias_correction1 = state['exp_avg_lr_1'] / group['lr'] if group['lr']!=0. else 1. #1. - beta1 ** state['step'] bias_correction2 = state['exp_avg_lr_2'] # For convenience, we directly use "sqrt_bias_correction2" and "step_size" as the following sqrt_bias_correction2 = math.sqrt(bias_correction2) # when state['exp_avg_lr_1'] is zero, exp_avg should also be zero and it is trivial one_over_bias_correction1 = lr / state['exp_avg_lr_1'] if state['exp_avg_lr_1']!=0. else 0. step_size = one_over_bias_correction1 * sqrt_bias_correction2 # instead of correcting "denom" by dividing it, we put the correction factor into "step_size" and "eps" # Decay the first and second moment running average coefficient rescaling = state['PopArt_rescale'] exp_avg.mul_(beta1*rescaling).add_(grad, alpha=(1. - beta1) * lr) exp_avg_sq.mul_(beta2*rescaling**2).addcmul_(grad, grad, value=1. - beta2) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.max(max_exp_avg_sq, exp_avg_sq, out=max_exp_avg_sq) # Use the max. for normalizing running avg. of gradient denom = max_exp_avg_sq.sqrt().add_(eps * sqrt_bias_correction2) # 'eps' is first multiplied by sqrt_bias_correction2 and then divided by sqrt_bias_correction2 else: denom = exp_avg_sq.sqrt().add_(eps * sqrt_bias_correction2) p.data.addcdiv_(exp_avg, denom, value=-step_size) return loss class AdamBelief(Optimizer): """Implements AdamW algorithm. It has been proposed in `Fixing Weight Decay Regularization in Adam`_. Arguments: params (iterable): iterable of parameters to optimize or dicts defining parameter groups lr (float, optional): learning rate (default: 1e-3) betas (Tuple[float, float], optional): coefficients used for computing running averages of gradient and its square (default: (0.9, 0.999)) eps (float, optional): term added to the denominator to improve numerical stability (default: 1e-8) weight_decay (float, optional): weight decay (L2 penalty) (default: 0) .. Fixing Weight Decay Regularization in Adam: https://arxiv.org/abs/1711.05101 """ def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, amsgrad=False): if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(AdamBelief, self).__init__(params, defaults) def __setstate__(self, state): super(AdamW, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: beta1, beta2 = group['betas'] lr, eps, amsgrad = group['lr'], group['eps'], group['amsgrad'] for p in group['params']: if p.grad is None: continue if group['weight_decay'] != 0: p.data.mul_(1. - lr * group['weight_decay']) grad = p.grad.data if grad.is_sparse: raise RuntimeError('AdamW does not support sparse gradients, please consider SparseAdam instead') state = self.state[p] # State initialization if 'step' not in state: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of learning rates state['exp_avg_lr_1'] = 0. state['exp_avg_lr_2'] = 0. # Exponential moving average of squared gradient values state['exp_avg_var'] = torch.zeros_like(p.data) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_var'] = torch.zeros_like(p.data) exp_avg, exp_avg_var = state['exp_avg'], state['exp_avg_var'] if amsgrad: if not 'max_exp_avg_var' in state: state['max_exp_avg_var'] = torch.zeros_like(p.data) max_exp_avg_var = state['max_exp_avg_var'] state['step'] += 1 # We define the bias_correction1 such that it respects the possibly moving "group['lr']" state['exp_avg_lr_1'] = state['exp_avg_lr_1'] * beta1 + (1. - beta1) * lr state['exp_avg_lr_2'] = state['exp_avg_lr_2'] * beta2 + (1. - beta2) #bias_correction1 = state['exp_avg_lr_1'] / group['lr'] if group['lr']!=0. else 1. #1. - beta1 ** state['step'] bias_correction2 = state['exp_avg_lr_2'] # For convenience, we directly use "sqrt_bias_correction2" and "step_size" as the following sqrt_bias_correction2 = math.sqrt(bias_correction2) # when state['exp_avg_lr_1'] is zero, exp_avg should also be zero and it is trivial one_over_bias_correction1 = lr / state['exp_avg_lr_1'] if state['exp_avg_lr_1']!=0. else 0. step_size = one_over_bias_correction1 * sqrt_bias_correction2 # instead of correcting "denom" by dividing it, we put the correction factor into "step_size" and "eps" # Decay the first and second moment running average coefficient diff = grad - exp_avg exp_avg.mul_(beta1).add_(grad, alpha=(1. - beta1)) exp_avg_var.mul_(beta2).addcmul_(diff, diff, value=1. - beta2) if amsgrad: # Maintains the maximum of all 2nd moment running avg. till now torch.max(max_exp_avg_var, exp_avg_var, out=max_exp_avg_var) # Use the max. for normalizing running avg. of gradient denom = max_exp_avg_var.sqrt().add_(eps * sqrt_bias_correction2) # 'eps' is first multiplied by sqrt_bias_correction2 and then divided by sqrt_bias_correction2 else: denom = exp_avg_var.sqrt().add_(eps * sqrt_bias_correction2) p.data.addcdiv_(exp_avg, denom, value= - step_size * lr) return loss class LaProp(Optimizer): def __init__(self, params, lr=4e-4, betas=(0.9, 0.999), eps=1e-15, weight_decay=0., amsgrad=False, centered=False): self.centered = centered if not 0.0 <= lr: raise ValueError("Invalid learning rate: {}".format(lr)) if not 0.0 <= eps: raise ValueError("Invalid epsilon value: {}".format(eps)) if not 0.0 <= betas[0] < 1.0: raise ValueError("Invalid beta parameter at index 0: {}".format(betas[0])) if not 0.0 <= betas[1] < 1.0: raise ValueError("Invalid beta parameter at index 1: {}".format(betas[1])) if not 0.0 <= weight_decay: raise ValueError("Invalid weight_decay value: {}".format(weight_decay)) defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad) super(LaProp, self).__init__(params, defaults) def __setstate__(self, state): super(LaProp, self).__setstate__(state) for group in self.param_groups: group.setdefault('amsgrad', False) def step(self, closure=None): """Performs a single optimization step. Arguments: closure (callable, optional): A closure that reevaluates the model and returns the loss. """ loss = None if closure is not None: loss = closure() for group in self.param_groups: for p in group['params']: if p.grad is None: continue if group['weight_decay'] != 0: p.data.mul_(1. - group['lr'] * group['weight_decay']) grad = p.grad.data if grad.is_sparse: raise RuntimeError('LaProp does not support sparse gradients, please consider SparseAdam instead') amsgrad = group['amsgrad'] state = self.state[p] # State initialization if 'step' not in state: state['step'] = 0 # Exponential moving average of gradient values state['exp_avg'] = torch.zeros_like(p.data) # Exponential moving average of learning rates state['exp_avg_lr_1'] = 0. state['exp_avg_lr_2'] = 0. # Exponential moving average of squared gradient values state['exp_avg_sq'] = torch.zeros_like(p.data) state['exp_mean_avg_sq'] = torch.zeros_like(p.data) if amsgrad: # Maintains max of all exp. moving avg. of sq. grad. values state['max_exp_avg_sq'] = torch.zeros_like(p.data) state['PopArt_rescale'] = 1. state['Momentum_rescale'] = 1. exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq'] if self.centered: exp_mean_avg_sq = state['exp_mean_avg_sq'] if amsgrad: max_exp_avg_sq = state['max_exp_avg_sq'] beta1, beta2 = group['betas'] state['step'] += 1 state['exp_avg_lr_1'] = state['exp_avg_lr_1'] * beta1 + (1. - beta1) * group['lr'] state['exp_avg_lr_2'] = state['exp_avg_lr_2'] * beta2 + (1. - beta2) #bias_correction1 = state['exp_avg_lr_1'] / group['lr'] if group['lr']!=0. else 1. #1 - beta1 ** state['step'] bias_correction2 = state['exp_avg_lr_2'] # For convenience, we directly use "sqrt_bias_correction2" and "step_size" as the following sqrt_bias_correction2 = math.sqrt(bias_correction2) # when state['exp_avg_lr_1'] is zero, exp_avg should also be zero and it is trivial one_over_bias_correction1 = group['lr'] / state['exp_avg_lr_1'] if state['exp_avg_lr_1']!=0. else 0. step_size = one_over_bias_correction1 # Decay the first and second moment running average coefficient rescaling = state['PopArt_rescale'] exp_avg_sq.mul_(beta2*rescaling**2).addcmul_(grad, grad, value=1. - beta2) denom = exp_avg_sq if self.centered: exp_mean_avg_sq.mul_(beta2*rescaling).add_(grad, alpha=1. - beta2) if state['step']>5: denom = denom.addcmul(exp_mean_avg_sq, exp_mean_avg_sq, value=-1.) if amsgrad: if not (self.centered and state['step']<=5): # Maintains the maximum of all (centered) 2nd moment running avg. till now torch.max(max_exp_avg_sq, denom, out=max_exp_avg_sq) # Use the max. for normalizing running avg. of gradient denom = max_exp_avg_sq denom = denom.sqrt().add_(group['eps'] * sqrt_bias_correction2) # instead of correcting "denom" by dividing it, we put the correction factor into "exp_avg" and "eps" momentum_rescaling = state['Momentum_rescale'] exp_avg.mul_(beta1*momentum_rescaling).addcdiv_(grad, denom, value=(1. - beta1) * group['lr'] * sqrt_bias_correction2) p.data.add_(exp_avg, alpha = -step_size) return loss
<filename>C2CRIBuildDir/projects/C2C-RI/src/RIGUI/src/org/fhwa/c2cri/gui/wizard/testconfig/edit/page/SelectRequirementsPage.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.fhwa.c2cri.gui.wizard.testconfig.edit.page; import com.github.cjwizard.WizardPage; import com.github.cjwizard.WizardSettings; import java.awt.KeyboardFocusManager; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.TableColumnModel; import javax.swing.table.TableRowSorter; import org.fhwa.c2cri.domain.testmodel.TestConfigurationController; import org.fhwa.c2cri.gui.SelectionFlagEditor; import org.fhwa.c2cri.gui.SelectionFlagListener; import org.fhwa.c2cri.gui.SelectionFlagRenderer; import org.fhwa.c2cri.gui.TextAreaRenderer; import org.fhwa.c2cri.gui.wizard.C2CRIWizardPage; import org.fhwa.c2cri.testmodel.DefaultLayerParameters; import org.fhwa.c2cri.testmodel.ProjectRequirementsInterface; import org.fhwa.c2cri.testmodel.Requirement; import org.fhwa.c2cri.testmodel.UserNeedsInterface; /** * * @author TransCore ITS, LLC */ public class SelectRequirementsPage extends C2CRIWizardPage implements java.awt.event.ActionListener { /** * The sorter2. */ private TableRowSorter<RequirementsTableModel> sorter2; private String currentNeed; private boolean appLayerSelected; TestConfigurationController controller; /** * Creates new form SelectNeedsPage */ public SelectRequirementsPage(String title, String description, TestConfigurationController controller, boolean appLayerSelected, String selectedNeed) { super(title, description); initComponents(); this.controller = controller; initRequirementsPanel(standardRequirementsTable, parametersTable, appLayerSelected ? controller.getAppLayerParams() : controller.getInfoLayerParams(), selectedNeed); this.appLayerSelected = appLayerSelected; currentNeed = selectedNeed; requirementsClearAllButton.addActionListener(this); } /** * Inits the parameters panel. * * Pre-Conditions: N/A Post-Conditions: N/A * * @param standardNeedsTable the standard needs table * @param standardRequirementsTable the standard requirements table * @param parametersTable the parameters table * @param layerParams the layer params */ private void initRequirementsPanel(final JTable standardRequirementsTable, final JTable parametersTable, final DefaultLayerParameters layerParams, final String needId) { System.out.println(" Loading the Parameter Panel ....... "); //Ensure the tables do not currently have sorters activated standardRequirementsTable.setRowSorter(null); parametersTable.setRowSorter(null); RequirementsTableModel requirementsTableModel = new RequirementsTableModel(layerParams.getNrtm(), needId); OtherRequirementsTableModel otherRequirementsTableModel = new OtherRequirementsTableModel(layerParams.getNrtm(), needId); standardRequirementsTable.setModel(requirementsTableModel); parametersTable.setModel(otherRequirementsTableModel); // To prevent tabbing between individual cells of the table disable the // functions in the tables. standardRequirementsTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); standardRequirementsTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); standardRequirementsTable.setFocusCycleRoot(false); parametersTable.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null); parametersTable.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null); parametersTable.setFocusCycleRoot(false); requirementsTableModel.fireTableStructureChanged(); otherRequirementsTableModel.fireTableStructureChanged(); requirementsTableModel.fireTableDataChanged(); otherRequirementsTableModel.fireTableDataChanged(); SelectionFlagListener unselectedNeedListener = new SelectionFlagListener() { @Override public void flagValueSetUpdate(int tableRow) { standardRequirementsTable.setEnabled(true); parametersTable.setEnabled(true); } @Override public void flagValueClearedUpdate(int tableModelRow) { String deselectedNeed = layerParams.getNrtm().getUserNeeds().needs.get(tableModelRow).getTitle(); List<String> selectedRequirementsList = new ArrayList<String>(); // Gather a list of optional selected requirements associated with this need for (Requirement thisProjectRequirement : layerParams.getNrtm().getUserNeeds().getNeed(deselectedNeed).getProjectRequirements().requirements) { if ((thisProjectRequirement.getFlagValue()) && (!thisProjectRequirement.getType().equals("M") && !thisProjectRequirement.getType().equals("Mandatory"))) { thisProjectRequirement.setFlagValue(false); ((RequirementsTableModel) standardRequirementsTable.getModel()).fireTableDataChanged(); } } int currentRow = standardRequirementsTable.getSelectionModel().getLeadSelectionIndex(); standardRequirementsTable.getSelectionModel().removeSelectionInterval(currentRow, currentRow); standardRequirementsTable.setEnabled(false); parametersTable.setEnabled(false); } }; SelectionFlagEditor infoLayerFlagEditor = new SelectionFlagEditor(UserNeedsInterface.type_Header); infoLayerFlagEditor.registerSelectionFlagListener(unselectedNeedListener); //When selection changes, provide user with row numbers for //both view and model. //When selection changes, provide user with row numbers for //both view and model. standardRequirementsTable.getSelectionModel().addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { int viewRow = standardRequirementsTable.getSelectedRow(); if (parametersTable.isEditing()) { parametersTable.getCellEditor().cancelCellEditing(); } if (viewRow < 0) { //Selection got filtered away. } else { Boolean requirementSelected = (Boolean) standardRequirementsTable.getValueAt(standardRequirementsTable.getSelectedRow(), standardRequirementsTable.getColumn(ProjectRequirementsInterface.flagValue_Header).getModelIndex()); if (requirementSelected) { parametersTable.setEnabled(true); } else { parametersTable.setEnabled(false); } } } }); otherRequirementsTableModel.setRequirementListSelectionTable(standardRequirementsTable); standardRequirementsTable.getSelectionModel().addListSelectionListener(otherRequirementsTableModel); sorter2 = new TableRowSorter<RequirementsTableModel>(requirementsTableModel); SelectionFlagListener projectRequirementSelectedListener = new SelectionFlagListener() { @Override public void flagValueSetUpdate(int tableRow) { parametersTable.setEnabled(true); } @Override public void flagValueClearedUpdate(int tableModelRow) { if (parametersTable.isEditing()) { parametersTable.getCellEditor().cancelCellEditing(); } parametersTable.setEnabled(false); } }; SelectionFlagEditor projectRequirementsFlagEditor = new SelectionFlagEditor(ProjectRequirementsInterface.type_Header); projectRequirementsFlagEditor.registerSelectionFlagListener(projectRequirementSelectedListener); standardRequirementsTable.getColumn(ProjectRequirementsInterface.flagValue_Header).setCellRenderer(new SelectionFlagRenderer(ProjectRequirementsInterface.type_Header)); standardRequirementsTable.getColumn(ProjectRequirementsInterface.flagValue_Header).setCellEditor(projectRequirementsFlagEditor); TableColumnModel cmodel = standardRequirementsTable.getColumnModel(); TextAreaRenderer textAreaRenderer = new TextAreaRenderer(); cmodel.getColumn(RequirementsTableModel.Text_Col).setCellRenderer(textAreaRenderer); TableColumnModel parameterModel = parametersTable.getColumnModel(); TextAreaRenderer textAreaParameters = new TextAreaRenderer(); parameterModel.getColumn(OtherRequirementsTableModel.Text_Col).setCellRenderer(textAreaParameters); requirementsTableModel.fireTableDataChanged(); otherRequirementsTableModel.fireTableDataChanged(); } @Override public void actionPerformed(ActionEvent arg0) { for (Requirement theRequirement : appLayerSelected ? controller.getAppLayerParams().getNrtm().getUserNeeds().getNeed(currentNeed).getProjectRequirements().requirements : controller.getInfoLayerParams().getNrtm().getUserNeeds().getNeed(currentNeed).getProjectRequirements().requirements) { if ((!theRequirement.getType().equals("M")) && (!theRequirement.getType().equals("Mandatory"))) { theRequirement.setFlagValue(false); } } ((RequirementsTableModel) standardRequirementsTable.getModel()).fireTableDataChanged(); } @Override public void rendering(List<WizardPage> path, WizardSettings settings) { super.rendering(path, settings); ((RequirementsTableModel) standardRequirementsTable.getModel()).fireTableDataChanged(); } @Override public boolean isCheckRequiredBeforeCancel() { return true; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { testParametersPanel = new javax.swing.JPanel(); parametersScrollPane = new javax.swing.JScrollPane(); parametersTable = new javax.swing.JTable(); selectRequirementsPanel = new javax.swing.JPanel(); standardRequirementsScrollPane = new javax.swing.JScrollPane(); standardRequirementsTable = new javax.swing.JTable(); jPanel2 = new javax.swing.JPanel(); requirementsClearAllButton = new javax.swing.JButton(); testParametersPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Test Parameters")); testParametersPanel.setPreferredSize(new java.awt.Dimension(678, 99)); parametersScrollPane.setPreferredSize(new java.awt.Dimension(452, 0)); parametersTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"SubscriptionDelay", "The maximum time (in milliseconds to await a response", "1000"} }, new String [] { "Parameter", "Description", "Value" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.Object.class }; boolean[] canEdit = new boolean [] { false, false, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); parametersTable.setToolTipText("Set information layer standard parameters."); parametersTable.setFillsViewportHeight(true); parametersScrollPane.setViewportView(parametersTable); javax.swing.GroupLayout testParametersPanelLayout = new javax.swing.GroupLayout(testParametersPanel); testParametersPanel.setLayout(testParametersPanelLayout); testParametersPanelLayout.setHorizontalGroup( testParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(testParametersPanelLayout.createSequentialGroup() .addContainerGap() .addComponent(parametersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE) .addContainerGap()) ); testParametersPanelLayout.setVerticalGroup( testParametersPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(testParametersPanelLayout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(parametersScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE) .addContainerGap()) ); selectRequirementsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Select Requirements")); selectRequirementsPanel.setPreferredSize(new java.awt.Dimension(678, 142)); standardRequirementsScrollPane.setViewportBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); standardRequirementsScrollPane.setPreferredSize(new java.awt.Dimension(452, 110)); standardRequirementsTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {"3.3.1.1.1", "Subscription Request", "M", new Boolean(true)}, {"3.3.1.1.2", "DMS Inventory", "O", new Boolean(true)}, {"3.3.1.1.3", "CCTV Control", "M", new Boolean(true)}, {"3.3.1.1.4", "FE Update", "O", null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Requirement", "Description", "Project Requirements", "Selected" } ) { Class[] types = new Class [] { java.lang.Object.class, java.lang.Object.class, java.lang.Object.class, java.lang.Boolean.class }; boolean[] canEdit = new boolean [] { false, false, false, true }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit [columnIndex]; } }); standardRequirementsTable.setToolTipText("Selection information layer standard requirements."); standardRequirementsTable.setFillsViewportHeight(true); standardRequirementsTable.setMinimumSize(new java.awt.Dimension(60, 60)); standardRequirementsScrollPane.setViewportView(standardRequirementsTable); jPanel2.setPreferredSize(new java.awt.Dimension(100, 23)); requirementsClearAllButton.setText("Clear Optional"); requirementsClearAllButton.setToolTipText("De-select all optional Requirements"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(227, Short.MAX_VALUE) .addComponent(requirementsClearAllButton) .addContainerGap(246, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(requirementsClearAllButton) ); javax.swing.GroupLayout selectRequirementsPanelLayout = new javax.swing.GroupLayout(selectRequirementsPanel); selectRequirementsPanel.setLayout(selectRequirementsPanelLayout); selectRequirementsPanelLayout.setHorizontalGroup( selectRequirementsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, selectRequirementsPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(selectRequirementsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(standardRequirementsScrollPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 576, Short.MAX_VALUE)) .addContainerGap()) ); selectRequirementsPanelLayout.setVerticalGroup( selectRequirementsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, selectRequirementsPanelLayout.createSequentialGroup() .addComponent(standardRequirementsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(testParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 608, Short.MAX_VALUE) .addComponent(selectRequirementsPanel, javax.swing.GroupLayout.Alignment.TRAILING, 0, 608, Short.MAX_VALUE)) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(selectRequirementsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 219, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(testParametersPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel jPanel2; protected javax.swing.JScrollPane parametersScrollPane; protected javax.swing.JTable parametersTable; protected javax.swing.JButton requirementsClearAllButton; private javax.swing.JPanel selectRequirementsPanel; private javax.swing.JScrollPane standardRequirementsScrollPane; protected javax.swing.JTable standardRequirementsTable; private javax.swing.JPanel testParametersPanel; // End of variables declaration//GEN-END:variables }
<reponame>knofler/app<filename>app/containers/Delete/saga.js /* eslint-disable comma-dangle */ /* eslint-disable no-console */ /* * * DELETE saga * */ import { all, call, put, takeLatest } from "redux-saga/effects"; import { socket } from "utils/socketio-client"; import { DELETE_CONST_POST } from "./constants"; import { deleteActionPostSuccess, deleteActionPostError } from "./actions"; const herokuAPIURL = "https://aframework-api.herokuapp.com"; const model = "/api/books"; const getUrl = process.env.API_URL || herokuAPIURL; const url = getUrl + model; console.log("process.env.API_URL", process.env.API_URL); console.log("herokuAPIURL is", herokuAPIURL); console.log("url is ", url); // Load Functions on Event Change function* deleteSagaPost() { yield takeLatest(DELETE_CONST_POST, fetchPostDelete); } function* fetchPostDelete(action) { try { // CRUD_CONST_DELETE event action and api call console.log("DELETE_CONST_POST constant's action in saga is:: ", action); console.log( "DELETE_CONST_POST constant's action.id in saga is:: ", action.id ); console.log( "DELETE_CONST_POST constant's action.model in saga is:: ", action.model ); if (action.model !== undefined && action.id !== undefined) { const deleteUrl = `${getUrl}/api/${action.model}/${action.id}`; console.log("deleteUrl:", deleteUrl); // const response = yield call(fetch, deleteUrl, { method: "DELETE", headers: { Accept: "application/json", "Content-Type": "application/json" } }); const responseBody = yield response.json(); console.log("responseBody of DELETE_CONST_POST in saga is", responseBody); window.localStorage.setItem("delete-data", JSON.stringify(responseBody)); yield put(deleteActionPostSuccess(responseBody)); socket.emit("delete_data", responseBody); } } catch (error) { yield put(deleteActionPostError(error)); } } // Individual exports for testing export default function* deleteSaga() { // See example in containers/HomePage/saga.js yield all([deleteSagaPost()]); }
#!/bin/bash COVER_PROFILE=coverage.txt echo "mode: set" > $COVER_PROFILE FAIL=0 go test -cover ./polly/cli || FAIL=1 if [ "$FAIL" -ne 0 ]; then exit 1 fi COVER_PKG="github.com/emccode/polly" go test -coverpkg=$COVER_PKG -coverprofile=profile.out ./test || FAIL=1 if [ -f profile.out ]; then cat profile.out | grep -v "mode: set" >> $COVER_PROFILE rm -f profile.out fi if [ "$FAIL" -ne 0 ]; then exit 1 fi if [ "$1" = "main" ]; then rm -f $COVER_PROFILE exit 0 fi for DIR in $(find . -type d \ -not -path '*/.*' \ -not -path './.git*' \ -not -path '*/_*' \ -not -path './vendor/*' \ -not -path './polly/*' \ -not -path './core' \ -not -path '.'); do if ls $DIR/*.go &> /dev/null; then go test -coverprofile=profile.out $DIR || FAIL=1 if [ -f profile.out ]; then cat profile.out | grep -v "mode: set" >> $COVER_PROFILE rm -f profile.out fi fi done if [ -n "$COVERALLS" -a "$FAIL" -eq "0" ]; then goveralls -v -coverprofile=$COVER_PROFILE fi if [ -n "$CODECOV" -a "$FAIL" -eq "0" ]; then bash <(curl -s https://codecov.io/bash) fi rm -f $COVER_PROFILE exit $FAIL
import * as azmaps from "azure-maps-control"; import { PieChartMarkerOptions } from './PieChartMarkerOptions'; import { ExtendedHtmlMarker } from './extentions/ExtendedHtmlMarker'; /** * A class for creating Pie Charts as HTML Markers on a map. */ export class PieChartMarker extends azmaps.HtmlMarker implements ExtendedHtmlMarker { /******************** * Private Properties ********************/ private _options = <PieChartMarkerOptions>{ values: [], radius: 40, colors: ['#d7191c', '#fdae61', '#ffffbf', '#abdda4', '#2b83ba'], fillColor: 'transparent', strokeWidth: 0, strokeColor: '#666666', innerRadius: 0 }; /** The total of all values. */ private _total: number = 0; /** Additional colors to use when enough haven't been specified. */ public static _moreColors = []; /******************** * Constructor ********************/ /** * Creates an HTML Marker in the shape of a pie chart. * @param options Options for rendering the Pie Chart marker. */ constructor(options: PieChartMarkerOptions) { super(options); super.setOptions({ htmlContent: document.createElement('div'), pixelOffset: [0, 0], anchor: 'center' }); this.setOptions(options); } /******************** * Public Methods ********************/ /** ID of the marker. */ public id: string; /** Any additional properties that you want to store with the marker. */ public properties: any = {}; /** * Gets the total value of all slices summed togehter. * @returns The total value of all slices summed togehter. */ public getTotalValue(): number { return this._total; } /** * Gets the value of a slice of the pie based on it's index. * @param idx The index of the slice. * @returns The value of a slice of the pie based on it's index. */ public getSliceValue(idx: number): number { const vals = this._options.values; return (idx >= 0 && idx < vals.length) ? vals[idx] : 0; } /** * Gets the percentage value of a slice of the pie based on it's index. * @param idx The index of the slice. * @returns The percentage value of a slice of the pie based on it's index. */ public getSlicePercentage(idx: number): number { const self = this; return (self._total > 0) ? Math.round(self.getSliceValue(idx) / self._total * 10000) / 100 : 0; } /** * Gets the options of the pie chart marker. * @returns The options of the pie chart marker. */ public getOptions(): PieChartMarkerOptions { return Object.assign({}, super.getOptions(), this._options); } /** * Sets the options of the pie chart marker. * @param options The options to set on the marker. */ public setOptions(options: PieChartMarkerOptions): void { const self = this; const opt = self._options; const stringify = JSON.stringify; let rerender = false; if (options.radius && options.radius > 0 && options.radius != opt.radius) { opt.radius = options.radius; rerender = true; } if (options.innerRadius >= 0 && options.innerRadius != opt.innerRadius) { opt.innerRadius = options.innerRadius; rerender = true; } if (options.colors && stringify(options.colors) !== stringify(opt.colors)) { opt.colors = options.colors; rerender = true; } if (options.fillColor && stringify(options.fillColor) !== stringify(opt.fillColor)) { opt.fillColor = options.fillColor; rerender = true; } if (options.strokeColor && options.strokeColor !== opt.strokeColor) { opt.strokeColor = options.strokeColor; rerender = true; } if (options.strokeWidth >= 0 && options.strokeWidth != opt.strokeWidth) { opt.strokeWidth = options.strokeWidth; rerender = true; } if (options.tooltipCallback !== undefined && opt.tooltipCallback != options.tooltipCallback) { opt.tooltipCallback = options.tooltipCallback; rerender = true; } if (options.values && stringify(options.values) !== stringify(opt.values)) { opt.values = options.values; rerender = true; } if (options.text !== undefined && options.text !== opt.text) { //opt.text = options.text; super.setOptions({ text: options.text }); rerender = true; } if (options.textClassName !== undefined && options.textClassName !== opt.textClassName) { opt.textClassName = options.textClassName; rerender = true; } if (rerender) { self._render(); } super.setOptions(options); } /******************** * Private Methods ********************/ /** * Method that generates the SVG pie chart for the marker. */ private _render() { const self = this; const opt = self._options; const data = opt.values; const radius = opt.radius; let startAngle = 0, angle = 0; if (data) { self._total = data.reduce((a, b) => { return a + b; }, 0); //Ensure that there are enough colors defined. const moreColors = PieChartMarker._moreColors; const random = Math.random; const round = Math.round; let mIdx = 0; while (data.length > opt.colors.length) { //Generate additional random colors, but try and stagger them such that there is a good variation between agenct colors. if (moreColors.length < data.length) { moreColors.push(`hsl(${round(random() * 360)},${round(random() * 20) + 70}%,${round(random() * 40) + 30}%)`); } //Grab the next additional color from the global pallet. opt.colors.push(moreColors[mIdx]); mIdx++; } //Origin for cx/cy const o = radius + opt.strokeWidth; const svg = [`<svg xmlns="http://www.w3.org/2000/svg" width="${2 * o}px" height="${2 * o}px">`]; let tooltip = ''; let maskId: string; if (opt.innerRadius > 0 && opt.innerRadius <= opt.radius) { maskId = 'piechart-innercircle-' + round(random() * 10000000); svg.push(`<defs><mask id="${maskId}"><rect width="100%" height="100%" fill="white"/><circle r="${opt.innerRadius}" cx="${o}" cy="${o}" fill="black"/></mask></defs> <circle r="${opt.innerRadius}" cx="${o}" cy="${o}" style="fill:${opt.fillColor};stroke:${opt.strokeColor};stroke-width:${opt.strokeWidth * 2}px;"/>`); } if (self._total > 0) { const ttc = opt.tooltipCallback; const ratio = Math.PI * 2 / self._total; for (let i = 0; i < data.length; i++) { angle = ratio * data[i]; if (ttc) { tooltip = ttc(self, i); } const c = (i < opt.colors.length) ? opt.colors[i] : moreColors[i]; svg.push(self._createSlice(o, o, radius, startAngle, angle, c, tooltip, maskId)); startAngle += angle; } } const text = self.getOptions().text; if (text) { svg.push(`<text x="${o}" y="${(o + 7)}" style="font-size:16px;font-family:arial;fill:#000;font-weight:bold;" class="${opt.textClassName || ''}" text-anchor="middle">${text}</text>`); } svg.push('</svg>'); (<HTMLDivElement>super.getOptions().htmlContent).innerHTML = svg.join(''); } } /** * Generates the SVG path for an arc slice of a pie. * @param cx Center x-origin of the arc. * @param cy Center y-origin of the arc. * @param r Radius of arc. * @param startAngle The start angle of the arc (0 = up, PI/2 = right, PI = down, 3/2 PI = left) * @param angle The angle width of the arc. * @param fillColor The fill color of the path. * @param tooltip The tooltip text to display when hovered. */ private _createSlice(cx: number, cy: number, r: number, startAngle: number, angle: number, fillColor: string, tooltip: string, maskId: string): string { const opt = this._options; const pi = Math.PI; let mask = ''; if(maskId){ mask = ` mask="url(#${maskId}"`; } if (angle > 2 * pi * 0.99) { //If the shape is nearly a complete circle, create a circle instead of an arc. return `<circle r="${r}" cx="${cx}" cy="${cy}" style="fill:${fillColor};stroke:${opt.strokeColor};stroke-width:${opt.strokeWidth}px;"${mask}><title>${tooltip}</title></circle>`; } const sin = Math.sin; const cos = Math.cos; const x1 = cx + r * sin(startAngle); const y1 = cy - r * cos(startAngle); const x2 = cx + r * sin(startAngle + angle); const y2 = cy - r * cos(startAngle + angle); const x21 = cx + opt.innerRadius * sin(startAngle); const y21 = cy - opt.innerRadius * cos(startAngle); const x22 = cx + opt.innerRadius * sin(startAngle + angle); const y22 = cy - opt.innerRadius * cos(startAngle + angle); //Flag for when arcs are larger than 180 degrees in radians. let big = 0; if (angle > pi) { big = 1; } return `<path d="M${cx} ${cy} L ${x1} ${y1} A ${r},${r} 0 ${big} 1 ${x2} ${y2}z" style="fill:${fillColor};stroke:${opt.strokeColor};stroke-width:${opt.strokeWidth}px;"${mask}><title>${tooltip}</title></path>`; } }
def distinct_subsequences(s): n = len(s) dp = [[0 for i in range(n+1)] for i in range(n+1)] for i in range(n+1): dp[i][0] = 1 for i in range(1, n+1): for j in range(1, n+1): if s[i-1] == s[j-1] and i != j: dp[i][j] = dp[i-1][j-1] + dp[i-1][j] else: dp[i][j] = dp[i-1][j] return dp[n][n]
#!/bin/sh if [ ! $# -ge 1 ] || [ ! $# -le 3 ]; then echo "Usage: $0 NAME (SECURITY_PROFILE) (CERTFILE)" exit 1 fi CLIENT_NAME=$1 CLIENT_SECURITY_PROFILE=$2 [ -z "$CLIENT_SECURITY_PROFILE" ] && CLIENT_SECURITY_PROFILE="idsc:BASE_SECURITY_PROFILE" CLIENT_CERT="keys/clients/$CLIENT_NAME.cert" if [ -n "$3" ]; then [ ! -f "$3" ] && (echo "Cert not found"; exit 1) cert_format="DER" openssl x509 -noout -in "$3" 2>/dev/null && cert_format="PEM" openssl x509 -inform "$cert_format" -in "$3" -text > "$CLIENT_CERT" else openssl req -newkey rsa:2048 -new -batch -nodes -x509 -days 3650 -text -keyout "keys/clients/${CLIENT_NAME}.key" -out "$CLIENT_CERT" fi SKI="$(grep -A1 "Subject Key Identifier" "$CLIENT_CERT" | tail -n 1 | tr -d ' ')" AKI="$(grep -A1 "Authority Key Identifier" "$CLIENT_CERT" | tail -n 1 | tr -d ' ')" CLIENT_ID="$SKI:$AKI" CLIENT_CERT_SHA="$(openssl x509 -in "$CLIENT_CERT" -noout -sha256 -fingerprint | tr '[:upper:]' '[:lower:]' | tr -d : | sed 's/.*=//')" cat >> config/clients.yml <<EOF - client_id: $CLIENT_ID client_name: $CLIENT_NAME grant_types: client_credentials token_endpoint_auth_method: private_key_jwt scope: idsc:IDS_CONNECTOR_ATTRIBUTES_ALL attributes: - key: idsc value: IDS_CONNECTOR_ATTRIBUTES_ALL - key: securityProfile value: $CLIENT_SECURITY_PROFILE - key: referringConnector value: http://${CLIENT_NAME}.demo - key: "@type" value: ids:DatPayload - key: "@context" value: https://w3id.org/idsa/contexts/context.jsonld - key: transportCertsSha256 value: $CLIENT_CERT_SHA import_certfile: $CLIENT_CERT EOF
#!/bin/bash QUALITY=$(pylint --rcfile=pylint.rc transport_proxy.py yandex_transport_core/*.py | grep -oP '(?<=Your code has been rated at).*?(?=/)') echo "Quality : $QUALITY" echo '"Code quality"' > code_quality.csv echo $QUALITY >> code_quality.csv SIZE_BYTES=$(docker image inspect owlsoul/ytproxy:dev --format='{{.Size}}') SIZE_MB=$(( $SIZE_BYTES / 1024 / 1024)) echo "Docker image size (MB): $SIZE_MB" echo '"Docker image size"' > docker_image_size.csv echo $SIZE_MB >> docker_image_size.csv
#!/bin/sh remove_directory="/usr/local/foglamp/python/foglamp/plugins/north/omf/" # Remove dir if exists if [ -d "${remove_directory}" ]; then echo "FogLAMP package update: removing 'omf' Python north plugin ..." rm -rf "${remove_directory}" # Check if [ -d "${remove_directory}" ]; then echo "ERROR: FogLAMP plugin 'omf' not removed in '${remove_directory}'" exit 1 else echo "FogLAMP plugin 'omf' removed in '${remove_directory}'" fi fi # The dummy C plugin has been renamed to random, remove the old plugin dummy_directory="/usr/local/foglamp/plugins/south/dummy" if [ -d $dummy_directory ]; then echo "FogLAMP package update: removing 'dummy' South plugin" rm -rf $dummy_directory fi # The omf C plugin has been renamed to PI_Server, remove the old plugin omf_directory="/usr/local/foglamp/plugins/north/omf" if [ -d $omf_directory ]; then echo "FogLAMP package update: removing 'omf' North plugin" rm -rf $omf_directory fi
<filename>packages/web/src/components/Community/ModTools/RulesPane/RuleForm/RuleForm.test.tsx<gh_stars>0 import React from 'react'; import Modal from 'components/Modal/Modal'; import { render, fireEvent, cleanup, waitForElement, } from '@testing-library/react'; import RuleForm from './RuleForm'; describe('<RuleForm />', () => { const nameValue = 'testValue'; const descriptionValue = 'testDescription'; const cancelHandler = jest.fn(); const addRuleHandler = jest.fn(); const editRuleHandler = jest.fn(); const type = 'Add'; const editRule = { name: 'Edit', description: 'Rule', scope: 'Posts Only', date: 'date', community: 'communityId', user: 'userId', _id: 'testId', }; const { container, getByTestId, getByText, getByPlaceholderText } = render( <RuleForm cancelHandler={cancelHandler} editRule={editRule} addRuleHandler={addRuleHandler} editRuleHandler={editRuleHandler} type={type} />, ); beforeEach(async () => { console.log(container); const nameInput = await waitForElement(() => getByPlaceholderText('Name')); fireEvent.change(nameInput, { target: { value: nameValue } }); const descriptionInput = await waitForElement(() => getByPlaceholderText('Description'), ); fireEvent.change(descriptionInput, { target: { value: descriptionValue } }); const scopeButton = getByText('Posts only'); fireEvent.click(scopeButton); const submitButton = getByText('Add Rule'); fireEvent.click(submitButton); }); afterEach(cleanup); it('snapshot', () => { expect(container).toMatchSnapshot(); }); it('should call addRuleHandler once', async () => { expect(addRuleHandler).toHaveBeenCalledTimes(1); }); });
#!/bin/bash # # Copyright 2021 SkyAPM # # 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. # pecl package
#!/bin/bash rm dist/* python setup.py sdist bdist_wheel rm dist/*.egg twine upload dist/*
#!/bin/bash # Copyright (c) 2021, Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl # export vol_name=u01 ########### SIGINT handler ############ function _int() { echo "Stopping container.." echo "SIGINT received, shutting down servers!" echo "" echo "Stopping Node Manager.." /$vol_name/oracle/user_projects/domains/$DOMAIN_NAME/bin/stopNodeManager.sh echo "Stopping Admin Server.." /$vol_name/oracle/container-scripts/stopAdmin.sh exit; EOF lsnrctl stop } ########### SIGTERM handler ############ function _term() { echo "Stopping container.." echo "SIGTERM received, shutting down Servers!" echo "" echo "Stopping Node Manager.." /$vol_name/oracle/user_projects/domains/$DOMAIN_NAME/bin/stopNodeManager.sh echo "Stopping Admin Server.." /$vol_name/oracle/container-scripts/stopAdmin.sh exit; EOF lsnrctl stop } ########### SIGKILL handler ############ function _kill() { echo "SIGKILL received, shutting down Servers!" echo "" echo "Stopping Node Manager.." /$vol_name/oracle/user_projects/domains/$DOMAIN_NAME/bin/stopNodeManager.sh echo "Stopping Admin Server.." /$vol_name/oracle/container-scripts/stopAdmin.sh exit; EOF lsnrctl stop } # Set SIGINT handler trap _int SIGINT # Set SIGTERM handler trap _term SIGTERM # Set SIGKILL handler trap _kill SIGKILL export CONTAINERCONFIG_DIR_NAME="container-data" export CONTAINERCONFIG_DIR="/$vol_name/oracle/user_projects/$CONTAINERCONFIG_DIR_NAME" export CONTAINERCONFIG_LOG_DIR="$CONTAINERCONFIG_DIR/logs" export CONTAINERCONFIG_DOMAIN_DIR="/$vol_name/oracle/user_projects/domains" echo "" echo "=========================================================" echo " WebCenter Content Docker Container " echo " Admin Server " echo " 12.2.1.4.0 " echo "=========================================================" echo "" echo "" # Persistence volume location mapped to this location will need permission fixup if [ -d $CONTAINERCONFIG_DIR ]; then chown -R oracle:root $CONTAINERCONFIG_DOMAIN_DIR chown -R oracle:root $CONTAINERCONFIG_DIR chown -R oracle:root $CONTAINERCONFIG_LOG_DIR else mkdir -p $CONTAINERCONFIG_DIR mkdir -p $CONTAINERCONFIG_LOG_DIR mkdir -p $CONTAINERCONFIG_DOMAIN_DIR chown -R oracle:root $CONTAINERCONFIG_DOMAIN_DIR chown -R oracle:root $CONTAINERCONFIG_DIR chown -R oracle:root $CONTAINERCONFIG_LOG_DIR fi echo "" echo "" export component=$component echo "component=${component}" # configuring wcc domain sh /$vol_name/oracle/container-scripts/createWCCDomain.sh retval=$? if [ $retval -ne 0 ]; then echo "" echo "" echo "Domain Creation failed. Exiting.." exit 1 fi #delimited code IFS=',' read -r -a cmp <<< "$component" size=${#cmp[@]} echo "size of component=$size" if [ $size -gt "0" ] then for i in "${cmp[@]}" do if [ "${i^^}" == "IPM" ] then echo "Call IPM Implementation" fi if [ "${i^^}" == "CAPTURE" ] then echo "Not yet Implemented" fi if [ "${i^^}" == "ADFUI" ] then echo "Not yet Implemented" fi done fi echo "start admin container" # start admin container sh /$vol_name/oracle/container-scripts/startAdminContainer.sh
#!/usr/bin/bash # Copyright (c) 2021. Huawei Technologies Co.,Ltd.ALL rights reserved. # This program is licensed under Mulan PSL v2. # You can use it according to the terms and conditions of the Mulan PSL v2. # http://license.coscl.org.cn/MulanPSL2 # THIS PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. # ############################################# # @Author : doraemon2020 # @Contact : xcl_job@163.com # @Date : 2020-05-07 # @License : Mulan PSL v2 # @Desc : Test nmcli configure MACsec # ############################################ source ../common/net_lib.sh function config_params() { LOG_INFO "Start to config params of the case." get_free_eth 1 test_eth1=${LOCAL_ETH[0]} con_name='test-macsec+' LOG_INFO "End to config params of the case." } function run_test() { LOG_INFO "Start to run test." nmcli connection add type macsec \ con-name ${con_name} ifname macsec0 \ connection.autoconnect no \ macsec.parent ${test_eth1} macsec.mode psk \ macsec.mka-cak 12345678901234567890123456789012 \ macsec.mka-ckn 1234567890123456789012345678901234567890123456789012345678901234 \ ip4 192.0.2.100/24 CHECK_RESULT $? nmcli connection up ${con_name} CHECK_RESULT $? LOG_INFO "End to run test." } function post_test() { LOG_INFO "Start to restore the test environment." nmcli con delete ${con_name} LOG_INFO "End to restore the test environment." } main "$@"
package no.mnemonic.commons.logging; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.concurrent.atomic.AtomicReference; public class Logging { private static final String LOGGING_PROPERTY_FILE = "META-INF/no.mnemonic.commons.logging.Logging.properties"; private static final String LOGGING_PROPERTY_KEY = "provider.class"; private final static AtomicReference<LoggingProvider> provider = new AtomicReference<>(); public static Logger getLogger(String name) { if (name == null) name = ""; return getProvider().getLogger(name); } public static LoggingContext getLoggingContext() { return getProvider().getLoggingContext(); } public static Logger getLogger(Class clz) { return getLogger(clz == null ? null : clz.getName()); } public static void setProvider(LoggingProvider implementation) { provider.set(implementation); } //resolve provider private static LoggingProvider getProvider() { if (provider.get() != null) return provider.get(); provider.set(resolveProvider()); return provider.get(); } private static LoggingProvider resolveProvider() { try (InputStream propertyStream = Logging.class.getClassLoader().getResourceAsStream(LOGGING_PROPERTY_FILE)) { if (propertyStream == null) return createDefaultProvider(); Properties props = new Properties(); props.load(propertyStream); if (props.containsKey(LOGGING_PROPERTY_KEY)) return loadProvider(props.getProperty(LOGGING_PROPERTY_KEY)); return createDefaultProvider(); } catch (IOException e) { return createDefaultProvider(); } } private static LoggingProvider loadProvider(String providerClassName) { try { Class providerClz = Class.forName(providerClassName); return (LoggingProvider) providerClz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } private static LoggingProvider createDefaultProvider() { System.err.println("ERROR: no.mnemonic.commons.logging.Logging: No logging provider found, using console logger as default. Add implementation package to classpath."); return new LoggingProvider() { @Override public Logger getLogger(String name) { return new ConsoleLoggerImpl(); } @Override public LoggingContext getLoggingContext() { return new LoggingContext() { @Override public void clear() { // do nothing } @Override public boolean containsKey(String key) { return false; } @Override public String get(String key) { return null; } @Override public void put(String key, String value) { // do nothing } @Override public void remove(String key) { // do nothing } }; } }; } }
import {RouterModule, Routes} from '@angular/router'; import {NgModule} from '@angular/core'; import {PagesComponent} from './pages.component'; import {DashboardComponent} from './dashboard/dashboard.component'; import {ECommerceComponent} from './e-commerce/e-commerce.component'; import {NotFoundComponent} from './miscellaneous/not-found/not-found.component'; import {AuthGuardService} from '../service/auth/auth-guard.service'; import {UnauthorizedComponent} from './miscellaneous/unauthorized/unauthorized.component'; import {ShopComponent} from './shop/shop-main/shop.component'; import {ShoppingCartComponent} from './shop/shopping-cart/shopping-cart.component'; import {ShoppingCartPaymentComponent} from './shop/shopping-cart-payment/shopping-cart-payment.component'; const routes: Routes = [{ path: '', component: PagesComponent, children: [ { path: 'shop', component: ShopComponent, }, { path: 'cart', component: ShoppingCartComponent, }, { path: 'shopping-cart-payment', component: ShoppingCartPaymentComponent, }, { path: 'dashboard', data: {roles: ['INV']}, canActivate: [AuthGuardService], component: ECommerceComponent, }, { path: 'customer', loadChildren: () => import('./customer/customer.module') .then(m => m.CustomerModule), }, { path: 'employee', loadChildren: () => import('./employee/employee.module') .then(m => m.EmployeeModule), }, { path: 'supplier', loadChildren: () => import('./supplier/supplier.module') .then(m => m.SupplierModule), }, { path: 'transport', loadChildren: () => import('./transport/transport.module') .then(m => m.TransportModule), }, { path: 'user', loadChildren: () => import('./user/user.module') .then(m => m.UserModule), }, { path: 'item', loadChildren: () => import('./item/item.module') .then(m => m.ItemModule), }, { path: 'inventory', loadChildren: () => import('./inventory/inventory.module') .then(m => m.InventoryModule), }, { path: 'sale', loadChildren: () => import('./sale/sale.module') .then(m => m.SaleModule), }, { path: 'order', loadChildren: () => import('./order/order.module') .then(m => m.OrderModule), }, { path: 'delivery', loadChildren: () => import('./delivery/delivery.module') .then(m => m.DeliveryModule), }, { path: 'purchase-order', loadChildren: () => import('./purchase-order/purchase-order.module') .then(m => m.PurchaseOrderModule), }, { path: 'grn', loadChildren: () => import('./grn/grn.module') .then(m => m.GrnModule), }, { path: 'payment', loadChildren: () => import('./payment/payment.module') .then(m => m.PaymentModule), }, { path: 'test', loadChildren: () => import('./chemical-test/chemical-test.module') .then(m => m.ChemicalTestModule), }, { path: 'notification', loadChildren: () => import('./notification/notification.module') .then(m => m.NotificationModule), }, { path: 'complain', loadChildren: () => import('./complain/complain.module') .then(m => m.ComplainModule), }, { path: 'report', loadChildren: () => import('./report/report.module') .then(m => m.ReportModule), }, { path: 'iot-dashboard', data: {roles: ['INV']}, canActivate: [AuthGuardService], component: DashboardComponent, }, { path: 'layout', loadChildren: () => import('./layout/layout.module') .then(m => m.LayoutModule), }, { path: 'forms', loadChildren: () => import('./forms/forms.module') .then(m => m.FormsModule), }, { path: 'ui-features', loadChildren: () => import('./ui-features/ui-features.module') .then(m => m.UiFeaturesModule), }, { path: 'modal-overlays', loadChildren: () => import('./modal-overlays/modal-overlays.module') .then(m => m.ModalOverlaysModule), }, { path: 'extra-components', loadChildren: () => import('./extra-components/extra-components.module') .then(m => m.ExtraComponentsModule), }, { path: 'maps', loadChildren: () => import('./maps/maps.module') .then(m => m.MapsModule), }, { path: 'charts', loadChildren: () => import('./charts/charts.module') .then(m => m.ChartsModule), }, { path: 'editors', loadChildren: () => import('./editors/editors.module') .then(m => m.EditorsModule), }, { path: 'tables', loadChildren: () => import('./tables/tables.module') .then(m => m.TablesModule), }, { path: 'miscellaneous', loadChildren: () => import('./miscellaneous/miscellaneous.module') .then(m => m.MiscellaneousModule), }, { path: '', redirectTo: 'shop', pathMatch: 'full', }, { path: '401', component: UnauthorizedComponent, }, { path: '**', component: NotFoundComponent, }, ], }]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class PagesRoutingModule { }
<reponame>kemtol/nyelam var browser = function() { // Return cached result if avalible, else get result then cache it. if (browser.prototype._cachedResult) return browser.prototype._cachedResult; // Opera 8.0+ var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; // Firefox 1.0+ var isFirefox = typeof InstallTrigger !== 'undefined'; // Safari 3.0+ "[object HTMLElementConstructor]" var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || safari.pushNotification); // Internet Explorer 6-11 var isIE = /*@cc_on!@*/false || !!document.documentMode; // Edge 20+ var isEdge = !isIE && !!window.StyleMedia; // Chrome 1+ var isChrome = !!window.chrome && !!window.chrome.webstore; // Blink engine detection var isBlink = (isChrome || isOpera) && !!window.CSS; return browser.prototype._cachedResult = isOpera ? 'Opera' : isFirefox ? 'Firefox' : isSafari ? 'Safari' : isChrome ? 'Chrome' : isIE ? 'IE' : isEdge ? 'Edge' : isBlink ? 'Blink' : "null"; }; jQuery(window).on('load', function () { //Masonry jQuery('.testimonials-list').masonry({ // options itemSelector: '.testimonial-item', }); jQuery('.faq-list .row').masonry({ // options itemSelector: '.faq-item', }); //patch for wa api in firefox and opera //check if mobile if (typeof window.orientation == 'undefined'){ $("a[href*='whatsapp']").each(function() { $(this).attr("href", $(this).attr('href').replace(/\bapi\b/g, 'web')); }); } $("a[href*='whatsapp']").each(function() { console.log($(this).attr('href').replace(/\bsitewa\b/g, siteWa)) $(this).attr("href", $(this).attr('href').replace(/\bsitewa\b/g, siteWa)); }); //console.log(browser); });
# Copyright 2014 Google Inc. All Rights Reserved. # # 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. # Downloads and installs bdconfig and the xml templates set -e # Download and use bdconfig for xml configuration. if [[ ! -f "$(which bdconfig)" ]]; then download_bd_resource "${BDCONFIG}" /tmp/bdconfig.tar.gz mkdir -p /usr/local/share/google tar -C /usr/local/share/google -xzf /tmp/bdconfig.tar.gz ln -s /usr/local/share/google/bdconfig*/bdconfig /usr/local/bin fi
<filename>Teatro/Teatro.h #ifndef TEATRO_H_INCLUDED #define TEATRO_H_INCLUDED #include <iostream> /**************************** CODIFICADO POR <NAME> *****************************/ using namespace std; struct Teatro{ unsigned Linhas; unsigned Colunas; unsigned Vendas; bool *Assentos; Teatro(){ } Teatro(int linhas, int colunas) { Linhas = linhas; Colunas = colunas; Assentos = new bool[Linhas*Colunas]; Vendas = 0; //zerar matriz for(int i = 0; i<Linhas;i++){ for(int j = 0; j<Colunas;j++){ Assentos[i*Colunas+j] = false; } } } /*verifica a disponibilidade do assento*/ bool Disponibilidade(int linha, int coluna) { if(Assentos[linha*Colunas+coluna] == false && linha < Linhas && coluna < Colunas) return true; } void MarcarLugar(int linha, int coluna){ Assentos[linha*Colunas+coluna] = true; Vendas += 1; } /*Reembolsa*/ void Reembolso(int linha, int coluna) { Assentos[linha*Colunas+coluna] = false; Vendas -= 1; } }; #endif // TEATRO_H_INCLUDED
<gh_stars>1-10 package com.keildraco.config.states; import javax.annotation.Nullable; import com.keildraco.config.data.ItemType; import com.keildraco.config.data.Token; import com.keildraco.config.data.TokenType; import com.keildraco.config.exceptions.GenericParseException; import com.keildraco.config.exceptions.IllegalParserStateException; import com.keildraco.config.factory.TypeFactory; import com.keildraco.config.interfaces.AbstractParserBase; import com.keildraco.config.interfaces.IStateParser; import com.keildraco.config.interfaces.ParserInternalTypeBase; import com.keildraco.config.tokenizer.Tokenizer; import com.keildraco.config.types.ListType; import static com.keildraco.config.data.Constants.ParserNames.LIST; import static com.keildraco.config.data.Constants.ParserNames.OPERATION; /** * * @author <NAME> * */ public final class ListParser extends AbstractParserBase { /** * * @param factoryIn * @param parentIn */ public ListParser(final TypeFactory factoryIn, @Nullable final ParserInternalTypeBase parentIn) { super(factoryIn, parentIn, LIST); } private void handleIdentifierLoad(final Token next, final Token current, final Tokenizer tokenizer, final ListType rv) { if ((!next.isEmpty()) && ((next.getType() != TokenType.SEPERATOR) && (next.getType() != TokenType.CLOSE_LIST))) { final IStateParser nextState = this.getFactory().nextState(this.getName(), current, next); rv.addItem(nextState.getState(tokenizer)); } else { rv.addItem(this.getFactory().getType(null, current.getValue(), current.getValue(), ItemType.IDENTIFIER)); tokenizer.nextToken(); // consume the identifier } } @Override public ParserInternalTypeBase getState(final Tokenizer tokenizer) { if (!tokenizer.hasNext()) { throw new IllegalParserStateException("End of input at start of state"); } // we should enter with OPEN_LIST IDENTIFIER // so first we consume one token (OPEN_LIST) tokenizer.nextToken(); // next we get our current Token and the token that follows Token current = tokenizer.peek(); Token next = tokenizer.peekToken(); final ListType rv = new ListType(""); while (tokenizer.hasNext()) { if (current.getType() == TokenType.IDENTIFIER) { this.handleIdentifierLoad(next, current, tokenizer, rv); } else if ((current.getType() == TokenType.SEPERATOR) || (current.getType() == TokenType.CLOSE_LIST)) { tokenizer.nextToken(); // consume! if (current.getType() == TokenType.CLOSE_LIST) { return rv; } } else { throw new GenericParseException( String.format("Odd, this (token of type %s, value %s) should not be here!", current.getType(), current.getValue())); } current = tokenizer.peek(); next = tokenizer.peekToken(); } throw new GenericParseException("End of input found while processing a LIST!"); } @Override public void registerTransitions(final TypeFactory factory) { factory.registerStateTransition(LIST, TokenType.IDENTIFIER, TokenType.OPEN_PARENS, OPERATION); } }
/* * Copyright 2018-present Open Networking Foundation * * 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. */ package org.onosproject.xmpp.core.ctl.handlers; import com.google.common.collect.Lists; import io.netty.channel.ChannelHandlerContext; import org.codehaus.stax2.ri.evt.AttributeEventImpl; import org.codehaus.stax2.ri.evt.NamespaceEventImpl; import org.codehaus.stax2.ri.evt.StartElementEventImpl; import org.dom4j.Element; import org.dom4j.tree.DefaultElement; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.onosproject.xmpp.core.ctl.exception.UnsupportedStanzaTypeException; import org.onosproject.xmpp.core.stream.XmppStreamOpen; import org.xmpp.packet.IQ; import org.xmpp.packet.JID; import org.xmpp.packet.Message; import org.xmpp.packet.Packet; import org.xmpp.packet.Presence; import javax.xml.namespace.QName; import javax.xml.stream.Location; import javax.xml.stream.events.Attribute; import javax.xml.stream.events.Namespace; import javax.xml.stream.events.XMLEvent; import java.util.List; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; /** * Test class for XmppDecoder testing. */ public class XmppDecoderTest { XmppDecoder xmppDecoder; Element xmppStanzaElement; XMLEvent streamOpen; Element iqElement = new IQ().getElement(); Element messageElement = new Message().getElement(); Element presenceElement = new Presence().getElement(); ChannelHandlerContext mockChannelHandlerContext; Location mockLocation; @Before public void setUp() { xmppDecoder = new XmppDecoder(); mockChannelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class); mockLocation = EasyMock.createMock(Location.class); buildXmppStanza(); buildXmppStreamOpen(); } private void buildXmppStreamOpen() { QName qName = new QName("http://etherx.jabber.org/streams", "stream", "stream"); Attribute attrTo = new AttributeEventImpl(mockLocation, QName.valueOf("to"), "xmpp.onosproject.org", true); Attribute attrFrom = new AttributeEventImpl(mockLocation, QName.valueOf("from"), "<EMAIL>", true); List<Attribute> attributes = Lists.newArrayList(); attributes.add(attrTo); attributes.add(attrFrom); Namespace streamNs = NamespaceEventImpl.constructNamespace(mockLocation, "stream", "http://etherx.jabber.org/streams"); Namespace jabberNs = NamespaceEventImpl.constructDefaultNamespace(mockLocation, "jabber:client"); List<Namespace> namespaces = Lists.newArrayList(); namespaces.add(streamNs); namespaces.add(jabberNs); streamOpen = StartElementEventImpl.construct(mockLocation, qName, attributes.iterator(), namespaces.iterator(), null); } private void buildXmppStanza() { xmppStanzaElement = new DefaultElement("iq"); xmppStanzaElement.addAttribute("type", "set"); xmppStanzaElement.addAttribute("from", "<EMAIL>"); xmppStanzaElement.addAttribute("to", "xmpp.onosproject.org"); Element pubsub = new DefaultElement("pubsub", new org.dom4j.Namespace("", "http://jabber.org/protocol/pubsub")); Element subscribe = new DefaultElement("subscribe"); subscribe.addAttribute("node", "test"); pubsub.add(subscribe); xmppStanzaElement.add(pubsub); } @Test public void testDecodeStream() throws Exception { List<Object> out = Lists.newArrayList(); xmppDecoder.decode(mockChannelHandlerContext, streamOpen, out); assertThat(out.size(), is(1)); assertThat(out.get(0), is(instanceOf(XmppStreamOpen.class))); XmppStreamOpen stream = (XmppStreamOpen) out.get(0); assertThat(stream.getElement(), is(notNullValue())); assertThat(stream.getToJid(), is(new JID("xmpp.onosproject.org"))); assertThat(stream.getFromJid(), is(new JID("<EMAIL>"))); } @Test public void testDecodeXmppStanza() throws Exception { // TODO: complete it List<Object> out = Lists.newArrayList(); xmppDecoder.decode(mockChannelHandlerContext, xmppStanzaElement, out); assertThat(out.size(), is(1)); assertThat(out.get(0), is(instanceOf(Packet.class))); assertThat(out.get(0), is(instanceOf(IQ.class))); IQ iq = (IQ) out.get(0); assertThat(iq.getElement(), is(notNullValue())); assertThat(iq.getFrom(), is(new JID("<EMAIL>"))); assertThat(iq.getTo(), is(new JID("xmpp.onosproject.org"))); assertThat(iq.getType(), is(IQ.Type.set)); } @Test public void testRecognizePacket() throws Exception { Packet iqPacket = xmppDecoder.recognizeAndReturnXmppPacket(iqElement); assertThat(iqPacket, is(instanceOf(IQ.class))); Packet messagePacket = xmppDecoder.recognizeAndReturnXmppPacket(messageElement); assertThat(messagePacket, is(instanceOf(Message.class))); Packet presencePacket = xmppDecoder.recognizeAndReturnXmppPacket(presenceElement); assertThat(presencePacket, is(instanceOf(Presence.class))); Element wrongElement = new DefaultElement("test"); try { xmppDecoder.recognizeAndReturnXmppPacket(wrongElement); } catch (Exception e) { assertThat(e, is(instanceOf(UnsupportedStanzaTypeException.class))); } } }
#! /bin/bash PACKAGE="dbus" VERSION=$1 FOLD_NAME="$PACKAGE-$VERSION" if [ -z "$CORES" ]; then CORES='4' fi tar xf "$PACKAGE_DIR/$FOLD_NAME.tar.gz" pushd "$FOLD_NAME" # Configure the source ./configure --prefix=/usr \ --sysconfdir=/etc \ --localstatedir=/var \ --disable-static \ --disable-doxygen-docs \ --disable-xml-docs \ --docdir=/usr/share/doc/dbus-$VERSION \ --with-console-auth-dir=/run/console # Build using the configured sources make -j "$CORES" # Install the built package if [ "$INSTALL_SOURCES" -eq 1 ]; then make install mv -v /usr/lib/libdbus-1.so.* /lib ln -sfv ../../lib/$(readlink /usr/lib/libdbus-1.so) /usr/lib/libdbus-1.so ln -sfv /etc/machine-id /var/lib/dbus fi popd rm -rf "$FOLD_NAME"
#include <stdlib.h> #include <time.h> int randomNumberGenerator(int min, int max) { srand(time(0)); return rand() % (max - min + 1) + min; }
#!/usr/bin/env bash cat <<EOF build_framework.sh has been replaced with build_package.sh. Update your build.sh to use build_package.sh as follows. See dcos-commons/frameworks/hello-world/build.sh for an example: - Before calling build_package.sh, your build.sh should explicitly invoke e.g. './gradlew check distZip' to build your scheduler.zip. See dcos-commons/frameworks/hello-world/build.sh for an example. - Rename any '--artifact' flags to '-a'. In addition to any custom artifacts you may be building, you should now also provide the path to your scheduler.zip with e.g. '-a path/to/build/distributions/your-scheduler.zip'. See dcos-commons/frameworks/hello-world/build.sh for an example. - Any BOOTSTRAP_DIR/EXECUTOR_DIR/CLI_DIR settings can be removed as they are not applicable to build_package.sh. - If you are using build_go_exe.sh to build a binary across multiple platforms (e.g. to build a custom CLI across linux/darwin/windows), you should instead perform a single build_go_exe.sh invocation with multiple space-separated platforms. See dcos-commons/sdk/cli/build.sh for an example. Additionally, if your service does not require a custom CLI with additional custom, you can now switch to a default CLI and forego the need to have golang to build your service. Update your universe/resource.json's CLI entries as follows (with correct SHA256, SDKVERS and PLATFORM): "x86-64": { "contentHash": [ { "algo": "sha256", "value": "SHA256: get output of 'curl https://downloads.mesosphere.com/dcos-commons/artifacts/SDKVERS/dcos-service-cli-PLATFORM | sha256sum'" } ], "kind": "executable", "url": "https://downloads.mesosphere.com/dcos-commons/artifacts/SDKVERS/dcos-service-cli-PLATFORM" } If you do require a custom CLI (rare), then you must now explicitly build it within your build.sh and pass it to build_package.sh using '-a' arguments. See dcos-commons/frameworks/kafka/build.sh for an example. EOF exit 1
<filename>closure-templates/testdata/javascript/soy_usegoog_lib_nomap.js //javascript/closure/base.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Bootstrap for the Google JS Library (Closure). * * In uncompiled mode base.js will attempt to load Closure's deps file, unless * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects * to include their own deps file(s) from different locations. * * Avoid including base.js more than once. This is strictly discouraged and not * supported. goog.require(...) won't work properly in that case. * * @provideGoog */ /** * @define {boolean} Overridden to true by the compiler. */ var COMPILED = false; /** * Base namespace for the Closure library. Checks to see goog is already * defined in the current scope before assigning to prevent clobbering if * base.js is loaded more than once. * * @const */ var goog = goog || {}; /** * Reference to the global context. In most cases this will be 'window'. * @const * @suppress {newCheckTypes} */ goog.global = this; /** * A hook for overriding the define values in uncompiled mode. * * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`, * `goog.define` will use the value instead of the default value. This * allows flags to be overwritten without compilation (this is normally * accomplished with the compiler's "define" flag). * * Example: * <pre> * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false}; * </pre> * * @type {Object<string, (string|number|boolean)>|undefined} */ goog.global.CLOSURE_UNCOMPILED_DEFINES; /** * A hook for overriding the define values in uncompiled or compiled mode, * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence. * * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or * string literals or the compiler will emit an error. * * While any @define value may be set, only those set with goog.define will be * effective for uncompiled code. * * Example: * <pre> * var CLOSURE_DEFINES = {'goog.DEBUG': false} ; * </pre> * * @type {Object<string, (string|number|boolean)>|undefined} */ goog.global.CLOSURE_DEFINES; /** * Returns true if the specified value is not undefined. * * @param {?} val Variable to test. * @return {boolean} Whether variable is defined. */ goog.isDef = function(val) { // void 0 always evaluates to undefined and hence we do not need to depend on // the definition of the global variable named 'undefined'. return val !== void 0; }; /** * Returns true if the specified value is a string. * @param {?} val Variable to test. * @return {boolean} Whether variable is a string. */ goog.isString = function(val) { return typeof val == 'string'; }; /** * Returns true if the specified value is a boolean. * @param {?} val Variable to test. * @return {boolean} Whether variable is boolean. */ goog.isBoolean = function(val) { return typeof val == 'boolean'; }; /** * Returns true if the specified value is a number. * @param {?} val Variable to test. * @return {boolean} Whether variable is a number. */ goog.isNumber = function(val) { return typeof val == 'number'; }; /** * Builds an object structure for the provided namespace path, ensuring that * names that already exist are not overwritten. For example: * "a.b.c" -> a = {};a.b={};a.b.c={}; * Used by goog.provide and goog.exportSymbol. * @param {string} name name of the object that this file defines. * @param {*=} opt_object the object to expose at the end of the path. * @param {Object=} opt_objectToExportTo The object to add the path to; default * is `goog.global`. * @private */ goog.exportPath_ = function(name, opt_object, opt_objectToExportTo) { var parts = name.split('.'); var cur = opt_objectToExportTo || goog.global; // Internet Explorer exhibits strange behavior when throwing errors from // methods externed in this manner. See the testExportSymbolExceptions in // base_test.html for an example. if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') { cur.execScript('var ' + parts[0]); } for (var part; parts.length && (part = parts.shift());) { if (!parts.length && goog.isDef(opt_object)) { // last part and we have an object; use it cur[part] = opt_object; } else if (cur[part] && cur[part] !== Object.prototype[part]) { cur = cur[part]; } else { cur = cur[part] = {}; } } }; /** * Defines a named value. In uncompiled mode, the value is retrieved from * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and * has the property specified, and otherwise used the defined defaultValue. * When compiled the default can be overridden using the compiler * options or the value set in the CLOSURE_DEFINES object. * * @param {string} name The distinguished name to provide. * @param {string|number|boolean} defaultValue */ goog.define = function(name, defaultValue) { var value = defaultValue; if (!COMPILED) { var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES; var defines = goog.global.CLOSURE_DEFINES; if (uncompiledDefines && // Anti DOM-clobbering runtime check (b/37736576). /** @type {?} */ (uncompiledDefines).nodeType === undefined && Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) { value = uncompiledDefines[name]; } else if ( defines && // Anti DOM-clobbering runtime check (b/37736576). /** @type {?} */ (defines).nodeType === undefined && Object.prototype.hasOwnProperty.call(defines, name)) { value = defines[name]; } } goog.exportPath_(name, value); }; /** * @define {boolean} DEBUG is provided as a convenience so that debugging code * that should not be included in a production. It can be easily stripped * by specifying --define goog.DEBUG=false to the Closure Compiler aka * JSCompiler. For example, most toString() methods should be declared inside an * "if (goog.DEBUG)" conditional because they are generally used for debugging * purposes and it is difficult for the JSCompiler to statically determine * whether they are used. */ goog.define('goog.DEBUG', true); /** * @define {string} LOCALE defines the locale being used for compilation. It is * used to select locale specific data to be compiled in js binary. BUILD rule * can specify this value by "--define goog.LOCALE=<locale_name>" as a compiler * option. * * Take into account that the locale code format is important. You should use * the canonical Unicode format with hyphen as a delimiter. Language must be * lowercase, Language Script - Capitalized, Region - UPPERCASE. * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN. * * See more info about locale codes here: * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers * * For language codes you should use values defined by ISO 693-1. See it here * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from * this rule: the Hebrew language. For legacy reasons the old code (iw) should * be used instead of the new code (he). * */ goog.define('goog.LOCALE', 'en'); // default to en /** * @define {boolean} Whether this code is running on trusted sites. * * On untrusted sites, several native functions can be defined or overridden by * external libraries like Prototype, Datejs, and JQuery and setting this flag * to false forces closure to use its own implementations when possible. * * If your JavaScript can be loaded by a third party site and you are wary about * relying on non-standard implementations, specify * "--define goog.TRUSTED_SITE=false" to the compiler. */ goog.define('goog.TRUSTED_SITE', true); /** * @define {boolean} Whether a project is expected to be running in strict mode. * * This define can be used to trigger alternate implementations compatible with * running in EcmaScript Strict mode or warn about unavailable functionality. * @see https://goo.gl/PudQ4y * */ goog.define('goog.STRICT_MODE_COMPATIBLE', false); /** * @define {boolean} Whether code that calls {@link goog.setTestOnly} should * be disallowed in the compilation unit. */ goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG); /** * @define {boolean} Whether to use a Chrome app CSP-compliant method for * loading scripts via goog.require. @see appendScriptSrcNode_. */ goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false); /** * Defines a namespace in Closure. * * A namespace may only be defined once in a codebase. It may be defined using * goog.provide() or goog.module(). * * The presence of one or more goog.provide() calls in a file indicates * that the file defines the given objects/namespaces. * Provided symbols must not be null or undefined. * * In addition, goog.provide() creates the object stubs for a namespace * (for example, goog.provide("goog.foo.bar") will create the object * goog.foo.bar if it does not already exist). * * Build tools also scan for provide/require/module statements * to discern dependencies, build dependency files (see deps.js), etc. * * @see goog.require * @see goog.module * @param {string} name Namespace provided by this file in the form * "goog.package.part". */ goog.provide = function(name) { if (goog.isInModuleLoader_()) { throw new Error('goog.provide can not be used within a goog.module.'); } if (!COMPILED) { // Ensure that the same namespace isn't provided twice. // A goog.module/goog.provide maps a goog.require to a specific file if (goog.isProvided_(name)) { throw new Error('Namespace "' + name + '" already declared.'); } } goog.constructNamespace_(name); }; /** * @param {string} name Namespace provided by this file in the form * "goog.package.part". * @param {Object=} opt_obj The object to embed in the namespace. * @private */ goog.constructNamespace_ = function(name, opt_obj) { if (!COMPILED) { delete goog.implicitNamespaces_[name]; var namespace = name; while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) { if (goog.getObjectByName(namespace)) { break; } goog.implicitNamespaces_[namespace] = true; } } goog.exportPath_(name, opt_obj); }; /** * Module identifier validation regexp. * Note: This is a conservative check, it is very possible to be more lenient, * the primary exclusion here is "/" and "\" and a leading ".", these * restrictions are intended to leave the door open for using goog.require * with relative file paths rather than module identifiers. * @private */ goog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/; /** * Defines a module in Closure. * * Marks that this file must be loaded as a module and claims the namespace. * * A namespace may only be defined once in a codebase. It may be defined using * goog.provide() or goog.module(). * * goog.module() has three requirements: * - goog.module may not be used in the same file as goog.provide. * - goog.module must be the first statement in the file. * - only one goog.module is allowed per file. * * When a goog.module annotated file is loaded, it is enclosed in * a strict function closure. This means that: * - any variables declared in a goog.module file are private to the file * (not global), though the compiler is expected to inline the module. * - The code must obey all the rules of "strict" JavaScript. * - the file will be marked as "use strict" * * NOTE: unlike goog.provide, goog.module does not declare any symbols by * itself. If declared symbols are desired, use * goog.module.declareLegacyNamespace(). * * * See the public goog.module proposal: http://goo.gl/Va1hin * * @param {string} name Namespace provided by this file in the form * "goog.package.part", is expected but not required. * @return {void} */ goog.module = function(name) { if (!goog.isString(name) || !name || name.search(goog.VALID_MODULE_RE_) == -1) { throw new Error('Invalid module identifier'); } if (!goog.isInModuleLoader_()) { throw new Error( 'Module ' + name + ' has been loaded incorrectly. Note, ' + 'modules cannot be loaded as normal scripts. They require some kind of ' + 'pre-processing step. You\'re likely trying to load a module via a ' + 'script tag or as a part of a concatenated bundle without rewriting the ' + 'module. For more info see: ' + 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.'); } if (goog.moduleLoaderState_.moduleName) { throw new Error('goog.module may only be called once per module.'); } // Store the module name for the loader. goog.moduleLoaderState_.moduleName = name; if (!COMPILED) { // Ensure that the same namespace isn't provided twice. // A goog.module/goog.provide maps a goog.require to a specific file if (goog.isProvided_(name)) { throw new Error('Namespace "' + name + '" already declared.'); } delete goog.implicitNamespaces_[name]; } }; /** * @param {string} name The module identifier. * @return {?} The module exports for an already loaded module or null. * * Note: This is not an alternative to goog.require, it does not * indicate a hard dependency, instead it is used to indicate * an optional dependency or to access the exports of a module * that has already been loaded. * @suppress {missingProvide} */ goog.module.get = function(name) { return goog.module.getInternal_(name); }; /** * @param {string} name The module identifier. * @return {?} The module exports for an already loaded module or null. * @private */ goog.module.getInternal_ = function(name) { if (!COMPILED) { if (name in goog.loadedModules_) { return goog.loadedModules_[name]; } else if (!goog.implicitNamespaces_[name]) { var ns = goog.getObjectByName(name); return ns != null ? ns : null; } } return null; }; /** * @private {?{moduleName: (string|undefined), declareLegacyNamespace:boolean}} */ goog.moduleLoaderState_ = null; /** * @private * @return {boolean} Whether a goog.module is currently being initialized. */ goog.isInModuleLoader_ = function() { return goog.moduleLoaderState_ != null; }; /** * Provide the module's exports as a globally accessible object under the * module's declared name. This is intended to ease migration to goog.module * for files that have existing usages. * @suppress {missingProvide} */ goog.module.declareLegacyNamespace = function() { if (!COMPILED && !goog.isInModuleLoader_()) { throw new Error( 'goog.module.declareLegacyNamespace must be called from ' + 'within a goog.module'); } if (!COMPILED && !goog.moduleLoaderState_.moduleName) { throw new Error( 'goog.module must be called prior to ' + 'goog.module.declareLegacyNamespace.'); } goog.moduleLoaderState_.declareLegacyNamespace = true; }; /** * Marks that the current file should only be used for testing, and never for * live code in production. * * In the case of unit tests, the message may optionally be an exact namespace * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra * provide (if not explicitly defined in the code). * * @param {string=} opt_message Optional message to add to the error that's * raised when used in production code. */ goog.setTestOnly = function(opt_message) { if (goog.DISALLOW_TEST_ONLY_CODE) { opt_message = opt_message || ''; throw new Error( 'Importing test-only code into non-debug environment' + (opt_message ? ': ' + opt_message : '.')); } }; /** * Forward declares a symbol. This is an indication to the compiler that the * symbol may be used in the source yet is not required and may not be provided * in compilation. * * The most common usage of forward declaration is code that takes a type as a * function parameter but does not need to require it. By forward declaring * instead of requiring, no hard dependency is made, and (if not required * elsewhere) the namespace may never be required and thus, not be pulled * into the JavaScript binary. If it is required elsewhere, it will be type * checked as normal. * * Before using goog.forwardDeclare, please read the documentation at * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to * understand the options and tradeoffs when working with forward declarations. * * @param {string} name The namespace to forward declare in the form of * "goog.package.part". */ goog.forwardDeclare = function(name) {}; /** * Forward declare type information. Used to assign types to goog.global * referenced object that would otherwise result in unknown type references * and thus block property disambiguation. */ goog.forwardDeclare('Document'); goog.forwardDeclare('HTMLScriptElement'); goog.forwardDeclare('XMLHttpRequest'); if (!COMPILED) { /** * Check if the given name has been goog.provided. This will return false for * names that are available only as implicit namespaces. * @param {string} name name of the object to look for. * @return {boolean} Whether the name has been provided. * @private */ goog.isProvided_ = function(name) { return (name in goog.loadedModules_) || (!goog.implicitNamespaces_[name] && goog.isDefAndNotNull(goog.getObjectByName(name))); }; /** * Namespaces implicitly defined by goog.provide. For example, * goog.provide('goog.events.Event') implicitly declares that 'goog' and * 'goog.events' must be namespaces. * * @type {!Object<string, (boolean|undefined)>} * @private */ goog.implicitNamespaces_ = {'goog.module': true}; // NOTE: We add goog.module as an implicit namespace as goog.module is defined // here and because the existing module package has not been moved yet out of // the goog.module namespace. This satisifies both the debug loader and // ahead-of-time dependency management. } /** * Returns an object based on its fully qualified external name. The object * is not found if null or undefined. If you are using a compilation pass that * renames property names beware that using this function will not find renamed * properties. * * @param {string} name The fully qualified name. * @param {Object=} opt_obj The object within which to look; default is * |goog.global|. * @return {?} The value (object or primitive) or, if not found, null. */ goog.getObjectByName = function(name, opt_obj) { var parts = name.split('.'); var cur = opt_obj || goog.global; for (var i = 0; i < parts.length; i++) { cur = cur[parts[i]]; if (!goog.isDefAndNotNull(cur)) { return null; } } return cur; }; /** * Globalizes a whole namespace, such as goog or goog.lang. * * @param {!Object} obj The namespace to globalize. * @param {Object=} opt_global The object to add the properties to. * @deprecated Properties may be explicitly exported to the global scope, but * this should no longer be done in bulk. */ goog.globalize = function(obj, opt_global) { var global = opt_global || goog.global; for (var x in obj) { global[x] = obj[x]; } }; /** * Adds a dependency from a file to the files it requires. * @param {string} relPath The path to the js file. * @param {!Array<string>} provides An array of strings with * the names of the objects this file provides. * @param {!Array<string>} requires An array of strings with * the names of the objects this file requires. * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating * how the file must be loaded. The boolean 'true' is equivalent * to {'module': 'goog'} for backwards-compatibility. Valid properties * and values include {'module': 'goog'} and {'lang': 'es6'}. */ goog.addDependency = function(relPath, provides, requires, opt_loadFlags) { if (goog.DEPENDENCIES_ENABLED) { var loader = goog.getLoader_(); if (loader) { loader.addDependency(relPath, provides, requires, opt_loadFlags); } } }; // NOTE(nnaze): The debug DOM loader was included in base.js as an original way // to do "debug-mode" development. The dependency system can sometimes be // confusing, as can the debug DOM loader's asynchronous nature. // // With the DOM loader, a call to goog.require() is not blocking -- the script // will not load until some point after the current script. If a namespace is // needed at runtime, it needs to be defined in a previous script, or loaded via // require() with its registered dependencies. // // User-defined namespaces may need their own deps file. For a reference on // creating a deps file, see: // Externally: https://developers.google.com/closure/library/docs/depswriter // // Because of legacy clients, the DOM loader can't be easily removed from // base.js. Work was done to make it disableable or replaceable for // different environments (DOM-less JavaScript interpreters like Rhino or V8, // for example). See bootstrap/ for more information. /** * @define {boolean} Whether to enable the debug loader. * * If enabled, a call to goog.require() will attempt to load the namespace by * appending a script tag to the DOM (if the namespace has been registered). * * If disabled, goog.require() will simply assert that the namespace has been * provided (and depend on the fact that some outside tool correctly ordered * the script). */ goog.define('goog.ENABLE_DEBUG_LOADER', true); /** * @param {string} msg * @private */ goog.logToConsole_ = function(msg) { if (goog.global.console) { goog.global.console['error'](msg); } }; /** * Implements a system for the dynamic resolution of dependencies that works in * parallel with the BUILD system. Note that all calls to goog.require will be * stripped by the compiler. * @see goog.provide * @param {string} name Namespace to include (as was given in goog.provide()) in * the form "goog.package.part". * @return {?} If called within a goog.module file, the associated namespace or * module otherwise null. */ goog.require = function(name) { if (goog.ENABLE_DEBUG_LOADER && goog.debugLoader_) { goog.getLoader_().earlyProcessLoad(name); } // If the object already exists we do not need to do anything. if (!COMPILED) { if (goog.isProvided_(name)) { if (goog.isInModuleLoader_()) { return goog.module.getInternal_(name); } } else if (goog.ENABLE_DEBUG_LOADER) { var moduleLoaderState = goog.moduleLoaderState_; goog.moduleLoaderState_ = null; try { var loader = goog.getLoader_(); if (loader) { loader.load(name); } else { goog.logToConsole_( 'Could not load ' + name + ' because there is no debug loader.'); } } finally { goog.moduleLoaderState_ = moduleLoaderState; } } return null; } }; /** * Path for included scripts. * @type {string} */ goog.basePath = ''; /** * A hook for overriding the base path. * @type {string|undefined} */ goog.global.CLOSURE_BASE_PATH; /** * Whether to attempt to load Closure's deps file. By default, when uncompiled, * deps files will attempt to be loaded. * @type {boolean|undefined} */ goog.global.CLOSURE_NO_DEPS; /** * A function to import a single script. This is meant to be overridden when * Closure is being run in non-HTML contexts, such as web workers. It's defined * in the global scope so that it can be set before base.js is loaded, which * allows deps.js to be imported properly. * * The function is passed the script source, which is a relative URI. It should * return true if the script was imported, false otherwise. * @type {(function(string): boolean)|undefined} */ goog.global.CLOSURE_IMPORT_SCRIPT; /** * Null function used for default values of callbacks, etc. * @return {void} Nothing. */ goog.nullFunction = function() {}; /** * When defining a class Foo with an abstract method bar(), you can do: * Foo.prototype.bar = goog.abstractMethod * * Now if a subclass of Foo fails to override bar(), an error will be thrown * when bar() is invoked. * * @type {!Function} * @throws {Error} when invoked to indicate the method should be overridden. */ goog.abstractMethod = function() { throw new Error('unimplemented abstract method'); }; /** * Adds a `getInstance` static method that always returns the same * instance object. * @param {!Function} ctor The constructor for the class to add the static * method to. * @suppress {missingProperties} 'instance_' isn't a property on 'Function' * but we don't have a better type to use here. */ goog.addSingletonGetter = function(ctor) { // instance_ is immediately set to prevent issues with sealed constructors // such as are encountered when a constructor is returned as the export object // of a goog.module in unoptimized code. ctor.instance_ = undefined; ctor.getInstance = function() { if (ctor.instance_) { return ctor.instance_; } if (goog.DEBUG) { // NOTE: JSCompiler can't optimize away Array#push. goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor; } return ctor.instance_ = new ctor; }; }; /** * All singleton classes that have been instantiated, for testing. Don't read * it directly, use the `goog.testing.singleton` module. The compiler * removes this variable if unused. * @type {!Array<!Function>} * @private */ goog.instantiatedSingletons_ = []; /** * @define {boolean} Whether to load goog.modules using `eval` when using * the debug loader. This provides a better debugging experience as the * source is unmodified and can be edited using Chrome Workspaces or similar. * However in some environments the use of `eval` is banned * so we provide an alternative. */ goog.define('goog.LOAD_MODULE_USING_EVAL', true); /** * @define {boolean} Whether the exports of goog.modules should be sealed when * possible. */ goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG); /** * The registry of initialized modules: * the module identifier to module exports map. * @private @const {!Object<string, ?>} */ goog.loadedModules_ = {}; /** * True if goog.dependencies_ is available. * @const {boolean} */ goog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER; /** * @define {string} How to decide whether to transpile. Valid values * are 'always', 'never', and 'detect'. The default ('detect') is to * use feature detection to determine which language levels need * transpilation. */ // NOTE(user): we could expand this to accept a language level to bypass // detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but // would leave ES3 and ES5 files alone. goog.define('goog.TRANSPILE', 'detect'); /** * @define {string} Path to the transpiler. Executing the script at this * path (relative to base.js) should define a function $jscomp.transpile. */ goog.define('goog.TRANSPILER', 'transpile.js'); /** * @define {string} Debug loader file to load. This file should define an * implementation of a `goog.DebugLoader` and register it via * `goog.registerDebugLoader`. */ goog.define('goog.DEBUG_LOADER', ''); /** * @package {?boolean} * Visible for testing. */ goog.hasBadLetScoping = null; /** * @return {boolean} * @package Visible for testing. */ goog.useSafari10Workaround = function() { if (goog.hasBadLetScoping == null) { var hasBadLetScoping; try { hasBadLetScoping = !eval( '"use strict";' + 'let x = 1; function f() { return typeof x; };' + 'f() == "number";'); } catch (e) { // Assume that ES6 syntax isn't supported. hasBadLetScoping = false; } goog.hasBadLetScoping = hasBadLetScoping; } return goog.hasBadLetScoping; }; /** * @param {string} moduleDef * @return {string} * @package Visible for testing. */ goog.workaroundSafari10EvalBug = function(moduleDef) { return '(function(){' + moduleDef + '\n' + // Terminate any trailing single line comment. ';' + // Terminate any trailing expression. '})();\n'; }; /** * @param {function(?):?|string} moduleDef The module definition. */ goog.loadModule = function(moduleDef) { // NOTE: we allow function definitions to be either in the from // of a string to eval (which keeps the original source intact) or // in a eval forbidden environment (CSP) we allow a function definition // which in its body must call `goog.module`, and return the exports // of the module. var previousState = goog.moduleLoaderState_; try { goog.moduleLoaderState_ = {moduleName: '', declareLegacyNamespace: false}; var exports; if (goog.isFunction(moduleDef)) { exports = moduleDef.call(undefined, {}); } else if (goog.isString(moduleDef)) { if (goog.useSafari10Workaround()) { moduleDef = goog.workaroundSafari10EvalBug(moduleDef); } exports = goog.loadModuleFromSource_.call(undefined, moduleDef); } else { throw new Error('Invalid module definition'); } var moduleName = goog.moduleLoaderState_.moduleName; if (goog.isString(moduleName) && moduleName) { // Don't seal legacy namespaces as they may be used as a parent of // another namespace if (goog.moduleLoaderState_.declareLegacyNamespace) { goog.constructNamespace_(moduleName, exports); } else if ( goog.SEAL_MODULE_EXPORTS && Object.seal && typeof exports == 'object' && exports != null) { Object.seal(exports); } goog.loadedModules_[moduleName] = exports; } else { throw new Error('Invalid module name \"' + moduleName + '\"'); } } finally { goog.moduleLoaderState_ = previousState; } }; /** * @private @const */ goog.loadModuleFromSource_ = /** @type {function(string):?} */ (function() { // NOTE: we avoid declaring parameters or local variables here to avoid // masking globals or leaking values into the module definition. 'use strict'; var exports = {}; eval(arguments[0]); return exports; }); /** * Normalize a file path by removing redundant ".." and extraneous "." file * path components. * @param {string} path * @return {string} * @private */ goog.normalizePath_ = function(path) { var components = path.split('/'); var i = 0; while (i < components.length) { if (components[i] == '.') { components.splice(i, 1); } else if ( i && components[i] == '..' && components[i - 1] && components[i - 1] != '..') { components.splice(--i, 2); } else { i++; } } return components.join('/'); }; /** * Provides a hook for loading a file when using Closure's goog.require() API * with goog.modules. In particular this hook is provided to support Node.js. * * @type {(function(string):string)|undefined} */ goog.global.CLOSURE_LOAD_FILE_SYNC; /** * Loads file by synchronous XHR. Should not be used in production environments. * @param {string} src Source URL. * @return {?string} File contents, or null if load failed. * @private */ goog.loadFileSync_ = function(src) { if (goog.global.CLOSURE_LOAD_FILE_SYNC) { return goog.global.CLOSURE_LOAD_FILE_SYNC(src); } else { try { /** @type {XMLHttpRequest} */ var xhr = new goog.global['XMLHttpRequest'](); xhr.open('get', src, false); xhr.send(); // NOTE: Successful http: requests have a status of 200, but successful // file: requests may have a status of zero. Any other status, or a // thrown exception (particularly in case of file: requests) indicates // some sort of error, which we treat as a missing or unavailable file. return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null; } catch (err) { // No need to rethrow or log, since errors should show up on their own. return null; } } }; /** * Lazily retrieves the transpiler and applies it to the source. * @param {string} code JS code. * @param {string} path Path to the code. * @return {string} The transpiled code. * @private */ goog.transpile_ = function(code, path) { var jscomp = goog.global['$jscomp']; if (!jscomp) { goog.global['$jscomp'] = jscomp = {}; } var transpile = jscomp.transpile; if (!transpile) { var transpilerPath = goog.basePath + goog.TRANSPILER; var transpilerCode = goog.loadFileSync_(transpilerPath); if (transpilerCode) { // This must be executed synchronously, since by the time we know we // need it, we're about to load and write the ES6 code synchronously, // so a normal script-tag load will be too slow. Wrapped in a function // so that code is eval'd in the global scope. (function() { eval(transpilerCode + '\n//# sourceURL=' + transpilerPath); }).call(goog.global); // Even though the transpiler is optional, if $gwtExport is found, it's // a sign the transpiler was loaded and the $jscomp.transpile *should* // be there. if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] && !goog.global['$gwtExport']['$jscomp']['transpile']) { throw new Error( 'The transpiler did not properly export the "transpile" ' + 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport'])); } // transpile.js only exports a single $jscomp function, transpile. We // grab just that and add it to the existing definition of $jscomp which // contains the polyfills. goog.global['$jscomp'].transpile = goog.global['$gwtExport']['$jscomp']['transpile']; jscomp = goog.global['$jscomp']; transpile = jscomp.transpile; } } if (!transpile) { // The transpiler is an optional component. If it's not available then // replace it with a pass-through function that simply logs. var suffix = ' requires transpilation but no transpiler was found.'; transpile = jscomp.transpile = function(code, path) { // TODO(user): figure out some way to get this error to show up // in test results, noting that the failure may occur in many // different ways, including in loadModule() before the test // runner even comes up. goog.logToConsole_(path + suffix); return code; }; } // Note: any transpilation errors/warnings will be logged to the console. return transpile(code, path); }; //============================================================================== // Language Enhancements //============================================================================== /** * This is a "fixed" version of the typeof operator. It differs from the typeof * operator in such a way that null returns 'null' and arrays return 'array'. * @param {?} value The value to get the type of. * @return {string} The name of the type. */ goog.typeOf = function(value) { var s = typeof value; if (s == 'object') { if (value) { // Check these first, so we can avoid calling Object.prototype.toString if // possible. // // IE improperly marshals typeof across execution contexts, but a // cross-context object will still return false for "instanceof Object". if (value instanceof Array) { return 'array'; } else if (value instanceof Object) { return s; } // HACK: In order to use an Object prototype method on the arbitrary // value, the compiler requires the value be cast to type Object, // even though the ECMA spec explicitly allows it. var className = Object.prototype.toString.call( /** @type {!Object} */ (value)); // In Firefox 3.6, attempting to access iframe window objects' length // property throws an NS_ERROR_FAILURE, so we need to special-case it // here. if (className == '[object Window]') { return 'object'; } // We cannot always use constructor == Array or instanceof Array because // different frames have different Array objects. In IE6, if the iframe // where the array was created is destroyed, the array loses its // prototype. Then dereferencing val.splice here throws an exception, so // we can't use goog.isFunction. Calling typeof directly returns 'unknown' // so that will work. In this case, this function will return false and // most array functions will still work because the array is still // array-like (supports length and []) even though it has lost its // prototype. // <NAME> noticed that Object.prototype.toString // allows access to the unforgeable [[Class]] property. // 15.2.4.2 Object.prototype.toString ( ) // When the toString method is called, the following steps are taken: // 1. Get the [[Class]] property of this object. // 2. Compute a string value by concatenating the three strings // "[object ", Result(1), and "]". // 3. Return Result(2). // and this behavior survives the destruction of the execution context. if ((className == '[object Array]' || // In IE all non value types are wrapped as objects across window // boundaries (not iframe though) so we have to do object detection // for this edge case. typeof value.length == 'number' && typeof value.splice != 'undefined' && typeof value.propertyIsEnumerable != 'undefined' && !value.propertyIsEnumerable('splice') )) { return 'array'; } // HACK: There is still an array case that fails. // function ArrayImpostor() {} // ArrayImpostor.prototype = []; // var impostor = new ArrayImpostor; // this can be fixed by getting rid of the fast path // (value instanceof Array) and solely relying on // (value && Object.prototype.toString.vall(value) === '[object Array]') // but that would require many more function calls and is not warranted // unless closure code is receiving objects from untrusted sources. // IE in cross-window calls does not correctly marshal the function type // (it appears just as an object) so we cannot use just typeof val == // 'function'. However, if the object has a call property, it is a // function. if ((className == '[object Function]' || typeof value.call != 'undefined' && typeof value.propertyIsEnumerable != 'undefined' && !value.propertyIsEnumerable('call'))) { return 'function'; } } else { return 'null'; } } else if (s == 'function' && typeof value.call == 'undefined') { // In Safari typeof nodeList returns 'function', and on Firefox typeof // behaves similarly for HTML{Applet,Embed,Object}, Elements and RegExps. We // would like to return object for those and we can detect an invalid // function by making sure that the function object has a call method. return 'object'; } return s; }; /** * Returns true if the specified value is null. * @param {?} val Variable to test. * @return {boolean} Whether variable is null. */ goog.isNull = function(val) { return val === null; }; /** * Returns true if the specified value is defined and not null. * @param {?} val Variable to test. * @return {boolean} Whether variable is defined and not null. */ goog.isDefAndNotNull = function(val) { // Note that undefined == null. return val != null; }; /** * Returns true if the specified value is an array. * @param {?} val Variable to test. * @return {boolean} Whether variable is an array. */ goog.isArray = function(val) { return goog.typeOf(val) == 'array'; }; /** * Returns true if the object looks like an array. To qualify as array like * the value needs to be either a NodeList or an object with a Number length * property. Note that for this function neither strings nor functions are * considered "array-like". * * @param {?} val Variable to test. * @return {boolean} Whether variable is an array. */ goog.isArrayLike = function(val) { var type = goog.typeOf(val); // We do not use goog.isObject here in order to exclude function values. return type == 'array' || type == 'object' && typeof val.length == 'number'; }; /** * Returns true if the object looks like a Date. To qualify as Date-like the * value needs to be an object and have a getFullYear() function. * @param {?} val Variable to test. * @return {boolean} Whether variable is a like a Date. */ goog.isDateLike = function(val) { return goog.isObject(val) && typeof val.getFullYear == 'function'; }; /** * Returns true if the specified value is a function. * @param {?} val Variable to test. * @return {boolean} Whether variable is a function. */ goog.isFunction = function(val) { return goog.typeOf(val) == 'function'; }; /** * Returns true if the specified value is an object. This includes arrays and * functions. * @param {?} val Variable to test. * @return {boolean} Whether variable is an object. */ goog.isObject = function(val) { var type = typeof val; return type == 'object' && val != null || type == 'function'; // return Object(val) === val also works, but is slower, especially if val is // not an object. }; /** * Gets a unique ID for an object. This mutates the object so that further calls * with the same object as a parameter returns the same value. The unique ID is * guaranteed to be unique across the current session amongst objects that are * passed into `getUid`. There is no guarantee that the ID is unique or * consistent across sessions. It is unsafe to generate unique ID for function * prototypes. * * @param {Object} obj The object to get the unique ID for. * @return {number} The unique ID for the object. */ goog.getUid = function(obj) { // TODO(arv): Make the type stricter, do not accept null. // In Opera window.hasOwnProperty exists but always returns false so we avoid // using it. As a consequence the unique ID generated for BaseClass.prototype // and SubClass.prototype will be the same. return obj[goog.UID_PROPERTY_] || (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_); }; /** * Whether the given object is already assigned a unique ID. * * This does not modify the object. * * @param {!Object} obj The object to check. * @return {boolean} Whether there is an assigned unique id for the object. */ goog.hasUid = function(obj) { return !!obj[goog.UID_PROPERTY_]; }; /** * Removes the unique ID from an object. This is useful if the object was * previously mutated using `goog.getUid` in which case the mutation is * undone. * @param {Object} obj The object to remove the unique ID field from. */ goog.removeUid = function(obj) { // TODO(arv): Make the type stricter, do not accept null. // In IE, DOM nodes are not instances of Object and throw an exception if we // try to delete. Instead we try to use removeAttribute. if (obj !== null && 'removeAttribute' in obj) { obj.removeAttribute(goog.UID_PROPERTY_); } try { delete obj[goog.UID_PROPERTY_]; } catch (ex) { } }; /** * Name for unique ID property. Initialized in a way to help avoid collisions * with other closure JavaScript on the same page. * @type {string} * @private */ goog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0); /** * Counter for UID. * @type {number} * @private */ goog.uidCounter_ = 0; /** * Adds a hash code field to an object. The hash code is unique for the * given object. * @param {Object} obj The object to get the hash code for. * @return {number} The hash code for the object. * @deprecated Use goog.getUid instead. */ goog.getHashCode = goog.getUid; /** * Removes the hash code field from an object. * @param {Object} obj The object to remove the field from. * @deprecated Use goog.removeUid instead. */ goog.removeHashCode = goog.removeUid; /** * Clones a value. The input may be an Object, Array, or basic type. Objects and * arrays will be cloned recursively. * * WARNINGS: * <code>goog.cloneObject</code> does not detect reference loops. Objects that * refer to themselves will cause infinite recursion. * * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies * UIDs created by <code>getUid</code> into cloned results. * * @param {*} obj The value to clone. * @return {*} A clone of the input value. * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods. */ goog.cloneObject = function(obj) { var type = goog.typeOf(obj); if (type == 'object' || type == 'array') { if (typeof obj.clone === 'function') { return obj.clone(); } var clone = type == 'array' ? [] : {}; for (var key in obj) { clone[key] = goog.cloneObject(obj[key]); } return clone; } return obj; }; /** * A native implementation of goog.bind. * @param {?function(this:T, ...)} fn A function to partially apply. * @param {T} selfObj Specifies the object which this should point to when the * function is run. * @param {...*} var_args Additional arguments that are partially applied to the * function. * @return {!Function} A partially-applied form of the function goog.bind() was * invoked as a method of. * @template T * @private */ goog.bindNative_ = function(fn, selfObj, var_args) { return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments)); }; /** * A pure-JS implementation of goog.bind. * @param {?function(this:T, ...)} fn A function to partially apply. * @param {T} selfObj Specifies the object which this should point to when the * function is run. * @param {...*} var_args Additional arguments that are partially applied to the * function. * @return {!Function} A partially-applied form of the function goog.bind() was * invoked as a method of. * @template T * @private */ goog.bindJs_ = function(fn, selfObj, var_args) { if (!fn) { throw new Error(); } if (arguments.length > 2) { var boundArgs = Array.prototype.slice.call(arguments, 2); return function() { // Prepend the bound arguments to the current arguments. var newArgs = Array.prototype.slice.call(arguments); Array.prototype.unshift.apply(newArgs, boundArgs); return fn.apply(selfObj, newArgs); }; } else { return function() { return fn.apply(selfObj, arguments); }; } }; /** * Partially applies this function to a particular 'this object' and zero or * more arguments. The result is a new function with some arguments of the first * function pre-filled and the value of this 'pre-specified'. * * Remaining arguments specified at call-time are appended to the pre-specified * ones. * * Also see: {@link #partial}. * * Usage: * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2'); * barMethBound('arg3', 'arg4');</pre> * * @param {?function(this:T, ...)} fn A function to partially apply. * @param {T} selfObj Specifies the object which this should point to when the * function is run. * @param {...*} var_args Additional arguments that are partially applied to the * function. * @return {!Function} A partially-applied form of the function goog.bind() was * invoked as a method of. * @template T * @suppress {deprecated} See above. */ goog.bind = function(fn, selfObj, var_args) { // TODO(nicksantos): narrow the type signature. if (Function.prototype.bind && // NOTE(nicksantos): Somebody pulled base.js into the default Chrome // extension environment. This means that for Chrome extensions, they get // the implementation of Function.prototype.bind that calls goog.bind // instead of the native one. Even worse, we don't want to introduce a // circular dependency between goog.bind and Function.prototype.bind, so // we have to hack this to make sure it works correctly. Function.prototype.bind.toString().indexOf('native code') != -1) { goog.bind = goog.bindNative_; } else { goog.bind = goog.bindJs_; } return goog.bind.apply(null, arguments); }; /** * Like goog.bind(), except that a 'this object' is not required. Useful when * the target function is already bound. * * Usage: * var g = goog.partial(f, arg1, arg2); * g(arg3, arg4); * * @param {Function} fn A function to partially apply. * @param {...*} var_args Additional arguments that are partially applied to fn. * @return {!Function} A partially-applied form of the function goog.partial() * was invoked as a method of. */ goog.partial = function(fn, var_args) { var args = Array.prototype.slice.call(arguments, 1); return function() { // Clone the array (with slice()) and append additional arguments // to the existing arguments. var newArgs = args.slice(); newArgs.push.apply(newArgs, arguments); return fn.apply(this, newArgs); }; }; /** * Copies all the members of a source object to a target object. This method * does not work on all browsers for all objects that contain keys such as * toString or hasOwnProperty. Use goog.object.extend for this purpose. * @param {Object} target Target. * @param {Object} source Source. */ goog.mixin = function(target, source) { for (var x in source) { target[x] = source[x]; } // For IE7 or lower, the for-in-loop does not contain any properties that are // not enumerable on the prototype object (for example, isPrototypeOf from // Object.prototype) but also it will not include 'replace' on objects that // extend String and change 'replace' (not that it is common for anyone to // extend anything except Object). }; /** * @return {number} An integer value representing the number of milliseconds * between midnight, January 1, 1970 and the current time. */ goog.now = (goog.TRUSTED_SITE && Date.now) || (function() { // Unary plus operator converts its operand to a number which in // the case of // a date is done by calling getTime(). return +new Date(); }); /** * Evals JavaScript in the global scope. In IE this uses execScript, other * browsers use goog.global.eval. If goog.global.eval does not evaluate in the * global scope (for example, in Safari), appends a script tag instead. * Throws an exception if neither execScript or eval is defined. * @param {string} script JavaScript string. */ goog.globalEval = function(script) { if (goog.global.execScript) { goog.global.execScript(script, 'JavaScript'); } else if (goog.global.eval) { // Test to see if eval works if (goog.evalWorksForGlobals_ == null) { try { goog.global.eval('var _evalTest_ = 1;'); } catch (ignore) { } if (typeof goog.global['_evalTest_'] != 'undefined') { try { delete goog.global['_evalTest_']; } catch (ignore) { // Microsoft edge fails the deletion above in strict mode. } goog.evalWorksForGlobals_ = true; } else { goog.evalWorksForGlobals_ = false; } } if (goog.evalWorksForGlobals_) { goog.global.eval(script); } else { /** @type {!Document} */ var doc = goog.global.document; var scriptElt = /** @type {!HTMLScriptElement} */ (doc.createElement('SCRIPT')); scriptElt.type = 'text/javascript'; scriptElt.defer = false; // Note(user): can't use .innerHTML since "t('<test>')" will fail and // .text doesn't work in Safari 2. Therefore we append a text node. scriptElt.appendChild(doc.createTextNode(script)); doc.head.appendChild(scriptElt); doc.head.removeChild(scriptElt); } } else { throw new Error('goog.globalEval not available'); } }; /** * Indicates whether or not we can call 'eval' directly to eval code in the * global scope. Set to a Boolean by the first call to goog.globalEval (which * empirically tests whether eval works for globals). @see goog.globalEval * @type {?boolean} * @private */ goog.evalWorksForGlobals_ = null; /** * Optional map of CSS class names to obfuscated names used with * goog.getCssName(). * @private {!Object<string, string>|undefined} * @see goog.setCssNameMapping */ goog.cssNameMapping_; /** * Optional obfuscation style for CSS class names. Should be set to either * 'BY_WHOLE' or 'BY_PART' if defined. * @type {string|undefined} * @private * @see goog.setCssNameMapping */ goog.cssNameMappingStyle_; /** * A hook for modifying the default behavior goog.getCssName. The function * if present, will receive the standard output of the goog.getCssName as * its input. * * @type {(function(string):string)|undefined} */ goog.global.CLOSURE_CSS_NAME_MAP_FN; /** * Handles strings that are intended to be used as CSS class names. * * This function works in tandem with @see goog.setCssNameMapping. * * Without any mapping set, the arguments are simple joined with a hyphen and * passed through unaltered. * * When there is a mapping, there are two possible styles in which these * mappings are used. In the BY_PART style, each part (i.e. in between hyphens) * of the passed in css name is rewritten according to the map. In the BY_WHOLE * style, the full css name is looked up in the map directly. If a rewrite is * not specified by the map, the compiler will output a warning. * * When the mapping is passed to the compiler, it will replace calls to * goog.getCssName with the strings from the mapping, e.g. * var x = goog.getCssName('foo'); * var y = goog.getCssName(this.baseClass, 'active'); * becomes: * var x = 'foo'; * var y = this.baseClass + '-active'; * * If one argument is passed it will be processed, if two are passed only the * modifier will be processed, as it is assumed the first argument was generated * as a result of calling goog.getCssName. * * @param {string} className The class name. * @param {string=} opt_modifier A modifier to be appended to the class name. * @return {string} The class name or the concatenation of the class name and * the modifier. */ goog.getCssName = function(className, opt_modifier) { // String() is used for compatibility with compiled soy where the passed // className can be non-string objects. if (String(className).charAt(0) == '.') { throw new Error( 'className passed in goog.getCssName must not start with ".".' + ' You passed: ' + className); } var getMapping = function(cssName) { return goog.cssNameMapping_[cssName] || cssName; }; var renameByParts = function(cssName) { // Remap all the parts individually. var parts = cssName.split('-'); var mapped = []; for (var i = 0; i < parts.length; i++) { mapped.push(getMapping(parts[i])); } return mapped.join('-'); }; var rename; if (goog.cssNameMapping_) { rename = goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts; } else { rename = function(a) { return a; }; } var result = opt_modifier ? className + '-' + rename(opt_modifier) : rename(className); // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further // processing of the class name. if (goog.global.CLOSURE_CSS_NAME_MAP_FN) { return goog.global.CLOSURE_CSS_NAME_MAP_FN(result); } return result; }; /** * Sets the map to check when returning a value from goog.getCssName(). Example: * <pre> * goog.setCssNameMapping({ * "goog": "a", * "disabled": "b", * }); * * var x = goog.getCssName('goog'); * // The following evaluates to: "a a-b". * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled') * </pre> * When declared as a map of string literals to string literals, the JSCompiler * will replace all calls to goog.getCssName() using the supplied map if the * --process_closure_primitives flag is set. * * @param {!Object} mapping A map of strings to strings where keys are possible * arguments to goog.getCssName() and values are the corresponding values * that should be returned. * @param {string=} opt_style The style of css name mapping. There are two valid * options: 'BY_PART', and 'BY_WHOLE'. * @see goog.getCssName for a description. */ goog.setCssNameMapping = function(mapping, opt_style) { goog.cssNameMapping_ = mapping; goog.cssNameMappingStyle_ = opt_style; }; /** * To use CSS renaming in compiled mode, one of the input files should have a * call to goog.setCssNameMapping() with an object literal that the JSCompiler * can extract and use to replace all calls to goog.getCssName(). In uncompiled * mode, JavaScript code should be loaded before this base.js file that declares * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is * to ensure that the mapping is loaded before any calls to goog.getCssName() * are made in uncompiled mode. * * A hook for overriding the CSS name mapping. * @type {!Object<string, string>|undefined} */ goog.global.CLOSURE_CSS_NAME_MAPPING; if (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) { // This does not call goog.setCssNameMapping() because the JSCompiler // requires that goog.setCssNameMapping() be called with an object literal. goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING; } /** * Gets a localized message. * * This function is a compiler primitive. If you give the compiler a localized * message bundle, it will replace the string at compile-time with a localized * version, and expand goog.getMsg call to a concatenated string. * * Messages must be initialized in the form: * <code> * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'}); * </code> * * This function produces a string which should be treated as plain text. Use * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to * produce SafeHtml. * * @param {string} str Translatable string, places holders in the form {$foo}. * @param {Object<string, string>=} opt_values Maps place holder name to value. * @return {string} message with placeholders filled. */ goog.getMsg = function(str, opt_values) { if (opt_values) { str = str.replace(/\{\$([^}]+)}/g, function(match, key) { return (opt_values != null && key in opt_values) ? opt_values[key] : match; }); } return str; }; /** * Gets a localized message. If the message does not have a translation, gives a * fallback message. * * This is useful when introducing a new message that has not yet been * translated into all languages. * * This function is a compiler primitive. Must be used in the form: * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code> * where MSG_A and MSG_B were initialized with goog.getMsg. * * @param {string} a The preferred message. * @param {string} b The fallback message. * @return {string} The best translated message. */ goog.getMsgWithFallback = function(a, b) { return a; }; /** * Exposes an unobfuscated global namespace path for the given object. * Note that fields of the exported object *will* be obfuscated, unless they are * exported in turn via this function or goog.exportProperty. * * Also handy for making public items that are defined in anonymous closures. * * ex. goog.exportSymbol('public.path.Foo', Foo); * * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction); * public.path.Foo.staticFunction(); * * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod', * Foo.prototype.myMethod); * new public.path.Foo().myMethod(); * * @param {string} publicPath Unobfuscated name to export. * @param {*} object Object the name should point to. * @param {Object=} opt_objectToExportTo The object to add the path to; default * is goog.global. */ goog.exportSymbol = function(publicPath, object, opt_objectToExportTo) { goog.exportPath_(publicPath, object, opt_objectToExportTo); }; /** * Exports a property unobfuscated into the object's namespace. * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction); * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod); * @param {Object} object Object whose static property is being exported. * @param {string} publicName Unobfuscated name to export. * @param {*} symbol Object the name should point to. */ goog.exportProperty = function(object, publicName, symbol) { object[publicName] = symbol; }; /** * Inherit the prototype methods from one constructor into another. * * Usage: * <pre> * function ParentClass(a, b) { } * ParentClass.prototype.foo = function(a) { }; * * function ChildClass(a, b, c) { * ChildClass.base(this, 'constructor', a, b); * } * goog.inherits(ChildClass, ParentClass); * * var child = new ChildClass('a', 'b', 'see'); * child.foo(); // This works. * </pre> * * @param {!Function} childCtor Child class. * @param {!Function} parentCtor Parent class. * @suppress {strictMissingProperties} superClass_ and base is not defined on * Function. */ goog.inherits = function(childCtor, parentCtor) { /** @constructor */ function tempCtor() {} tempCtor.prototype = parentCtor.prototype; childCtor.superClass_ = parentCtor.prototype; childCtor.prototype = new tempCtor(); /** @override */ childCtor.prototype.constructor = childCtor; /** * Calls superclass constructor/method. * * This function is only available if you use goog.inherits to * express inheritance relationships between classes. * * NOTE: This is a replacement for goog.base and for superClass_ * property defined in childCtor. * * @param {!Object} me Should always be "this". * @param {string} methodName The method name to call. Calling * superclass constructor can be done with the special string * 'constructor'. * @param {...*} var_args The arguments to pass to superclass * method/constructor. * @return {*} The return value of the superclass method/constructor. */ childCtor.base = function(me, methodName, var_args) { // Copying using loop to avoid deop due to passing arguments object to // function. This is faster in many JS engines as of late 2014. var args = new Array(arguments.length - 2); for (var i = 2; i < arguments.length; i++) { args[i - 2] = arguments[i]; } return parentCtor.prototype[methodName].apply(me, args); }; }; /** * Call up to the superclass. * * If this is called from a constructor, then this calls the superclass * constructor with arguments 1-N. * * If this is called from a prototype method, then you must pass the name of the * method as the second argument to this function. If you do not, you will get a * runtime error. This calls the superclass' method with arguments 2-N. * * This function only works if you use goog.inherits to express inheritance * relationships between your classes. * * This function is a compiler primitive. At compile-time, the compiler will do * macro expansion to remove a lot of the extra overhead that this function * introduces. The compiler will also enforce a lot of the assumptions that this * function makes, and treat it as a compiler error if you break them. * * @param {!Object} me Should always be "this". * @param {*=} opt_methodName The method name if calling a super method. * @param {...*} var_args The rest of the arguments. * @return {*} The return value of the superclass method. * @suppress {es5Strict} This method can not be used in strict mode, but * all Closure Library consumers must depend on this file. * @deprecated goog.base is not strict mode compatible. Prefer the static * "base" method added to the constructor by goog.inherits * or ES6 classes and the "super" keyword. */ goog.base = function(me, opt_methodName, var_args) { var caller = arguments.callee.caller; if (goog.STRICT_MODE_COMPATIBLE || (goog.DEBUG && !caller)) { throw new Error( 'arguments.caller not defined. goog.base() cannot be used ' + 'with strict mode code. See ' + 'http://www.ecma-international.org/ecma-262/5.1/#sec-C'); } if (typeof caller.superClass_ !== 'undefined') { // Copying using loop to avoid deop due to passing arguments object to // function. This is faster in many JS engines as of late 2014. var ctorArgs = new Array(arguments.length - 1); for (var i = 1; i < arguments.length; i++) { ctorArgs[i - 1] = arguments[i]; } // This is a constructor. Call the superclass constructor. return caller.superClass_.constructor.apply(me, ctorArgs); } // Copying using loop to avoid deop due to passing arguments object to // function. This is faster in many JS engines as of late 2014. var args = new Array(arguments.length - 2); for (var i = 2; i < arguments.length; i++) { args[i - 2] = arguments[i]; } var foundCaller = false; for (var ctor = me.constructor; ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) { if (ctor.prototype[opt_methodName] === caller) { foundCaller = true; } else if (foundCaller) { return ctor.prototype[opt_methodName].apply(me, args); } } // If we did not find the caller in the prototype chain, then one of two // things happened: // 1) The caller is an instance method. // 2) This method was not called by the right caller. if (me[opt_methodName] === caller) { return me.constructor.prototype[opt_methodName].apply(me, args); } else { throw new Error( 'goog.base called from a method of one name ' + 'to a method of a different name'); } }; /** * Allow for aliasing within scope functions. This function exists for * uncompiled code - in compiled code the calls will be inlined and the aliases * applied. In uncompiled code the function is simply run since the aliases as * written are valid JavaScript. * * * @param {function()} fn Function to call. This function can contain aliases * to namespaces (e.g. "var dom = goog.dom") or classes * (e.g. "var Timer = goog.Timer"). */ goog.scope = function(fn) { if (goog.isInModuleLoader_()) { throw new Error('goog.scope is not supported within a goog.module.'); } fn.call(goog.global); }; /* * To support uncompiled, strict mode bundles that use eval to divide source * like so: * eval('someSource;//# sourceUrl sourcefile.js'); * We need to export the globally defined symbols "goog" and "COMPILED". * Exporting "goog" breaks the compiler optimizations, so we required that * be defined externally. * NOTE: We don't use goog.exportSymbol here because we don't want to trigger * extern generation when that compiler option is enabled. */ if (!COMPILED) { goog.global['COMPILED'] = COMPILED; } //============================================================================== // goog.defineClass implementation //============================================================================== /** * Creates a restricted form of a Closure "class": * - from the compiler's perspective, the instance returned from the * constructor is sealed (no new properties may be added). This enables * better checks. * - the compiler will rewrite this definition to a form that is optimal * for type checking and optimization (initially this will be a more * traditional form). * * @param {Function} superClass The superclass, Object or null. * @param {goog.defineClass.ClassDescriptor} def * An object literal describing * the class. It may have the following properties: * "constructor": the constructor function * "statics": an object literal containing methods to add to the constructor * as "static" methods or a function that will receive the constructor * function as its only parameter to which static properties can * be added. * all other properties are added to the prototype. * @return {!Function} The class constructor. */ goog.defineClass = function(superClass, def) { // TODO(johnlenz): consider making the superClass an optional parameter. var constructor = def.constructor; var statics = def.statics; // Wrap the constructor prior to setting up the prototype and static methods. if (!constructor || constructor == Object.prototype.constructor) { constructor = function() { throw new Error( 'cannot instantiate an interface (no constructor defined).'); }; } var cls = goog.defineClass.createSealingConstructor_(constructor, superClass); if (superClass) { goog.inherits(cls, superClass); } // Remove all the properties that should not be copied to the prototype. delete def.constructor; delete def.statics; goog.defineClass.applyProperties_(cls.prototype, def); if (statics != null) { if (statics instanceof Function) { statics(cls); } else { goog.defineClass.applyProperties_(cls, statics); } } return cls; }; /** * @typedef {{ * constructor: (!Function|undefined), * statics: (Object|undefined|function(Function):void) * }} */ goog.defineClass.ClassDescriptor; /** * @define {boolean} Whether the instances returned by goog.defineClass should * be sealed when possible. * * When sealing is disabled the constructor function will not be wrapped by * goog.defineClass, making it incompatible with ES6 class methods. */ goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG); /** * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is * defined, this function will wrap the constructor in a function that seals the * results of the provided constructor function. * * @param {!Function} ctr The constructor whose results maybe be sealed. * @param {Function} superClass The superclass constructor. * @return {!Function} The replacement constructor. * @private */ goog.defineClass.createSealingConstructor_ = function(ctr, superClass) { if (!goog.defineClass.SEAL_CLASS_INSTANCES) { // Do now wrap the constructor when sealing is disabled. Angular code // depends on this for injection to work properly. return ctr; } // Compute whether the constructor is sealable at definition time, rather // than when the instance is being constructed. var superclassSealable = !goog.defineClass.isUnsealable_(superClass); /** * @this {Object} * @return {?} */ var wrappedCtr = function() { // Don't seal an instance of a subclass when it calls the constructor of // its super class as there is most likely still setup to do. var instance = ctr.apply(this, arguments) || this; instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_]; if (this.constructor === wrappedCtr && superclassSealable && Object.seal instanceof Function) { Object.seal(instance); } return instance; }; return wrappedCtr; }; /** * @param {Function} ctr The constructor to test. * @return {boolean} Whether the constructor has been tagged as unsealable * using goog.tagUnsealableClass. * @private */ goog.defineClass.isUnsealable_ = function(ctr) { return ctr && ctr.prototype && ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_]; }; // TODO(johnlenz): share these values with the goog.object /** * The names of the fields that are defined on Object.prototype. * @type {!Array<string>} * @private * @const */ goog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; // TODO(johnlenz): share this function with the goog.object /** * @param {!Object} target The object to add properties to. * @param {!Object} source The object to copy properties from. * @private */ goog.defineClass.applyProperties_ = function(target, source) { // TODO(johnlenz): update this to support ES5 getters/setters var key; for (key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } // For IE the for-in-loop does not contain any properties that are not // enumerable on the prototype object (for example isPrototypeOf from // Object.prototype) and it will also not include 'replace' on objects that // extend String and change 'replace' (not that it is common for anyone to // extend anything except Object). for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) { key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i]; if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } }; /** * Sealing classes breaks the older idiom of assigning properties on the * prototype rather than in the constructor. As such, goog.defineClass * must not seal subclasses of these old-style classes until they are fixed. * Until then, this marks a class as "broken", instructing defineClass * not to seal subclasses. * @param {!Function} ctr The legacy constructor to tag as unsealable. */ goog.tagUnsealableClass = function(ctr) { if (!COMPILED && goog.defineClass.SEAL_CLASS_INSTANCES) { ctr.prototype[goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_] = true; } }; /** * Name for unsealable tag property. * @const @private {string} */ goog.UNSEALABLE_CONSTRUCTOR_PROPERTY_ = 'goog_defineClass_legacy_unsealable'; if (goog.DEPENDENCIES_ENABLED) { /** * Tries to detect whether is in the context of an HTML document. * @return {boolean} True if it looks like HTML document. * @private */ goog.inHtmlDocument_ = function() { /** @type {!Document} */ var doc = goog.global.document; return doc != null && 'write' in doc; // XULDocument misses write. }; /** * Tries to detect the base path of base.js script that bootstraps Closure. * @private */ goog.findBasePath_ = function() { if (goog.isDef(goog.global.CLOSURE_BASE_PATH) && // Anti DOM-clobbering runtime check (b/37736576). goog.isString(goog.global.CLOSURE_BASE_PATH)) { goog.basePath = goog.global.CLOSURE_BASE_PATH; return; } else if (!goog.inHtmlDocument_()) { return; } /** @type {!Document} */ var doc = goog.global.document; // If we have a currentScript available, use it exclusively. var currentScript = doc.currentScript; if (currentScript) { var scripts = [currentScript]; } else { var scripts = doc.getElementsByTagName('SCRIPT'); } // Search backwards since the current script is in almost all cases the one // that has base.js. for (var i = scripts.length - 1; i >= 0; --i) { var script = /** @type {!HTMLScriptElement} */ (scripts[i]); var src = script.src; var qmark = src.lastIndexOf('?'); var l = qmark == -1 ? src.length : qmark; if (src.substr(l - 7, 7) == 'base.js') { goog.basePath = src.substr(0, l - 7); return; } } }; goog.findBasePath_(); /** @struct @constructor @final */ goog.Transpiler = function() { /** @private {?Object<string, boolean>} */ this.requiresTranspilation_ = null; }; /** * Returns a newly created map from language mode string to a boolean * indicating whether transpilation should be done for that mode. * * Guaranteed invariant: * For any two modes, l1 and l2 where l2 is a newer mode than l1, * `map[l1] == true` implies that `map[l2] == true`. * * Note this method is extracted and used elsewhere, so it cannot rely on * anything external (it should easily be able to be transformed into a * standalone, top level function). * * @private * @return {!Object<string, boolean>} */ goog.Transpiler.prototype.createRequiresTranspilation_ = function() { var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false}; var transpilationRequiredForAllLaterModes = false; /** * Adds an entry to requiresTranspliation for the given language mode. * * IMPORTANT: Calls must be made in order from oldest to newest language * mode. * @param {string} modeName * @param {function(): boolean} isSupported Returns true if the JS engine * supports the given mode. */ function addNewerLanguageTranspilationCheck(modeName, isSupported) { if (transpilationRequiredForAllLaterModes) { requiresTranspilation[modeName] = true; } else if (isSupported()) { requiresTranspilation[modeName] = false; } else { requiresTranspilation[modeName] = true; transpilationRequiredForAllLaterModes = true; } } /** * Does the given code evaluate without syntax errors and return a truthy * result? */ function /** boolean */ evalCheck(/** string */ code) { try { return !!eval(code); } catch (ignored) { return false; } } var userAgent = goog.global.navigator && goog.global.navigator.userAgent ? goog.global.navigator.userAgent : ''; // Identify ES3-only browsers by their incorrect treatment of commas. addNewerLanguageTranspilationCheck('es5', function() { return evalCheck('[1,].length==1'); }); addNewerLanguageTranspilationCheck('es6', function() { // Edge has a non-deterministic (i.e., not reproducible) bug with ES6: // https://github.com/Microsoft/ChakraCore/issues/1496. var re = /Edge\/(\d+)(\.\d)*/i; var edgeUserAgent = userAgent.match(re); if (edgeUserAgent && Number(edgeUserAgent[1]) < 15) { return false; } // Test es6: [FF50 (?), Edge 14 (?), Chrome 50] // (a) default params (specifically shadowing locals), // (b) destructuring, (c) block-scoped functions, // (d) for-of (const), (e) new.target/Reflect.construct var es6fullTest = 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' + 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' + 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' + 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' + '==3}'; return evalCheck('(()=>{"use strict";' + es6fullTest + '})()'); }); // TODO(joeltine): Remove es6-impl references for b/31340605. // Consider es6-impl (widely-implemented es6 features) to be supported // whenever es6 is supported. Technically es6-impl is a lower level of // support than es6, but we don't have tests specifically for it. addNewerLanguageTranspilationCheck('es6-impl', function() { return true; }); // ** and **= are the only new features in 'es7' addNewerLanguageTranspilationCheck('es7', function() { return evalCheck('2 ** 2 == 4'); }); // async functions are the only new features in 'es8' addNewerLanguageTranspilationCheck('es8', function() { return evalCheck('async () => 1, true'); }); // Object rest/spread. TODO(tbreisacher): Rename this to 'es9' if // rest/spread end up being finalized in the 2018 spec. addNewerLanguageTranspilationCheck('es_next', function() { return evalCheck('({...rest} = {}), true'); }); return requiresTranspilation; }; /** * Determines whether the given language needs to be transpiled. * @param {string} lang * @return {boolean} */ goog.Transpiler.prototype.needsTranspile = function(lang) { if (goog.TRANSPILE == 'always') { return true; } else if (goog.TRANSPILE == 'never') { return false; } else if (!this.requiresTranspilation_) { this.requiresTranspilation_ = this.createRequiresTranspilation_(); } if (lang in this.requiresTranspilation_) { return this.requiresTranspilation_[lang]; } else { throw new Error('Unknown language mode: ' + lang); } }; /** * Lazily retrieves the transpiler and applies it to the source. * @param {string} code JS code. * @param {string} path Path to the code. * @return {string} The transpiled code. */ goog.Transpiler.prototype.transpile = function(code, path) { // TODO(user): We should delete goog.transpile_ and just have this // function. But there's some compile error atm where goog.global is being // stripped incorrectly without this. return goog.transpile_(code, path); }; /** @private @final {!goog.Transpiler} */ goog.transpiler_ = new goog.Transpiler(); /** * A debug loader is responsible for downloading and executing javascript * files in an unbundled, uncompiled environment. * * @struct @constructor */ goog.DebugLoader = function() { /** * This object is used to keep track of dependencies and other data that is * used for loading scripts. * @private * @type {{ * loadFlags: !Object<string, !Object<string, string>>, * nameToPath: !Object<string, string>, * requires: !Object<string, !Object<string, boolean>>, * visited: !Object<string, boolean>, * written: !Object<string, boolean>, * deferred: !Object<string, string> * }} */ this.dependencies_ = { loadFlags: {}, // 1 to 1 nameToPath: {}, // 1 to 1 requires: {}, // 1 to many // Used when resolving dependencies to prevent us from visiting file // twice. visited: {}, written: {}, // Used to keep track of script files we have written. deferred: {} // Used to track deferred module evaluations in old IEs }; /** * Whether IE9 or earlier is waiting on a dependency. This ensures that * deferred modules that have no non-deferred dependencies actually get * loaded, since if we defer them and then never pull in a non-deferred * script, then `this.loadQueuedModules_` will never be called. Instead, * if not waiting on anything we simply don't defer in the first place. * @private {boolean} */ this.oldIeWaiting_ = false; /** @private {!Array<string>} */ this.queuedModules_ = []; /** @private {number} */ this.lastNonModuleScriptIndex_ = 0; }; /** * Whether the browser is IE9 or earlier, which needs special handling * for deferred modules. * @const @private {boolean} */ goog.DebugLoader.IS_OLD_IE_ = !!(!goog.global.atob && goog.global.document && goog.global.document.all); /** * Performs any needed preprocessing of a goog.require call. * * @param {string} name */ goog.DebugLoader.prototype.earlyProcessLoad = function(name) { if (goog.DebugLoader.IS_OLD_IE_) { this.maybeProcessDeferredDep_(name); } }; /** * Loads the given symbol along with any dependencies. * * @param {string} name */ goog.DebugLoader.prototype.load = function(name) { var pathToLoad = this.getPathFromDeps_(name); if (!pathToLoad) { var errorMessage = 'goog.require could not find: ' + name; this.logToConsole(errorMessage); throw Error(errorMessage); } else { /** @type {!Array<string>} The scripts we need to write this time. */ var scripts = []; var seenScript = {}; var deps = this.dependencies_; var loader = this; /** @param {string} path */ var visitNode = function(path) { if (path in deps.written) { return; } // We have already visited this one. We can get here if we have cyclic // dependencies. if (path in deps.visited) { return; } deps.visited[path] = true; if (path in deps.requires) { for (var requireName in deps.requires[path]) { // If the required name is defined, we assume that it was already // bootstrapped by other means. if (!loader.isProvided(requireName)) { if (requireName in deps.nameToPath) { visitNode(deps.nameToPath[requireName]); } else { throw Error('Undefined nameToPath for ' + requireName); } } } } if (!(path in seenScript)) { seenScript[path] = true; scripts.push(path); } }; visitNode(pathToLoad); // record that we are going to load all these scripts. for (var i = 0; i < scripts.length; i++) { var path = scripts[i]; this.dependencies_.written[path] = true; } for (var i = 0; i < scripts.length; i++) { var path = scripts[i]; if (path) { var loadFlags = deps.loadFlags[path] || {}; var languageLevel = loadFlags['lang'] || 'es3'; var needsTranspile = this.getTranspiler().needsTranspile(languageLevel); if (loadFlags['module'] == 'goog' || needsTranspile) { this.importProcessedScript_( goog.basePath + path, loadFlags['module'] == 'goog', needsTranspile); } else { this.importScript_(goog.basePath + path); } } else { throw Error('Undefined script input'); } } } }; /** * @param {string} relPath * @param {!Array<string>} provides * @param {!Array<string>} requires * @param {boolean|!Object<string>=} opt_loadFlags * @see goog.addDependency */ goog.DebugLoader.prototype.addDependency = function( relPath, provides, requires, opt_loadFlags) { var provide, require; var path = relPath.replace(/\\/g, '/'); var deps = this.dependencies_; if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') { opt_loadFlags = opt_loadFlags ? {'module': 'goog'} : {}; } for (var i = 0; provide = provides[i]; i++) { deps.nameToPath[provide] = path; deps.loadFlags[path] = opt_loadFlags; } for (var j = 0; require = requires[j]; j++) { if (!(path in deps.requires)) { deps.requires[path] = {}; } deps.requires[path][require] = true; } }; /** * Imports a script if, and only if, that script hasn't already been imported. * (Must be called at execution time) * @param {string} src Script source. * @param {string=} opt_sourceText The optionally source text to evaluate * @private */ goog.DebugLoader.prototype.importScript_ = function(src, opt_sourceText) { var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || goog.bind(this.writeScriptTag_, this); if (importScript(src, opt_sourceText)) { this.dependencies_.written[src] = true; } }; /** * Given a URL initiate retrieval and execution of a script that needs * pre-processing. * @param {string} src Script source URL. * @param {boolean} isModule Whether this is a goog.module. * @param {boolean} needsTranspile Whether this source needs transpilation. * @private */ goog.DebugLoader.prototype.importProcessedScript_ = function( src, isModule, needsTranspile) { // In an attempt to keep browsers from timing out loading scripts using // synchronous XHRs, put each load in its own script block. var bootstrap = 'goog.debugLoader_.retrieveAndExec_("' + src + '", ' + isModule + ', ' + needsTranspile + ');'; this.importScript_('', bootstrap); }; /** * Retrieve and execute a script that needs some sort of wrapping. * @param {string} src Script source URL. * @param {boolean} isModule Whether to load as a module. * @param {boolean} needsTranspile Whether to transpile down to ES3. * @private * @suppress {unusedPrivateMembers} */ goog.DebugLoader.prototype.retrieveAndExec_ = function( src, isModule, needsTranspile) { if (!COMPILED) { // The full but non-canonicalized URL for later use. var originalPath = src; // Canonicalize the path, removing any /./ or /../ since Chrome's // debugging console doesn't auto-canonicalize XHR loads as it does // <script> srcs. src = this.normalizePath(src); var importScript = goog.global.CLOSURE_IMPORT_SCRIPT || goog.bind(this.writeScriptTag_, this); var scriptText = this.loadFileSync(src); if (scriptText == null) { throw new Error('Load of "' + src + '" failed'); } if (needsTranspile) { scriptText = this.getTranspiler().transpile(scriptText, src); } if (isModule) { scriptText = this.wrapModule_(src, scriptText); } else { scriptText += '\n//# sourceURL=' + src; } var isOldIE = goog.DebugLoader.IS_OLD_IE_; if (isOldIE && this.oldIeWaiting_) { this.dependencies_.deferred[originalPath] = scriptText; this.queuedModules_.push(originalPath); } else { importScript(src, scriptText); } } }; /** * Return an appropriate module text. Suitable to insert into * a script tag (that is unescaped). * @param {string} srcUrl * @param {string} scriptText * @return {string} * @private */ goog.DebugLoader.prototype.wrapModule_ = function(srcUrl, scriptText) { if (!goog.LOAD_MODULE_USING_EVAL || !goog.isDef(goog.global.JSON)) { return '' + 'goog.loadModule(function(exports) {' + '"use strict";' + scriptText + '\n' + // terminate any trailing single line comment. ';return exports' + '});' + '\n//# sourceURL=' + srcUrl + '\n'; } else { return '' + 'goog.loadModule(' + goog.global.JSON.stringify( scriptText + '\n//# sourceURL=' + srcUrl + '\n') + ');'; } }; // On IE9 and earlier, it is necessary to handle // deferred module loads. In later browsers, the // code to be evaluated is simply inserted as a script // block in the correct order. To eval deferred // code at the right time, we piggy back on goog.require to call // this.maybeProcessDeferredDep_. // // The goog.requires are used both to bootstrap // the loading process (when no deps are available) and // declare that they should be available. // // Here we eval the sources, if all the deps are available // either already eval'd or goog.require'd. This will // be the case when all the dependencies have already // been loaded, and the dependent module is loaded. // // But this alone isn't sufficient because it is also // necessary to handle the case where there is no root // that is not deferred. For that there we register for an event // and trigger this.loadQueuedModules_ handle any remaining deferred // evaluations. /** * Handle any remaining deferred goog.module evals. * @private */ goog.DebugLoader.prototype.loadQueuedModules_ = function() { var count = this.queuedModules_.length; if (count > 0) { var queue = this.queuedModules_; this.queuedModules_ = []; for (var i = 0; i < count; i++) { var path = queue[i]; this.maybeProcessDeferredPath_(path); } } this.oldIeWaiting_ = false; }; /** * Eval the named module if its dependencies are * available. * @param {string} name The module to load. * @private */ goog.DebugLoader.prototype.maybeProcessDeferredDep_ = function(name) { if (this.isDeferredModule_(name) && this.allDepsAreAvailable_(name)) { var path = this.getPathFromDeps_(name); this.maybeProcessDeferredPath_(goog.basePath + path); } }; /** * @param {string} name The module to check. * @return {boolean} Whether the name represents a * module whose evaluation has been deferred. * @private */ goog.DebugLoader.prototype.isDeferredModule_ = function(name) { var path = this.getPathFromDeps_(name); var loadFlags = path && this.dependencies_.loadFlags[path] || {}; var languageLevel = loadFlags['lang'] || 'es3'; if (path && (loadFlags['module'] == 'goog' || this.getTranspiler().needsTranspile(languageLevel))) { var abspath = goog.basePath + path; return (abspath) in this.dependencies_.deferred; } return false; }; /** * @param {string} name The module to check. * @return {boolean} Whether the name represents a * module whose declared dependencies have all been loaded * (eval'd or a deferred module load) * @private */ goog.DebugLoader.prototype.allDepsAreAvailable_ = function(name) { var path = this.getPathFromDeps_(name); if (path && (path in this.dependencies_.requires)) { for (var requireName in this.dependencies_.requires[path]) { if (!this.isProvided(requireName) && !this.isDeferredModule_(requireName)) { return false; } } } return true; }; /** * @param {string} abspath * @private */ goog.DebugLoader.prototype.maybeProcessDeferredPath_ = function(abspath) { if (abspath in this.dependencies_.deferred) { var src = this.dependencies_.deferred[abspath]; delete this.dependencies_.deferred[abspath]; goog.globalEval(src); } }; /** * Writes a new script pointing to `src` directly into the DOM. * * NOTE: This method is not CSP-compliant. @see this.appendScriptSrcNode_ for * the fallback mechanism. * * @param {string} src The script URL. * @private */ goog.DebugLoader.prototype.writeScriptSrcNode_ = function(src) { goog.global.document.write( '<script type="text/javascript" src="' + src + '"></' + 'script>'); }; /** * Appends a new script node to the DOM using a CSP-compliant mechanism. This * method exists as a fallback for document.write (which is not allowed in a * strict CSP context, e.g., Chrome apps). * * NOTE: This method is not analogous to using document.write to insert a * <script> tag; specifically, the user agent will execute a script added by * document.write immediately after the current script block finishes * executing, whereas the DOM-appended script node will not be executed until * the entire document is parsed and executed. That is to say, this script is * added to the end of the script execution queue. * * The page must not attempt to call goog.required entities until after the * document has loaded, e.g., in or after the window.onload callback. * * @param {string} src The script URL. * @private */ goog.DebugLoader.prototype.appendScriptSrcNode_ = function(src) { /** @type {!Document} */ var doc = goog.global.document; var scriptEl = /** @type {!HTMLScriptElement} */ (doc.createElement('script')); scriptEl.type = 'text/javascript'; scriptEl.src = src; scriptEl.defer = false; scriptEl.async = false; doc.head.appendChild(scriptEl); }; /** * The default implementation of the import function. Writes a script tag to * import the script. * * @param {string} src The script url. * @param {string=} opt_sourceText The optionally source text to evaluate * @return {boolean} True if the script was imported, false otherwise. * @private */ goog.DebugLoader.prototype.writeScriptTag_ = function(src, opt_sourceText) { if (this.inHtmlDocument()) { /** @type {!HTMLDocument} */ var doc = goog.global.document; // If the user tries to require a new symbol after document load, // something has gone terribly wrong. Doing a document.write would // wipe out the page. This does not apply to the CSP-compliant method // of writing script tags. if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING && doc.readyState == 'complete') { // Certain test frameworks load base.js multiple times, which tries // to write deps.js each time. If that happens, just fail silently. // These frameworks wipe the page between each load of base.js, so this // is OK. var isDeps = /\bdeps.js$/.test(src); if (isDeps) { return false; } else { throw Error('Cannot write "' + src + '" after document load'); } } if (opt_sourceText === undefined) { if (!goog.DebugLoader.IS_OLD_IE_) { if (goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) { this.appendScriptSrcNode_(src); } else { this.writeScriptSrcNode_(src); } } else { this.oldIeWaiting_ = true; var state = ' onreadystatechange=\'goog.debugLoader_' + '.onScriptLoad_(this, ' + ++this.lastNonModuleScriptIndex_ + ')\' '; doc.write( '<script type="text/javascript" src="' + src + '"' + state + '></' + 'script>'); } } else { doc.write( '<script type="text/javascript">' + this.protectScriptTag_(opt_sourceText) + '</' + 'script>'); } return true; } else { return false; } }; /** * Rewrites closing script tags in input to avoid ending an enclosing script * tag. * * @param {string} str * @return {string} * @private */ goog.DebugLoader.prototype.protectScriptTag_ = function(str) { return str.replace(/<\/(SCRIPT)/ig, '\\x3c/$1'); }; /** * A readystatechange handler for legacy IE * @param {?} script * @param {number} scriptIndex * @return {boolean} * @private * @suppress {unusedPrivateMembers} */ goog.DebugLoader.prototype.onScriptLoad_ = function(script, scriptIndex) { // for now load the modules when we reach the last script, // later allow more inter-mingling. if (script.readyState == 'complete' && this.lastNonModuleScriptIndex_ == scriptIndex) { this.loadQueuedModules_(); } return true; }; /** * Looks at the dependency rules and tries to determine the script file that * fulfills a particular rule. * @param {string} rule In the form goog.namespace.Class or project.script. * @return {?string} Url corresponding to the rule, or null. * @private */ goog.DebugLoader.prototype.getPathFromDeps_ = function(rule) { if (rule in this.dependencies_.nameToPath) { return this.dependencies_.nameToPath[rule]; } else { return null; } }; /** * @return {!goog.Transpiler} * @protected @final */ goog.DebugLoader.prototype.getTranspiler = function() { return goog.transpiler_; }; /** * @param {string} namespaceOrPath * @return {boolean} * @protected @final */ goog.DebugLoader.prototype.isProvided = function(namespaceOrPath) { return goog.isProvided_(namespaceOrPath); }; /** * @return {boolean} * @protected @final */ goog.DebugLoader.prototype.inHtmlDocument = function() { return goog.inHtmlDocument_(); }; /** * @param {string} message * @protected @final */ goog.DebugLoader.prototype.logToConsole = function(message) { goog.logToConsole_(message); }; /** * @param {string} srcUrl * @return {?string} * @protected @final */ goog.DebugLoader.prototype.loadFileSync = function(srcUrl) { return goog.loadFileSync_(srcUrl); }; /** * @param {string} path * @return {string} * @protected @final */ goog.DebugLoader.prototype.normalizePath = function(path) { return goog.normalizePath_(path); }; /** @private {?goog.DebugLoader} */ goog.debugLoader_ = null; /** @param {!goog.DebugLoader} loader */ goog.registerDebugLoader = function(loader) { if (goog.debugLoader_) { throw new Error('Debug loader already registered!'); } if (!(loader instanceof goog.DebugLoader)) { throw new Error('Not a goog.DebugLoader.'); } goog.debugLoader_ = loader; }; /** @private @return {!goog.DebugLoader} */ goog.getLoader_ = function() { if (!goog.debugLoader_ && goog.DEBUG_LOADER) { // Tried to load earlier but failed. throw new Error('Loaded debug loader file but no loader was registered!'); } else if (!goog.debugLoader_) { // No custom loader and no closure deps. Was not made earlier; make it // now. goog.debugLoader_ = new goog.DebugLoader(); } return goog.debugLoader_; }; (function() { var tempLoader; if (goog.DEBUG_LOADER) { tempLoader = new goog.DebugLoader(); tempLoader.importScript_(goog.basePath + goog.DEBUG_LOADER); } // Allow projects to manage the deps files themselves. if (!goog.global.CLOSURE_NO_DEPS) { tempLoader = tempLoader || new goog.DebugLoader(); if (!goog.DEBUG_LOADER) { // Can reuse the same debug loader in the rest of the application. goog.registerDebugLoader(tempLoader); } tempLoader.importScript_(goog.basePath + 'deps.js'); } })(); } //javascript/closure/debug/error.js // Copyright 2009 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Provides a base class for custom Error objects such that the * stack is correctly maintained. * * You should never need to throw goog.debug.Error(msg) directly, Error(msg) is * sufficient. * */ goog.provide('goog.debug.Error'); /** * Base class for custom error objects. * @param {*=} opt_msg The message associated with the error. * @constructor * @extends {Error} */ goog.debug.Error = function(opt_msg) { // Attempt to ensure there is a stack trace. if (Error.captureStackTrace) { Error.captureStackTrace(this, goog.debug.Error); } else { var stack = new Error().stack; if (stack) { /** @override */ this.stack = stack; } } if (opt_msg) { /** @override */ this.message = String(opt_msg); } /** * Whether to report this error to the server. Setting this to false will * cause the error reporter to not report the error back to the server, * which can be useful if the client knows that the error has already been * logged on the server. * @type {boolean} */ this.reportErrorToServer = true; }; goog.inherits(goog.debug.Error, Error); /** @override */ goog.debug.Error.prototype.name = 'CustomError'; //javascript/closure/dom/nodetype.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Definition of goog.dom.NodeType. */ goog.provide('goog.dom.NodeType'); /** * Constants for the nodeType attribute in the Node interface. * * These constants match those specified in the Node interface. These are * usually present on the Node object in recent browsers, but not in older * browsers (specifically, early IEs) and thus are given here. * * In some browsers (early IEs), these are not defined on the Node object, * so they are provided here. * * See http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-1950641247 * @enum {number} */ goog.dom.NodeType = { ELEMENT: 1, ATTRIBUTE: 2, TEXT: 3, CDATA_SECTION: 4, ENTITY_REFERENCE: 5, ENTITY: 6, PROCESSING_INSTRUCTION: 7, COMMENT: 8, DOCUMENT: 9, DOCUMENT_TYPE: 10, DOCUMENT_FRAGMENT: 11, NOTATION: 12 }; //javascript/closure/asserts/asserts.js // Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities to check the preconditions, postconditions and * invariants runtime. * * Methods in this package should be given special treatment by the compiler * for type-inference. For example, <code>goog.asserts.assert(foo)</code> * will restrict <code>foo</code> to a truthy value. * * The compiler has an option to disable asserts. So code like: * <code> * var x = goog.asserts.assert(foo()); goog.asserts.assert(bar()); * </code> * will be transformed into: * <code> * var x = foo(); * </code> * The compiler will leave in foo() (because its return value is used), * but it will remove bar() because it assumes it does not have side-effects. * * @author <EMAIL> (<NAME>) */ goog.provide('goog.asserts'); goog.provide('goog.asserts.AssertionError'); goog.require('goog.debug.Error'); goog.require('goog.dom.NodeType'); /** * @define {boolean} Whether to strip out asserts or to leave them in. */ goog.define('goog.asserts.ENABLE_ASSERTS', goog.DEBUG); /** * Error object for failed assertions. * @param {string} messagePattern The pattern that was used to form message. * @param {!Array<*>} messageArgs The items to substitute into the pattern. * @constructor * @extends {goog.debug.Error} * @final */ goog.asserts.AssertionError = function(messagePattern, messageArgs) { goog.debug.Error.call(this, goog.asserts.subs_(messagePattern, messageArgs)); /** * The message pattern used to format the error message. Error handlers can * use this to uniquely identify the assertion. * @type {string} */ this.messagePattern = messagePattern; }; goog.inherits(goog.asserts.AssertionError, goog.debug.Error); /** @override */ goog.asserts.AssertionError.prototype.name = 'AssertionError'; /** * The default error handler. * @param {!goog.asserts.AssertionError} e The exception to be handled. */ goog.asserts.DEFAULT_ERROR_HANDLER = function(e) { throw e; }; /** * The handler responsible for throwing or logging assertion errors. * @private {function(!goog.asserts.AssertionError)} */ goog.asserts.errorHandler_ = goog.asserts.DEFAULT_ERROR_HANDLER; /** * Does simple python-style string substitution. * subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog". * @param {string} pattern The string containing the pattern. * @param {!Array<*>} subs The items to substitute into the pattern. * @return {string} A copy of `str` in which each occurrence of * {@code %s} has been replaced an argument from `var_args`. * @private */ goog.asserts.subs_ = function(pattern, subs) { var splitParts = pattern.split('%s'); var returnString = ''; // Replace up to the last split part. We are inserting in the // positions between split parts. var subLast = splitParts.length - 1; for (var i = 0; i < subLast; i++) { // keep unsupplied as '%s' var sub = (i < subs.length) ? subs[i] : '%s'; returnString += splitParts[i] + sub; } return returnString + splitParts[subLast]; }; /** * Throws an exception with the given message and "Assertion failed" prefixed * onto it. * @param {string} defaultMessage The message to use if givenMessage is empty. * @param {Array<*>} defaultArgs The substitution arguments for defaultMessage. * @param {string|undefined} givenMessage Message supplied by the caller. * @param {Array<*>} givenArgs The substitution arguments for givenMessage. * @throws {goog.asserts.AssertionError} When the value is not a number. * @private */ goog.asserts.doAssertFailure_ = function( defaultMessage, defaultArgs, givenMessage, givenArgs) { var message = 'Assertion failed'; if (givenMessage) { message += ': ' + givenMessage; var args = givenArgs; } else if (defaultMessage) { message += ': ' + defaultMessage; args = defaultArgs; } // The '' + works around an Opera 10 bug in the unit tests. Without it, // a stack trace is added to var message above. With this, a stack trace is // not added until this line (it causes the extra garbage to be added after // the assertion message instead of in the middle of it). var e = new goog.asserts.AssertionError('' + message, args || []); goog.asserts.errorHandler_(e); }; /** * Sets a custom error handler that can be used to customize the behavior of * assertion failures, for example by turning all assertion failures into log * messages. * @param {function(!goog.asserts.AssertionError)} errorHandler */ goog.asserts.setErrorHandler = function(errorHandler) { if (goog.asserts.ENABLE_ASSERTS) { goog.asserts.errorHandler_ = errorHandler; } }; /** * Checks if the condition evaluates to true if goog.asserts.ENABLE_ASSERTS is * true. * @template T * @param {T} condition The condition to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {T} The value of the condition. * @throws {goog.asserts.AssertionError} When the condition evaluates to false. */ goog.asserts.assert = function(condition, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !condition) { goog.asserts.doAssertFailure_( '', null, opt_message, Array.prototype.slice.call(arguments, 2)); } return condition; }; /** * Fails if goog.asserts.ENABLE_ASSERTS is true. This function is useful in case * when we want to add a check in the unreachable area like switch-case * statement: * * <pre> * switch(type) { * case FOO: doSomething(); break; * case BAR: doSomethingElse(); break; * default: goog.asserts.fail('Unrecognized type: ' + type); * // We have only 2 types - "default:" section is unreachable code. * } * </pre> * * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @throws {goog.asserts.AssertionError} Failure. */ goog.asserts.fail = function(opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS) { goog.asserts.errorHandler_( new goog.asserts.AssertionError( 'Failure' + (opt_message ? ': ' + opt_message : ''), Array.prototype.slice.call(arguments, 1))); } }; /** * Checks if the value is a number if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {number} The value, guaranteed to be a number when asserts enabled. * @throws {goog.asserts.AssertionError} When the value is not a number. */ goog.asserts.assertNumber = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isNumber(value)) { goog.asserts.doAssertFailure_( 'Expected number but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {number} */ (value); }; /** * Checks if the value is a string if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {string} The value, guaranteed to be a string when asserts enabled. * @throws {goog.asserts.AssertionError} When the value is not a string. */ goog.asserts.assertString = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isString(value)) { goog.asserts.doAssertFailure_( 'Expected string but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {string} */ (value); }; /** * Checks if the value is a function if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {!Function} The value, guaranteed to be a function when asserts * enabled. * @throws {goog.asserts.AssertionError} When the value is not a function. */ goog.asserts.assertFunction = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isFunction(value)) { goog.asserts.doAssertFailure_( 'Expected function but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {!Function} */ (value); }; /** * Checks if the value is an Object if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {!Object} The value, guaranteed to be a non-null object. * @throws {goog.asserts.AssertionError} When the value is not an object. */ goog.asserts.assertObject = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isObject(value)) { goog.asserts.doAssertFailure_( 'Expected object but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {!Object} */ (value); }; /** * Checks if the value is an Array if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {!Array<?>} The value, guaranteed to be a non-null array. * @throws {goog.asserts.AssertionError} When the value is not an array. */ goog.asserts.assertArray = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isArray(value)) { goog.asserts.doAssertFailure_( 'Expected array but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {!Array<?>} */ (value); }; /** * Checks if the value is a boolean if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {boolean} The value, guaranteed to be a boolean when asserts are * enabled. * @throws {goog.asserts.AssertionError} When the value is not a boolean. */ goog.asserts.assertBoolean = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !goog.isBoolean(value)) { goog.asserts.doAssertFailure_( 'Expected boolean but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {boolean} */ (value); }; /** * Checks if the value is a DOM Element if goog.asserts.ENABLE_ASSERTS is true. * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @return {!Element} The value, likely to be a DOM Element when asserts are * enabled. * @throws {goog.asserts.AssertionError} When the value is not an Element. */ goog.asserts.assertElement = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && (!goog.isObject(value) || value.nodeType != goog.dom.NodeType.ELEMENT)) { goog.asserts.doAssertFailure_( 'Expected Element but got %s: %s.', [goog.typeOf(value), value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {!Element} */ (value); }; /** * Checks if the value is an instance of the user-defined type if * goog.asserts.ENABLE_ASSERTS is true. * * The compiler may tighten the type returned by this function. * * @param {?} value The value to check. * @param {function(new: T, ...)} type A user-defined constructor. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @throws {goog.asserts.AssertionError} When the value is not an instance of * type. * @return {T} * @template T */ goog.asserts.assertInstanceof = function(value, type, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && !(value instanceof type)) { goog.asserts.doAssertFailure_( 'Expected instanceof %s but got %s.', [goog.asserts.getType_(type), goog.asserts.getType_(value)], opt_message, Array.prototype.slice.call(arguments, 3)); } return value; }; /** * Checks whether the value is a finite number, if goog.asserts.ENABLE_ASSERTS * is true. * * @param {*} value The value to check. * @param {string=} opt_message Error message in case of failure. * @param {...*} var_args The items to substitute into the failure message. * @throws {goog.asserts.AssertionError} When the value is not a number, or is * a non-finite number such as NaN, Infinity or -Infinity. * @return {number} The value initially passed in. */ goog.asserts.assertFinite = function(value, opt_message, var_args) { if (goog.asserts.ENABLE_ASSERTS && (typeof value != 'number' || !isFinite(value))) { goog.asserts.doAssertFailure_( 'Expected %s to be a finite number but it is not.', [value], opt_message, Array.prototype.slice.call(arguments, 2)); } return /** @type {number} */ (value); }; /** * Checks that no enumerable keys are present in Object.prototype. Such keys * would break most code that use {@code for (var ... in ...)} loops. */ goog.asserts.assertObjectPrototypeIsIntact = function() { for (var key in Object.prototype) { goog.asserts.fail(key + ' should not be enumerable in Object.prototype.'); } }; /** * Returns the type of a value. If a constructor is passed, and a suitable * string cannot be found, 'unknown type name' will be returned. * @param {*} value A constructor, object, or primitive. * @return {string} The best display name for the value, or 'unknown type name'. * @private */ goog.asserts.getType_ = function(value) { if (value instanceof Function) { return value.displayName || value.name || 'unknown type name'; } else if (value instanceof Object) { return /** @type {string} */ (value.constructor.displayName) || value.constructor.name || Object.prototype.toString.call(value); } else { return value === null ? 'null' : typeof value; } }; //javascript/closure/array/array.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities for manipulating arrays. * * @author <EMAIL> (<NAME>) */ goog.provide('goog.array'); goog.require('goog.asserts'); /** * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should * rely on Array.prototype functions, if available. * * The Array.prototype functions can be defined by external libraries like * Prototype and setting this flag to false forces closure to use its own * goog.array implementation. * * If your javascript can be loaded by a third party site and you are wary about * relying on the prototype functions, specify * "--define goog.NATIVE_ARRAY_PROTOTYPES=false" to the JSCompiler. * * Setting goog.TRUSTED_SITE to false will automatically set * NATIVE_ARRAY_PROTOTYPES to false. */ goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE); /** * @define {boolean} If true, JSCompiler will use the native implementation of * array functions where appropriate (e.g., `Array#filter`) and remove the * unused pure JS implementation. */ goog.define('goog.array.ASSUME_NATIVE_FUNCTIONS', false); /** * Returns the last element in an array without removing it. * Same as goog.array.last. * @param {IArrayLike<T>|string} array The array. * @return {T} Last item in array. * @template T */ goog.array.peek = function(array) { return array[array.length - 1]; }; /** * Returns the last element in an array without removing it. * Same as goog.array.peek. * @param {IArrayLike<T>|string} array The array. * @return {T} Last item in array. * @template T */ goog.array.last = goog.array.peek; // NOTE(arv): Since most of the array functions are generic it allows you to // pass an array-like object. Strings have a length and are considered array- // like. However, the 'in' operator does not work on strings so we cannot just // use the array path even if the browser supports indexing into strings. We // therefore end up splitting the string. /** * Returns the index of the first element of an array with a specified value, or * -1 if the element is not present in the array. * * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof} * * @param {IArrayLike<T>|string} arr The array to be searched. * @param {T} obj The object for which we are searching. * @param {number=} opt_fromIndex The index at which to start the search. If * omitted the search starts at index 0. * @return {number} The index of the first matching array element. * @template T */ goog.array.indexOf = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ? function(arr, obj, opt_fromIndex) { goog.asserts.assert(arr.length != null); return Array.prototype.indexOf.call(arr, obj, opt_fromIndex); } : function(arr, obj, opt_fromIndex) { var fromIndex = opt_fromIndex == null ? 0 : (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) : opt_fromIndex); if (goog.isString(arr)) { // Array.prototype.indexOf uses === so only strings should be found. if (!goog.isString(obj) || obj.length != 1) { return -1; } return arr.indexOf(obj, fromIndex); } for (var i = fromIndex; i < arr.length; i++) { if (i in arr && arr[i] === obj) return i; } return -1; }; /** * Returns the index of the last element of an array with a specified value, or * -1 if the element is not present in the array. * * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof} * * @param {!IArrayLike<T>|string} arr The array to be searched. * @param {T} obj The object for which we are searching. * @param {?number=} opt_fromIndex The index at which to start the search. If * omitted the search starts at the end of the array. * @return {number} The index of the last matching array element. * @template T */ goog.array.lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ? function(arr, obj, opt_fromIndex) { goog.asserts.assert(arr.length != null); // Firefox treats undefined and null as 0 in the fromIndex argument which // leads it to always return -1 var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex; return Array.prototype.lastIndexOf.call(arr, obj, fromIndex); } : function(arr, obj, opt_fromIndex) { var fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex; if (fromIndex < 0) { fromIndex = Math.max(0, arr.length + fromIndex); } if (goog.isString(arr)) { // Array.prototype.lastIndexOf uses === so only strings should be found. if (!goog.isString(obj) || obj.length != 1) { return -1; } return arr.lastIndexOf(obj, fromIndex); } for (var i = fromIndex; i >= 0; i--) { if (i in arr && arr[i] === obj) return i; } return -1; }; /** * Calls a function for each element in an array. Skips holes in the array. * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach} * * @param {IArrayLike<T>|string} arr Array or array like object over * which to iterate. * @param {?function(this: S, T, number, ?): ?} f The function to call for every * element. This function takes 3 arguments (the element, the index and the * array). The return value is ignored. * @param {S=} opt_obj The object to be used as the value of 'this' within f. * @template T,S */ goog.array.forEach = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ? function(arr, f, opt_obj) { goog.asserts.assert(arr.length != null); Array.prototype.forEach.call(arr, f, opt_obj); } : function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2) { f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr); } } }; /** * Calls a function for each element in an array, starting from the last * element rather than the first. * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this: S, T, number, ?): ?} f The function to call for every * element. This function * takes 3 arguments (the element, the index and the array). The return * value is ignored. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @template T,S */ goog.array.forEachRight = function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = l - 1; i >= 0; --i) { if (i in arr2) { f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr); } } }; /** * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * * See {@link http://tinyurl.com/developer-mozilla-org-array-filter} * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?):boolean} f The function to call for * every element. This function * takes 3 arguments (the element, the index and the array) and must * return a Boolean. If the return value is true the element is added to the * result array. If it is false the element is not included. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @return {!Array<T>} a new array in which only elements that passed the test * are present. * @template T,S */ goog.array.filter = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ? function(arr, f, opt_obj) { goog.asserts.assert(arr.length != null); return Array.prototype.filter.call(arr, f, opt_obj); } : function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var res = []; var resLength = 0; var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2) { var val = arr2[i]; // in case f mutates arr2 if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) { res[resLength++] = val; } } } return res; }; /** * Calls a function for each element in an array and inserts the result into a * new array. * * See {@link http://tinyurl.com/developer-mozilla-org-array-map} * * @param {IArrayLike<VALUE>|string} arr Array or array like object * over which to iterate. * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call * for every element. This function takes 3 arguments (the element, * the index and the array) and should return something. The result will be * inserted into a new array. * @param {THIS=} opt_obj The object to be used as the value of 'this' within f. * @return {!Array<RESULT>} a new array with the results from f. * @template THIS, VALUE, RESULT */ goog.array.map = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ? function(arr, f, opt_obj) { goog.asserts.assert(arr.length != null); return Array.prototype.map.call(arr, f, opt_obj); } : function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var res = new Array(l); var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2) { res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr); } } return res; }; /** * Passes every element of an array into a function and accumulates the result. * * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce} * * For example: * var a = [1, 2, 3, 4]; * goog.array.reduce(a, function(r, v, i, arr) {return r + v;}, 0); * returns 10 * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {function(this:S, R, T, number, ?) : R} f The function to call for * every element. This function * takes 4 arguments (the function's previous result or the initial value, * the value of the current array element, the current array index, and the * array itself) * function(previousValue, currentValue, index, array). * @param {?} val The initial value to pass into the function on the first call. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @return {R} Result of evaluating f repeatedly across the values of the array. * @template T,S,R */ goog.array.reduce = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ? function(arr, f, val, opt_obj) { goog.asserts.assert(arr.length != null); if (opt_obj) { f = goog.bind(f, opt_obj); } return Array.prototype.reduce.call(arr, f, val); } : function(arr, f, val, opt_obj) { var rval = val; goog.array.forEach(arr, function(val, index) { rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr); }); return rval; }; /** * Passes every element of an array into a function and accumulates the result, * starting from the last element and working towards the first. * * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright} * * For example: * var a = ['a', 'b', 'c']; * goog.array.reduceRight(a, function(r, v, i, arr) {return r + v;}, ''); * returns 'cba' * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, R, T, number, ?) : R} f The function to call for * every element. This function * takes 4 arguments (the function's previous result or the initial value, * the value of the current array element, the current array index, and the * array itself) * function(previousValue, currentValue, index, array). * @param {?} val The initial value to pass into the function on the first call. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @return {R} Object returned as a result of evaluating f repeatedly across the * values of the array. * @template T,S,R */ goog.array.reduceRight = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ? function(arr, f, val, opt_obj) { goog.asserts.assert(arr.length != null); goog.asserts.assert(f != null); if (opt_obj) { f = goog.bind(f, opt_obj); } return Array.prototype.reduceRight.call(arr, f, val); } : function(arr, f, val, opt_obj) { var rval = val; goog.array.forEachRight(arr, function(val, index) { rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr); }); return rval; }; /** * Calls f for each element of an array. If any call returns true, some() * returns true (without checking the remaining elements). If all calls * return false, some() returns false. * * See {@link http://tinyurl.com/developer-mozilla-org-array-some} * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for * for every element. This function takes 3 arguments (the element, the * index and the array) and should return a boolean. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @return {boolean} true if any element passes the test. * @template T,S */ goog.array.some = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ? function(arr, f, opt_obj) { goog.asserts.assert(arr.length != null); return Array.prototype.some.call(arr, f, opt_obj); } : function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) { return true; } } return false; }; /** * Call f for each element of an array. If all calls return true, every() * returns true. If any call returns false, every() returns false and * does not continue to check the remaining elements. * * See {@link http://tinyurl.com/developer-mozilla-org-array-every} * * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for * for every element. This function takes 3 arguments (the element, the * index and the array) and should return a boolean. * @param {S=} opt_obj The object to be used as the value of 'this' * within f. * @return {boolean} false if any element fails the test. * @template T,S */ goog.array.every = goog.NATIVE_ARRAY_PROTOTYPES && (goog.array.ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ? function(arr, f, opt_obj) { goog.asserts.assert(arr.length != null); return Array.prototype.every.call(arr, f, opt_obj); } : function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) { return false; } } return true; }; /** * Counts the array elements that fulfill the predicate, i.e. for which the * callback function returns true. Skips holes in the array. * * @param {!IArrayLike<T>|string} arr Array or array like object * over which to iterate. * @param {function(this: S, T, number, ?): boolean} f The function to call for * every element. Takes 3 arguments (the element, the index and the array). * @param {S=} opt_obj The object to be used as the value of 'this' within f. * @return {number} The number of the matching elements. * @template T,S */ goog.array.count = function(arr, f, opt_obj) { var count = 0; goog.array.forEach(arr, function(element, index, arr) { if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) { ++count; } }, opt_obj); return count; }; /** * Search an array for the first element that satisfies a given condition and * return that element. * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call * for every element. This function takes 3 arguments (the element, the * index and the array) and should return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {T|null} The first array element that passes the test, or null if no * element is found. * @template T,S */ goog.array.find = function(arr, f, opt_obj) { var i = goog.array.findIndex(arr, f, opt_obj); return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i]; }; /** * Search an array for the first element that satisfies a given condition and * return its index. * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call for * every element. This function * takes 3 arguments (the element, the index and the array) and should * return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {number} The index of the first array element that passes the test, * or -1 if no element is found. * @template T,S */ goog.array.findIndex = function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = 0; i < l; i++) { if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) { return i; } } return -1; }; /** * Search an array (in reverse order) for the last element that satisfies a * given condition and return that element. * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call * for every element. This function * takes 3 arguments (the element, the index and the array) and should * return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {T|null} The last array element that passes the test, or null if no * element is found. * @template T,S */ goog.array.findRight = function(arr, f, opt_obj) { var i = goog.array.findIndexRight(arr, f, opt_obj); return i < 0 ? null : goog.isString(arr) ? arr.charAt(i) : arr[i]; }; /** * Search an array (in reverse order) for the last element that satisfies a * given condition and return its index. * @param {IArrayLike<T>|string} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call * for every element. This function * takes 3 arguments (the element, the index and the array) and should * return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {number} The index of the last array element that passes the test, * or -1 if no element is found. * @template T,S */ goog.array.findIndexRight = function(arr, f, opt_obj) { var l = arr.length; // must be fixed during loop... see docs var arr2 = goog.isString(arr) ? arr.split('') : arr; for (var i = l - 1; i >= 0; i--) { if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) { return i; } } return -1; }; /** * Whether the array contains the given object. * @param {IArrayLike<?>|string} arr The array to test for the presence of the * element. * @param {*} obj The object for which to test. * @return {boolean} true if obj is present. */ goog.array.contains = function(arr, obj) { return goog.array.indexOf(arr, obj) >= 0; }; /** * Whether the array is empty. * @param {IArrayLike<?>|string} arr The array to test. * @return {boolean} true if empty. */ goog.array.isEmpty = function(arr) { return arr.length == 0; }; /** * Clears the array. * @param {IArrayLike<?>} arr Array or array like object to clear. */ goog.array.clear = function(arr) { // For non real arrays we don't have the magic length so we delete the // indices. if (!goog.isArray(arr)) { for (var i = arr.length - 1; i >= 0; i--) { delete arr[i]; } } arr.length = 0; }; /** * Pushes an item into an array, if it's not already in the array. * @param {Array<T>} arr Array into which to insert the item. * @param {T} obj Value to add. * @template T */ goog.array.insert = function(arr, obj) { if (!goog.array.contains(arr, obj)) { arr.push(obj); } }; /** * Inserts an object at the given index of the array. * @param {IArrayLike<?>} arr The array to modify. * @param {*} obj The object to insert. * @param {number=} opt_i The index at which to insert the object. If omitted, * treated as 0. A negative index is counted from the end of the array. */ goog.array.insertAt = function(arr, obj, opt_i) { goog.array.splice(arr, opt_i, 0, obj); }; /** * Inserts at the given index of the array, all elements of another array. * @param {IArrayLike<?>} arr The array to modify. * @param {IArrayLike<?>} elementsToAdd The array of elements to add. * @param {number=} opt_i The index at which to insert the object. If omitted, * treated as 0. A negative index is counted from the end of the array. */ goog.array.insertArrayAt = function(arr, elementsToAdd, opt_i) { goog.partial(goog.array.splice, arr, opt_i, 0).apply(null, elementsToAdd); }; /** * Inserts an object into an array before a specified object. * @param {Array<T>} arr The array to modify. * @param {T} obj The object to insert. * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2 * is omitted or not found, obj is inserted at the end of the array. * @template T */ goog.array.insertBefore = function(arr, obj, opt_obj2) { var i; if (arguments.length == 2 || (i = goog.array.indexOf(arr, opt_obj2)) < 0) { arr.push(obj); } else { goog.array.insertAt(arr, obj, i); } }; /** * Removes the first occurrence of a particular value from an array. * @param {IArrayLike<T>} arr Array from which to remove * value. * @param {T} obj Object to remove. * @return {boolean} True if an element was removed. * @template T */ goog.array.remove = function(arr, obj) { var i = goog.array.indexOf(arr, obj); var rv; if ((rv = i >= 0)) { goog.array.removeAt(arr, i); } return rv; }; /** * Removes the last occurrence of a particular value from an array. * @param {!IArrayLike<T>} arr Array from which to remove value. * @param {T} obj Object to remove. * @return {boolean} True if an element was removed. * @template T */ goog.array.removeLast = function(arr, obj) { var i = goog.array.lastIndexOf(arr, obj); if (i >= 0) { goog.array.removeAt(arr, i); return true; } return false; }; /** * Removes from an array the element at index i * @param {IArrayLike<?>} arr Array or array like object from which to * remove value. * @param {number} i The index to remove. * @return {boolean} True if an element was removed. */ goog.array.removeAt = function(arr, i) { goog.asserts.assert(arr.length != null); // use generic form of splice // splice returns the removed items and if successful the length of that // will be 1 return Array.prototype.splice.call(arr, i, 1).length == 1; }; /** * Removes the first value that satisfies the given condition. * @param {IArrayLike<T>} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call * for every element. This function * takes 3 arguments (the element, the index and the array) and should * return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {boolean} True if an element was removed. * @template T,S */ goog.array.removeIf = function(arr, f, opt_obj) { var i = goog.array.findIndex(arr, f, opt_obj); if (i >= 0) { goog.array.removeAt(arr, i); return true; } return false; }; /** * Removes all values that satisfy the given condition. * @param {IArrayLike<T>} arr Array or array * like object over which to iterate. * @param {?function(this:S, T, number, ?) : boolean} f The function to call * for every element. This function * takes 3 arguments (the element, the index and the array) and should * return a boolean. * @param {S=} opt_obj An optional "this" context for the function. * @return {number} The number of items removed * @template T,S */ goog.array.removeAllIf = function(arr, f, opt_obj) { var removedCount = 0; goog.array.forEachRight(arr, function(val, index) { if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) { if (goog.array.removeAt(arr, index)) { removedCount++; } } }); return removedCount; }; /** * Returns a new array that is the result of joining the arguments. If arrays * are passed then their items are added, however, if non-arrays are passed they * will be added to the return array as is. * * Note that ArrayLike objects will be added as is, rather than having their * items added. * * goog.array.concat([1, 2], [3, 4]) -> [1, 2, 3, 4] * goog.array.concat(0, [1, 2]) -> [0, 1, 2] * goog.array.concat([1, 2], null) -> [1, 2, null] * * There is bug in all current versions of IE (6, 7 and 8) where arrays created * in an iframe become corrupted soon (not immediately) after the iframe is * destroyed. This is common if loading data via goog.net.IframeIo, for example. * This corruption only affects the concat method which will start throwing * Catastrophic Errors (#-2147418113). * * See http://endoflow.com/scratch/corrupted-arrays.html for a test case. * * Internally goog.array should use this, so that all methods will continue to * work on these broken array objects. * * @param {...*} var_args Items to concatenate. Arrays will have each item * added, while primitives and objects will be added as is. * @return {!Array<?>} The new resultant array. */ goog.array.concat = function(var_args) { return Array.prototype.concat.apply([], arguments); }; /** * Returns a new array that contains the contents of all the arrays passed. * @param {...!Array<T>} var_args * @return {!Array<T>} * @template T */ goog.array.join = function(var_args) { return Array.prototype.concat.apply([], arguments); }; /** * Converts an object to an array. * @param {IArrayLike<T>|string} object The object to convert to an * array. * @return {!Array<T>} The object converted into an array. If object has a * length property, every property indexed with a non-negative number * less than length will be included in the result. If object does not * have a length property, an empty array will be returned. * @template T */ goog.array.toArray = function(object) { var length = object.length; // If length is not a number the following it false. This case is kept for // backwards compatibility since there are callers that pass objects that are // not array like. if (length > 0) { var rv = new Array(length); for (var i = 0; i < length; i++) { rv[i] = object[i]; } return rv; } return []; }; /** * Does a shallow copy of an array. * @param {IArrayLike<T>|string} arr Array or array-like object to * clone. * @return {!Array<T>} Clone of the input array. * @template T */ goog.array.clone = goog.array.toArray; /** * Extends an array with another array, element, or "array like" object. * This function operates 'in-place', it does not create a new Array. * * Example: * var a = []; * goog.array.extend(a, [0, 1]); * a; // [0, 1] * goog.array.extend(a, 2); * a; // [0, 1, 2] * * @param {Array<VALUE>} arr1 The array to modify. * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of * elements to add to arr1. * @template VALUE */ goog.array.extend = function(arr1, var_args) { for (var i = 1; i < arguments.length; i++) { var arr2 = arguments[i]; if (goog.isArrayLike(arr2)) { var len1 = arr1.length || 0; var len2 = arr2.length || 0; arr1.length = len1 + len2; for (var j = 0; j < len2; j++) { arr1[len1 + j] = arr2[j]; } } else { arr1.push(arr2); } } }; /** * Adds or removes elements from an array. This is a generic version of Array * splice. This means that it might work on other objects similar to arrays, * such as the arguments object. * * @param {IArrayLike<T>} arr The array to modify. * @param {number|undefined} index The index at which to start changing the * array. If not defined, treated as 0. * @param {number} howMany How many elements to remove (0 means no removal. A * value below 0 is treated as zero and so is any other non number. Numbers * are floored). * @param {...T} var_args Optional, additional elements to insert into the * array. * @return {!Array<T>} the removed elements. * @template T */ goog.array.splice = function(arr, index, howMany, var_args) { goog.asserts.assert(arr.length != null); return Array.prototype.splice.apply(arr, goog.array.slice(arguments, 1)); }; /** * Returns a new array from a segment of an array. This is a generic version of * Array slice. This means that it might work on other objects similar to * arrays, such as the arguments object. * * @param {IArrayLike<T>|string} arr The array from * which to copy a segment. * @param {number} start The index of the first element to copy. * @param {number=} opt_end The index after the last element to copy. * @return {!Array<T>} A new array containing the specified segment of the * original array. * @template T */ goog.array.slice = function(arr, start, opt_end) { goog.asserts.assert(arr.length != null); // passing 1 arg to slice is not the same as passing 2 where the second is // null or undefined (in that case the second argument is treated as 0). // we could use slice on the arguments object and then use apply instead of // testing the length if (arguments.length <= 2) { return Array.prototype.slice.call(arr, start); } else { return Array.prototype.slice.call(arr, start, opt_end); } }; /** * Removes all duplicates from an array (retaining only the first * occurrence of each array element). This function modifies the * array in place and doesn't change the order of the non-duplicate items. * * For objects, duplicates are identified as having the same unique ID as * defined by {@link goog.getUid}. * * Alternatively you can specify a custom hash function that returns a unique * value for each item in the array it should consider unique. * * Runtime: N, * Worstcase space: 2N (no dupes) * * @param {IArrayLike<T>} arr The array from which to remove * duplicates. * @param {Array=} opt_rv An optional array in which to return the results, * instead of performing the removal inplace. If specified, the original * array will remain unchanged. * @param {function(T):string=} opt_hashFn An optional function to use to * apply to every item in the array. This function should return a unique * value for each item in the array it should consider unique. * @template T */ goog.array.removeDuplicates = function(arr, opt_rv, opt_hashFn) { var returnArray = opt_rv || arr; var defaultHashFn = function(item) { // Prefix each type with a single character representing the type to // prevent conflicting keys (e.g. true and 'true'). return goog.isObject(item) ? 'o' + goog.getUid(item) : (typeof item).charAt(0) + item; }; var hashFn = opt_hashFn || defaultHashFn; var seen = {}, cursorInsert = 0, cursorRead = 0; while (cursorRead < arr.length) { var current = arr[cursorRead++]; var key = hashFn(current); if (!Object.prototype.hasOwnProperty.call(seen, key)) { seen[key] = true; returnArray[cursorInsert++] = current; } } returnArray.length = cursorInsert; }; /** * Searches the specified array for the specified target using the binary * search algorithm. If no opt_compareFn is specified, elements are compared * using <code>goog.array.defaultCompare</code>, which compares the elements * using the built in < and > operators. This will produce the expected * behavior for homogeneous arrays of String(s) and Number(s). The array * specified <b>must</b> be sorted in ascending order (as defined by the * comparison function). If the array is not sorted, results are undefined. * If the array contains multiple instances of the specified target value, any * of these instances may be found. * * Runtime: O(log n) * * @param {IArrayLike<VALUE>} arr The array to be searched. * @param {TARGET} target The sought value. * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison * function by which the array is ordered. Should take 2 arguments to * compare, and return a negative number, zero, or a positive number * depending on whether the first argument is less than, equal to, or * greater than the second. * @return {number} Lowest index of the target value if found, otherwise * (-(insertion point) - 1). The insertion point is where the value should * be inserted into arr to preserve the sorted property. Return value >= 0 * iff target is found. * @template TARGET, VALUE */ goog.array.binarySearch = function(arr, target, opt_compareFn) { return goog.array.binarySearch_( arr, opt_compareFn || goog.array.defaultCompare, false /* isEvaluator */, target); }; /** * Selects an index in the specified array using the binary search algorithm. * The evaluator receives an element and determines whether the desired index * is before, at, or after it. The evaluator must be consistent (formally, * goog.array.map(goog.array.map(arr, evaluator, opt_obj), goog.math.sign) * must be monotonically non-increasing). * * Runtime: O(log n) * * @param {IArrayLike<VALUE>} arr The array to be searched. * @param {function(this:THIS, VALUE, number, ?): number} evaluator * Evaluator function that receives 3 arguments (the element, the index and * the array). Should return a negative number, zero, or a positive number * depending on whether the desired index is before, at, or after the * element passed to it. * @param {THIS=} opt_obj The object to be used as the value of 'this' * within evaluator. * @return {number} Index of the leftmost element matched by the evaluator, if * such exists; otherwise (-(insertion point) - 1). The insertion point is * the index of the first element for which the evaluator returns negative, * or arr.length if no such element exists. The return value is non-negative * iff a match is found. * @template THIS, VALUE */ goog.array.binarySelect = function(arr, evaluator, opt_obj) { return goog.array.binarySearch_( arr, evaluator, true /* isEvaluator */, undefined /* opt_target */, opt_obj); }; /** * Implementation of a binary search algorithm which knows how to use both * comparison functions and evaluators. If an evaluator is provided, will call * the evaluator with the given optional data object, conforming to the * interface defined in binarySelect. Otherwise, if a comparison function is * provided, will call the comparison function against the given data object. * * This implementation purposefully does not use goog.bind or goog.partial for * performance reasons. * * Runtime: O(log n) * * @param {IArrayLike<?>} arr The array to be searched. * @param {function(?, ?, ?): number | function(?, ?): number} compareFn * Either an evaluator or a comparison function, as defined by binarySearch * and binarySelect above. * @param {boolean} isEvaluator Whether the function is an evaluator or a * comparison function. * @param {?=} opt_target If the function is a comparison function, then * this is the target to binary search for. * @param {Object=} opt_selfObj If the function is an evaluator, this is an * optional this object for the evaluator. * @return {number} Lowest index of the target value if found, otherwise * (-(insertion point) - 1). The insertion point is where the value should * be inserted into arr to preserve the sorted property. Return value >= 0 * iff target is found. * @private */ goog.array.binarySearch_ = function( arr, compareFn, isEvaluator, opt_target, opt_selfObj) { var left = 0; // inclusive var right = arr.length; // exclusive var found; while (left < right) { var middle = (left + right) >> 1; var compareResult; if (isEvaluator) { compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr); } else { // NOTE(dimvar): To avoid this cast, we'd have to use function overloading // for the type of binarySearch_, which the type system can't express yet. compareResult = /** @type {function(?, ?): number} */ (compareFn)( opt_target, arr[middle]); } if (compareResult > 0) { left = middle + 1; } else { right = middle; // We are looking for the lowest index so we can't return immediately. found = !compareResult; } } // left is the index if found, or the insertion point otherwise. // ~left is a shorthand for -left - 1. return found ? left : ~left; }; /** * Sorts the specified array into ascending order. If no opt_compareFn is * specified, elements are compared using * <code>goog.array.defaultCompare</code>, which compares the elements using * the built in < and > operators. This will produce the expected behavior * for homogeneous arrays of String(s) and Number(s), unlike the native sort, * but will give unpredictable results for heterogeneous lists of strings and * numbers with different numbers of digits. * * This sort is not guaranteed to be stable. * * Runtime: Same as <code>Array.prototype.sort</code> * * @param {Array<T>} arr The array to be sorted. * @param {?function(T,T):number=} opt_compareFn Optional comparison * function by which the * array is to be ordered. Should take 2 arguments to compare, and return a * negative number, zero, or a positive number depending on whether the * first argument is less than, equal to, or greater than the second. * @template T */ goog.array.sort = function(arr, opt_compareFn) { // TODO(arv): Update type annotation since null is not accepted. arr.sort(opt_compareFn || goog.array.defaultCompare); }; /** * Sorts the specified array into ascending order in a stable way. If no * opt_compareFn is specified, elements are compared using * <code>goog.array.defaultCompare</code>, which compares the elements using * the built in < and > operators. This will produce the expected behavior * for homogeneous arrays of String(s) and Number(s). * * Runtime: Same as <code>Array.prototype.sort</code>, plus an additional * O(n) overhead of copying the array twice. * * @param {Array<T>} arr The array to be sorted. * @param {?function(T, T): number=} opt_compareFn Optional comparison function * by which the array is to be ordered. Should take 2 arguments to compare, * and return a negative number, zero, or a positive number depending on * whether the first argument is less than, equal to, or greater than the * second. * @template T */ goog.array.stableSort = function(arr, opt_compareFn) { var compArr = new Array(arr.length); for (var i = 0; i < arr.length; i++) { compArr[i] = {index: i, value: arr[i]}; } var valueCompareFn = opt_compareFn || goog.array.defaultCompare; function stableCompareFn(obj1, obj2) { return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index; } goog.array.sort(compArr, stableCompareFn); for (var i = 0; i < arr.length; i++) { arr[i] = compArr[i].value; } }; /** * Sort the specified array into ascending order based on item keys * returned by the specified key function. * If no opt_compareFn is specified, the keys are compared in ascending order * using <code>goog.array.defaultCompare</code>. * * Runtime: O(S(f(n)), where S is runtime of <code>goog.array.sort</code> * and f(n) is runtime of the key function. * * @param {Array<T>} arr The array to be sorted. * @param {function(T): K} keyFn Function taking array element and returning * a key used for sorting this element. * @param {?function(K, K): number=} opt_compareFn Optional comparison function * by which the keys are to be ordered. Should take 2 arguments to compare, * and return a negative number, zero, or a positive number depending on * whether the first argument is less than, equal to, or greater than the * second. * @template T,K */ goog.array.sortByKey = function(arr, keyFn, opt_compareFn) { var keyCompareFn = opt_compareFn || goog.array.defaultCompare; goog.array.sort( arr, function(a, b) { return keyCompareFn(keyFn(a), keyFn(b)); }); }; /** * Sorts an array of objects by the specified object key and compare * function. If no compare function is provided, the key values are * compared in ascending order using <code>goog.array.defaultCompare</code>. * This won't work for keys that get renamed by the compiler. So use * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}. * @param {Array<Object>} arr An array of objects to sort. * @param {string} key The object key to sort by. * @param {Function=} opt_compareFn The function to use to compare key * values. */ goog.array.sortObjectsByKey = function(arr, key, opt_compareFn) { goog.array.sortByKey(arr, function(obj) { return obj[key]; }, opt_compareFn); }; /** * Tells if the array is sorted. * @param {!IArrayLike<T>} arr The array. * @param {?function(T,T):number=} opt_compareFn Function to compare the * array elements. * Should take 2 arguments to compare, and return a negative number, zero, * or a positive number depending on whether the first argument is less * than, equal to, or greater than the second. * @param {boolean=} opt_strict If true no equal elements are allowed. * @return {boolean} Whether the array is sorted. * @template T */ goog.array.isSorted = function(arr, opt_compareFn, opt_strict) { var compare = opt_compareFn || goog.array.defaultCompare; for (var i = 1; i < arr.length; i++) { var compareResult = compare(arr[i - 1], arr[i]); if (compareResult > 0 || compareResult == 0 && opt_strict) { return false; } } return true; }; /** * Compares two arrays for equality. Two arrays are considered equal if they * have the same length and their corresponding elements are equal according to * the comparison function. * * @param {IArrayLike<?>} arr1 The first array to compare. * @param {IArrayLike<?>} arr2 The second array to compare. * @param {Function=} opt_equalsFn Optional comparison function. * Should take 2 arguments to compare, and return true if the arguments * are equal. Defaults to {@link goog.array.defaultCompareEquality} which * compares the elements using the built-in '===' operator. * @return {boolean} Whether the two arrays are equal. */ goog.array.equals = function(arr1, arr2, opt_equalsFn) { if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) || arr1.length != arr2.length) { return false; } var l = arr1.length; var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality; for (var i = 0; i < l; i++) { if (!equalsFn(arr1[i], arr2[i])) { return false; } } return true; }; /** * 3-way array compare function. * @param {!IArrayLike<VALUE>} arr1 The first array to * compare. * @param {!IArrayLike<VALUE>} arr2 The second array to * compare. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison * function by which the array is to be ordered. Should take 2 arguments to * compare, and return a negative number, zero, or a positive number * depending on whether the first argument is less than, equal to, or * greater than the second. * @return {number} Negative number, zero, or a positive number depending on * whether the first argument is less than, equal to, or greater than the * second. * @template VALUE */ goog.array.compare3 = function(arr1, arr2, opt_compareFn) { var compare = opt_compareFn || goog.array.defaultCompare; var l = Math.min(arr1.length, arr2.length); for (var i = 0; i < l; i++) { var result = compare(arr1[i], arr2[i]); if (result != 0) { return result; } } return goog.array.defaultCompare(arr1.length, arr2.length); }; /** * Compares its two arguments for order, using the built in < and > * operators. * @param {VALUE} a The first object to be compared. * @param {VALUE} b The second object to be compared. * @return {number} A negative number, zero, or a positive number as the first * argument is less than, equal to, or greater than the second, * respectively. * @template VALUE */ goog.array.defaultCompare = function(a, b) { return a > b ? 1 : a < b ? -1 : 0; }; /** * Compares its two arguments for inverse order, using the built in < and > * operators. * @param {VALUE} a The first object to be compared. * @param {VALUE} b The second object to be compared. * @return {number} A negative number, zero, or a positive number as the first * argument is greater than, equal to, or less than the second, * respectively. * @template VALUE */ goog.array.inverseDefaultCompare = function(a, b) { return -goog.array.defaultCompare(a, b); }; /** * Compares its two arguments for equality, using the built in === operator. * @param {*} a The first object to compare. * @param {*} b The second object to compare. * @return {boolean} True if the two arguments are equal, false otherwise. */ goog.array.defaultCompareEquality = function(a, b) { return a === b; }; /** * Inserts a value into a sorted array. The array is not modified if the * value is already present. * @param {IArrayLike<VALUE>} array The array to modify. * @param {VALUE} value The object to insert. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison * function by which the array is ordered. Should take 2 arguments to * compare, and return a negative number, zero, or a positive number * depending on whether the first argument is less than, equal to, or * greater than the second. * @return {boolean} True if an element was inserted. * @template VALUE */ goog.array.binaryInsert = function(array, value, opt_compareFn) { var index = goog.array.binarySearch(array, value, opt_compareFn); if (index < 0) { goog.array.insertAt(array, value, -(index + 1)); return true; } return false; }; /** * Removes a value from a sorted array. * @param {!IArrayLike<VALUE>} array The array to modify. * @param {VALUE} value The object to remove. * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison * function by which the array is ordered. Should take 2 arguments to * compare, and return a negative number, zero, or a positive number * depending on whether the first argument is less than, equal to, or * greater than the second. * @return {boolean} True if an element was removed. * @template VALUE */ goog.array.binaryRemove = function(array, value, opt_compareFn) { var index = goog.array.binarySearch(array, value, opt_compareFn); return (index >= 0) ? goog.array.removeAt(array, index) : false; }; /** * Splits an array into disjoint buckets according to a splitting function. * @param {IArrayLike<T>} array The array. * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to * call for every element. This takes 3 arguments (the element, the index * and the array) and must return a valid object key (a string, number, * etc), or undefined, if that object should not be placed in a bucket. * @param {S=} opt_obj The object to be used as the value of 'this' within * sorter. * @return {!Object<!Array<T>>} An object, with keys being all of the unique * return values of sorter, and values being arrays containing the items for * which the splitter returned that key. * @template T,S */ goog.array.bucket = function(array, sorter, opt_obj) { var buckets = {}; for (var i = 0; i < array.length; i++) { var value = array[i]; var key = sorter.call(/** @type {?} */ (opt_obj), value, i, array); if (goog.isDef(key)) { // Push the value to the right bucket, creating it if necessary. var bucket = buckets[key] || (buckets[key] = []); bucket.push(value); } } return buckets; }; /** * Creates a new object built from the provided array and the key-generation * function. * @param {IArrayLike<T>} arr Array or array like object over * which to iterate whose elements will be the values in the new object. * @param {?function(this:S, T, number, ?) : string} keyFunc The function to * call for every element. This function takes 3 arguments (the element, the * index and the array) and should return a string that will be used as the * key for the element in the new object. If the function returns the same * key for more than one element, the value for that key is * implementation-defined. * @param {S=} opt_obj The object to be used as the value of 'this' * within keyFunc. * @return {!Object<T>} The new object. * @template T,S */ goog.array.toObject = function(arr, keyFunc, opt_obj) { var ret = {}; goog.array.forEach(arr, function(element, index) { ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] = element; }); return ret; }; /** * Creates a range of numbers in an arithmetic progression. * * Range takes 1, 2, or 3 arguments: * <pre> * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4] * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4] * range(-2, -5, -1) produces [-2, -3, -4] * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5. * </pre> * * @param {number} startOrEnd The starting value of the range if an end argument * is provided. Otherwise, the start value is 0, and this is the end value. * @param {number=} opt_end The optional end value of the range. * @param {number=} opt_step The step size between range values. Defaults to 1 * if opt_step is undefined or 0. * @return {!Array<number>} An array of numbers for the requested range. May be * an empty array if adding the step would not converge toward the end * value. */ goog.array.range = function(startOrEnd, opt_end, opt_step) { var array = []; var start = 0; var end = startOrEnd; var step = opt_step || 1; if (opt_end !== undefined) { start = startOrEnd; end = opt_end; } if (step * (end - start) < 0) { // Sign mismatch: start + step will never reach the end value. return []; } if (step > 0) { for (var i = start; i < end; i += step) { array.push(i); } } else { for (var i = start; i > end; i += step) { array.push(i); } } return array; }; /** * Returns an array consisting of the given value repeated N times. * * @param {VALUE} value The value to repeat. * @param {number} n The repeat count. * @return {!Array<VALUE>} An array with the repeated value. * @template VALUE */ goog.array.repeat = function(value, n) { var array = []; for (var i = 0; i < n; i++) { array[i] = value; } return array; }; /** * Returns an array consisting of every argument with all arrays * expanded in-place recursively. * * @param {...*} var_args The values to flatten. * @return {!Array<?>} An array containing the flattened values. */ goog.array.flatten = function(var_args) { var CHUNK_SIZE = 8192; var result = []; for (var i = 0; i < arguments.length; i++) { var element = arguments[i]; if (goog.isArray(element)) { for (var c = 0; c < element.length; c += CHUNK_SIZE) { var chunk = goog.array.slice(element, c, c + CHUNK_SIZE); var recurseResult = goog.array.flatten.apply(null, chunk); for (var r = 0; r < recurseResult.length; r++) { result.push(recurseResult[r]); } } } else { result.push(element); } } return result; }; /** * Rotates an array in-place. After calling this method, the element at * index i will be the element previously at index (i - n) % * array.length, for all values of i between 0 and array.length - 1, * inclusive. * * For example, suppose list comprises [t, a, n, k, s]. After invoking * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k]. * * @param {!Array<T>} array The array to rotate. * @param {number} n The amount to rotate. * @return {!Array<T>} The array. * @template T */ goog.array.rotate = function(array, n) { goog.asserts.assert(array.length != null); if (array.length) { n %= array.length; if (n > 0) { Array.prototype.unshift.apply(array, array.splice(-n, n)); } else if (n < 0) { Array.prototype.push.apply(array, array.splice(0, -n)); } } return array; }; /** * Moves one item of an array to a new position keeping the order of the rest * of the items. Example use case: keeping a list of JavaScript objects * synchronized with the corresponding list of DOM elements after one of the * elements has been dragged to a new position. * @param {!IArrayLike<?>} arr The array to modify. * @param {number} fromIndex Index of the item to move between 0 and * {@code arr.length - 1}. * @param {number} toIndex Target index between 0 and {@code arr.length - 1}. */ goog.array.moveItem = function(arr, fromIndex, toIndex) { goog.asserts.assert(fromIndex >= 0 && fromIndex < arr.length); goog.asserts.assert(toIndex >= 0 && toIndex < arr.length); // Remove 1 item at fromIndex. var removedItems = Array.prototype.splice.call(arr, fromIndex, 1); // Insert the removed item at toIndex. Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]); // We don't use goog.array.insertAt and goog.array.removeAt, because they're // significantly slower than splice. }; /** * Creates a new array for which the element at position i is an array of the * ith element of the provided arrays. The returned array will only be as long * as the shortest array provided; additional values are ignored. For example, * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]]. * * This is similar to the zip() function in Python. See {@link * http://docs.python.org/library/functions.html#zip} * * @param {...!IArrayLike<?>} var_args Arrays to be combined. * @return {!Array<!Array<?>>} A new array of arrays created from * provided arrays. */ goog.array.zip = function(var_args) { if (!arguments.length) { return []; } var result = []; var minLen = arguments[0].length; for (var i = 1; i < arguments.length; i++) { if (arguments[i].length < minLen) { minLen = arguments[i].length; } } for (var i = 0; i < minLen; i++) { var value = []; for (var j = 0; j < arguments.length; j++) { value.push(arguments[j][i]); } result.push(value); } return result; }; /** * Shuffles the values in the specified array using the Fisher-Yates in-place * shuffle (also known as the Knuth Shuffle). By default, calls Math.random() * and so resets the state of that random number generator. Similarly, may reset * the state of the any other specified random number generator. * * Runtime: O(n) * * @param {!Array<?>} arr The array to be shuffled. * @param {function():number=} opt_randFn Optional random function to use for * shuffling. * Takes no arguments, and returns a random number on the interval [0, 1). * Defaults to Math.random() using JavaScript's built-in Math library. */ goog.array.shuffle = function(arr, opt_randFn) { var randFn = opt_randFn || Math.random; for (var i = arr.length - 1; i > 0; i--) { // Choose a random array index in [0, i] (inclusive with i). var j = Math.floor(randFn() * (i + 1)); var tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } }; /** * Returns a new array of elements from arr, based on the indexes of elements * provided by index_arr. For example, the result of index copying * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c']. * * @param {!IArrayLike<T>} arr The array to get a indexed copy from. * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr. * @return {!Array<T>} A new array of elements from arr in index_arr order. * @template T */ goog.array.copyByIndex = function(arr, index_arr) { var result = []; goog.array.forEach(index_arr, function(index) { result.push(arr[index]); }); return result; }; /** * Maps each element of the input array into zero or more elements of the output * array. * * @param {!IArrayLike<VALUE>|string} arr Array or array like object * over which to iterate. * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function * to call for every element. This function takes 3 arguments (the element, * the index and the array) and should return an array. The result will be * used to extend a new array. * @param {THIS=} opt_obj The object to be used as the value of 'this' within f. * @return {!Array<RESULT>} a new array with the concatenation of all arrays * returned from f. * @template THIS, VALUE, RESULT */ goog.array.concatMap = function(arr, f, opt_obj) { return goog.array.concat.apply([], goog.array.map(arr, f, opt_obj)); }; //javascript/closure/debug/errorcontext.js // Copyright 2017 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Provides methods dealing with context on error objects. */ goog.provide('goog.debug.errorcontext'); /** * Adds key-value context to the error. * @param {!Error} err The error to add context to. * @param {string} contextKey Key for the context to be added. * @param {string} contextValue Value for the context to be added. */ goog.debug.errorcontext.addErrorContext = function( err, contextKey, contextValue) { if (!err[goog.debug.errorcontext.CONTEXT_KEY_]) { err[goog.debug.errorcontext.CONTEXT_KEY_] = {}; } err[goog.debug.errorcontext.CONTEXT_KEY_][contextKey] = contextValue; }; /** * @param {!Error} err The error to get context from. * @return {!Object<string, string>} The context of the provided error. */ goog.debug.errorcontext.getErrorContext = function(err) { return err[goog.debug.errorcontext.CONTEXT_KEY_] || {}; }; // TODO(user): convert this to a Symbol once goog.debug.ErrorReporter is // able to use ES6. /** @private @const {string} */ goog.debug.errorcontext.CONTEXT_KEY_ = '__closure__error__context__984382'; //javascript/closure/string/string.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities for string manipulation. * @author <EMAIL> (<NAME>) */ /** * Namespace for string utilities */ goog.provide('goog.string'); goog.provide('goog.string.Unicode'); /** * @define {boolean} Enables HTML escaping of lowercase letter "e" which helps * with detection of double-escaping as this letter is frequently used. */ goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false); /** * @define {boolean} Whether to force non-dom html unescaping. */ goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false); /** * Common Unicode string characters. * @enum {string} */ goog.string.Unicode = { NBSP: '\xa0' }; /** * Fast prefix-checker. * @param {string} str The string to check. * @param {string} prefix A string to look for at the start of `str`. * @return {boolean} True if `str` begins with `prefix`. */ goog.string.startsWith = function(str, prefix) { return str.lastIndexOf(prefix, 0) == 0; }; /** * Fast suffix-checker. * @param {string} str The string to check. * @param {string} suffix A string to look for at the end of `str`. * @return {boolean} True if `str` ends with `suffix`. */ goog.string.endsWith = function(str, suffix) { var l = str.length - suffix.length; return l >= 0 && str.indexOf(suffix, l) == l; }; /** * Case-insensitive prefix-checker. * @param {string} str The string to check. * @param {string} prefix A string to look for at the end of `str`. * @return {boolean} True if `str` begins with `prefix` (ignoring * case). */ goog.string.caseInsensitiveStartsWith = function(str, prefix) { return goog.string.caseInsensitiveCompare( prefix, str.substr(0, prefix.length)) == 0; }; /** * Case-insensitive suffix-checker. * @param {string} str The string to check. * @param {string} suffix A string to look for at the end of `str`. * @return {boolean} True if `str` ends with `suffix` (ignoring * case). */ goog.string.caseInsensitiveEndsWith = function(str, suffix) { return ( goog.string.caseInsensitiveCompare( suffix, str.substr(str.length - suffix.length, suffix.length)) == 0); }; /** * Case-insensitive equality checker. * @param {string} str1 First string to check. * @param {string} str2 Second string to check. * @return {boolean} True if `str1` and `str2` are the same string, * ignoring case. */ goog.string.caseInsensitiveEquals = function(str1, str2) { return str1.toLowerCase() == str2.toLowerCase(); }; /** * Does simple python-style string substitution. * subs("foo%s hot%s", "bar", "dog") becomes "foobar hotdog". * @param {string} str The string containing the pattern. * @param {...*} var_args The items to substitute into the pattern. * @return {string} A copy of `str` in which each occurrence of * {@code %s} has been replaced an argument from `var_args`. */ goog.string.subs = function(str, var_args) { var splitParts = str.split('%s'); var returnString = ''; var subsArguments = Array.prototype.slice.call(arguments, 1); while (subsArguments.length && // Replace up to the last split part. We are inserting in the // positions between split parts. splitParts.length > 1) { returnString += splitParts.shift() + subsArguments.shift(); } return returnString + splitParts.join('%s'); // Join unused '%s' }; /** * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines * and tabs) to a single space, and strips leading and trailing whitespace. * @param {string} str Input string. * @return {string} A copy of `str` with collapsed whitespace. */ goog.string.collapseWhitespace = function(str) { // Since IE doesn't include non-breaking-space (0xa0) in their \s character // class (as required by section 7.2 of the ECMAScript spec), we explicitly // include it in the regexp to enforce consistent cross-browser behavior. return str.replace(/[\s\xa0]+/g, ' ').replace(/^\s+|\s+$/g, ''); }; /** * Checks if a string is empty or contains only whitespaces. * @param {string} str The string to check. * @return {boolean} Whether `str` is empty or whitespace only. */ goog.string.isEmptyOrWhitespace = function(str) { // testing length == 0 first is actually slower in all browsers (about the // same in Opera). // Since IE doesn't include non-breaking-space (0xa0) in their \s character // class (as required by section 7.2 of the ECMAScript spec), we explicitly // include it in the regexp to enforce consistent cross-browser behavior. return /^[\s\xa0]*$/.test(str); }; /** * Checks if a string is empty. * @param {string} str The string to check. * @return {boolean} Whether `str` is empty. */ goog.string.isEmptyString = function(str) { return str.length == 0; }; /** * Checks if a string is empty or contains only whitespaces. * * @param {string} str The string to check. * @return {boolean} Whether `str` is empty or whitespace only. * @deprecated Use goog.string.isEmptyOrWhitespace instead. */ goog.string.isEmpty = goog.string.isEmptyOrWhitespace; /** * Checks if a string is null, undefined, empty or contains only whitespaces. * @param {*} str The string to check. * @return {boolean} Whether `str` is null, undefined, empty, or * whitespace only. * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)) * instead. */ goog.string.isEmptyOrWhitespaceSafe = function(str) { return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str)); }; /** * Checks if a string is null, undefined, empty or contains only whitespaces. * * @param {*} str The string to check. * @return {boolean} Whether `str` is null, undefined, empty, or * whitespace only. * @deprecated Use goog.string.isEmptyOrWhitespace instead. */ goog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe; /** * Checks if a string is all breaking whitespace. * @param {string} str The string to check. * @return {boolean} Whether the string is all breaking whitespace. */ goog.string.isBreakingWhitespace = function(str) { return !/[^\t\n\r ]/.test(str); }; /** * Checks if a string contains all letters. * @param {string} str string to check. * @return {boolean} True if `str` consists entirely of letters. */ goog.string.isAlpha = function(str) { return !/[^a-zA-Z]/.test(str); }; /** * Checks if a string contains only numbers. * @param {*} str string to check. If not a string, it will be * casted to one. * @return {boolean} True if `str` is numeric. */ goog.string.isNumeric = function(str) { return !/[^0-9]/.test(str); }; /** * Checks if a string contains only numbers or letters. * @param {string} str string to check. * @return {boolean} True if `str` is alphanumeric. */ goog.string.isAlphaNumeric = function(str) { return !/[^a-zA-Z0-9]/.test(str); }; /** * Checks if a character is a space character. * @param {string} ch Character to check. * @return {boolean} True if `ch` is a space. */ goog.string.isSpace = function(ch) { return ch == ' '; }; /** * Checks if a character is a valid unicode character. * @param {string} ch Character to check. * @return {boolean} True if `ch` is a valid unicode character. */ goog.string.isUnicodeChar = function(ch) { return ch.length == 1 && ch >= ' ' && ch <= '~' || ch >= '\u0080' && ch <= '\uFFFD'; }; /** * Takes a string and replaces newlines with a space. Multiple lines are * replaced with a single space. * @param {string} str The string from which to strip newlines. * @return {string} A copy of `str` stripped of newlines. */ goog.string.stripNewlines = function(str) { return str.replace(/(\r\n|\r|\n)+/g, ' '); }; /** * Replaces Windows and Mac new lines with unix style: \r or \r\n with \n. * @param {string} str The string to in which to canonicalize newlines. * @return {string} `str` A copy of {@code} with canonicalized newlines. */ goog.string.canonicalizeNewlines = function(str) { return str.replace(/(\r\n|\r|\n)/g, '\n'); }; /** * Normalizes whitespace in a string, replacing all whitespace chars with * a space. * @param {string} str The string in which to normalize whitespace. * @return {string} A copy of `str` with all whitespace normalized. */ goog.string.normalizeWhitespace = function(str) { return str.replace(/\xa0|\s/g, ' '); }; /** * Normalizes spaces in a string, replacing all consecutive spaces and tabs * with a single space. Replaces non-breaking space with a space. * @param {string} str The string in which to normalize spaces. * @return {string} A copy of `str` with all consecutive spaces and tabs * replaced with a single space. */ goog.string.normalizeSpaces = function(str) { return str.replace(/\xa0|[ \t]+/g, ' '); }; /** * Removes the breaking spaces from the left and right of the string and * collapses the sequences of breaking spaces in the middle into single spaces. * The original and the result strings render the same way in HTML. * @param {string} str A string in which to collapse spaces. * @return {string} Copy of the string with normalized breaking spaces. */ goog.string.collapseBreakingSpaces = function(str) { return str.replace(/[\t\r\n ]+/g, ' ') .replace(/^[\t\r\n ]+|[\t\r\n ]+$/g, ''); }; /** * Trims white spaces to the left and right of a string. * @param {string} str The string to trim. * @return {string} A trimmed copy of `str`. */ goog.string.trim = (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) { return str.trim(); } : function(str) { // Since IE doesn't include non-breaking-space (0xa0) in their \s // character class (as required by section 7.2 of the ECMAScript spec), // we explicitly include it in the regexp to enforce consistent // cross-browser behavior. // NOTE: We don't use String#replace because it might have side effects // causing this function to not compile to 0 bytes. return /^[\s\xa0]*([\s\S]*?)[\s\xa0]*$/.exec(str)[1]; }; /** * Trims whitespaces at the left end of a string. * @param {string} str The string to left trim. * @return {string} A trimmed copy of `str`. */ goog.string.trimLeft = function(str) { // Since IE doesn't include non-breaking-space (0xa0) in their \s character // class (as required by section 7.2 of the ECMAScript spec), we explicitly // include it in the regexp to enforce consistent cross-browser behavior. return str.replace(/^[\s\xa0]+/, ''); }; /** * Trims whitespaces at the right end of a string. * @param {string} str The string to right trim. * @return {string} A trimmed copy of `str`. */ goog.string.trimRight = function(str) { // Since IE doesn't include non-breaking-space (0xa0) in their \s character // class (as required by section 7.2 of the ECMAScript spec), we explicitly // include it in the regexp to enforce consistent cross-browser behavior. return str.replace(/[\s\xa0]+$/, ''); }; /** * A string comparator that ignores case. * -1 = str1 less than str2 * 0 = str1 equals str2 * 1 = str1 greater than str2 * * @param {string} str1 The string to compare. * @param {string} str2 The string to compare `str1` to. * @return {number} The comparator result, as described above. */ goog.string.caseInsensitiveCompare = function(str1, str2) { var test1 = String(str1).toLowerCase(); var test2 = String(str2).toLowerCase(); if (test1 < test2) { return -1; } else if (test1 == test2) { return 0; } else { return 1; } }; /** * Compares two strings interpreting their numeric substrings as numbers. * * @param {string} str1 First string. * @param {string} str2 Second string. * @param {!RegExp} tokenizerRegExp Splits a string into substrings of * non-negative integers, non-numeric characters and optionally fractional * numbers starting with a decimal point. * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if * str1 > str2. * @private */ goog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) { if (str1 == str2) { return 0; } if (!str1) { return -1; } if (!str2) { return 1; } // Using match to split the entire string ahead of time turns out to be faster // for most inputs than using RegExp.exec or iterating over each character. var tokens1 = str1.toLowerCase().match(tokenizerRegExp); var tokens2 = str2.toLowerCase().match(tokenizerRegExp); var count = Math.min(tokens1.length, tokens2.length); for (var i = 0; i < count; i++) { var a = tokens1[i]; var b = tokens2[i]; // Compare pairs of tokens, returning if one token sorts before the other. if (a != b) { // Only if both tokens are integers is a special comparison required. // Decimal numbers are sorted as strings (e.g., '.09' < '.1'). var num1 = parseInt(a, 10); if (!isNaN(num1)) { var num2 = parseInt(b, 10); if (!isNaN(num2) && num1 - num2) { return num1 - num2; } } return a < b ? -1 : 1; } } // If one string is a substring of the other, the shorter string sorts first. if (tokens1.length != tokens2.length) { return tokens1.length - tokens2.length; } // The two strings must be equivalent except for case (perfect equality is // tested at the head of the function.) Revert to default ASCII string // comparison to stabilize the sort. return str1 < str2 ? -1 : 1; }; /** * String comparison function that handles non-negative integer numbers in a * way humans might expect. Using this function, the string 'File 2.jpg' sorts * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison * is mostly case-insensitive, though strings that are identical except for case * are sorted with the upper-case strings before lower-case. * * This comparison function is up to 50x slower than either the default or the * case-insensitive compare. It should not be used in time-critical code, but * should be fast enough to sort several hundred short strings (like filenames) * with a reasonable delay. * * @param {string} str1 The string to compare in a numerically sensitive way. * @param {string} str2 The string to compare `str1` to. * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than * 0 if str1 > str2. */ goog.string.intAwareCompare = function(str1, str2) { return goog.string.numberAwareCompare_(str1, str2, /\d+|\D+/g); }; /** * String comparison function that handles non-negative integer and fractional * numbers in a way humans might expect. Using this function, the string * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent * to {@link goog.string.intAwareCompare} apart from the way how it interprets * dots. * * @param {string} str1 The string to compare in a numerically sensitive way. * @param {string} str2 The string to compare `str1` to. * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than * 0 if str1 > str2. */ goog.string.floatAwareCompare = function(str1, str2) { return goog.string.numberAwareCompare_(str1, str2, /\d+|\.\d+|\D+/g); }; /** * Alias for {@link goog.string.floatAwareCompare}. * * @param {string} str1 * @param {string} str2 * @return {number} */ goog.string.numerateCompare = goog.string.floatAwareCompare; /** * URL-encodes a string * @param {*} str The string to url-encode. * @return {string} An encoded copy of `str` that is safe for urls. * Note that '#', ':', and other characters used to delimit portions * of URLs *will* be encoded. */ goog.string.urlEncode = function(str) { return encodeURIComponent(String(str)); }; /** * URL-decodes the string. We need to specially handle '+'s because * the javascript library doesn't convert them to spaces. * @param {string} str The string to url decode. * @return {string} The decoded `str`. */ goog.string.urlDecode = function(str) { return decodeURIComponent(str.replace(/\+/g, ' ')); }; /** * Converts \n to <br>s or <br />s. * @param {string} str The string in which to convert newlines. * @param {boolean=} opt_xml Whether to use XML compatible tags. * @return {string} A copy of `str` with converted newlines. */ goog.string.newLineToBr = function(str, opt_xml) { return str.replace(/(\r\n|\r|\n)/g, opt_xml ? '<br />' : '<br>'); }; /** * Escapes double quote '"' and single quote '\'' characters in addition to * '&', '<', and '>' so that a string can be included in an HTML tag attribute * value within double or single quotes. * * It should be noted that > doesn't need to be escaped for the HTML or XML to * be valid, but it has been decided to escape it for consistency with other * implementations. * * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the * lowercase letter "e". * * NOTE(user): * HtmlEscape is often called during the generation of large blocks of HTML. * Using statics for the regular expressions and strings is an optimization * that can more than half the amount of time IE spends in this function for * large apps, since strings and regexes both contribute to GC allocations. * * Testing for the presence of a character before escaping increases the number * of function calls, but actually provides a speed increase for the average * case -- since the average case often doesn't require the escaping of all 4 * characters and indexOf() is much cheaper than replace(). * The worst case does suffer slightly from the additional calls, therefore the * opt_isLikelyToContainHtmlChars option has been included for situations * where all 4 HTML entities are very likely to be present and need escaping. * * Some benchmarks (times tended to fluctuate +-0.05ms): * FireFox IE6 * (no chars / average (mix of cases) / all 4 chars) * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80 * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84 * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85 * * An additional advantage of checking if replace actually needs to be called * is a reduction in the number of object allocations, so as the size of the * application grows the difference between the various methods would increase. * * @param {string} str string to be escaped. * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see * if the character needs replacing - use this option if you expect each of * the characters to appear often. Leave false if you expect few html * characters to occur in your strings, such as if you are escaping HTML. * @return {string} An escaped copy of `str`. */ goog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) { if (opt_isLikelyToContainHtmlChars) { str = str.replace(goog.string.AMP_RE_, '&amp;') .replace(goog.string.LT_RE_, '&lt;') .replace(goog.string.GT_RE_, '&gt;') .replace(goog.string.QUOT_RE_, '&quot;') .replace(goog.string.SINGLE_QUOTE_RE_, '&#39;') .replace(goog.string.NULL_RE_, '&#0;'); if (goog.string.DETECT_DOUBLE_ESCAPING) { str = str.replace(goog.string.E_RE_, '&#101;'); } return str; } else { // quick test helps in the case when there are no chars to replace, in // worst case this makes barely a difference to the time taken if (!goog.string.ALL_RE_.test(str)) return str; // str.indexOf is faster than regex.test in this case if (str.indexOf('&') != -1) { str = str.replace(goog.string.AMP_RE_, '&amp;'); } if (str.indexOf('<') != -1) { str = str.replace(goog.string.LT_RE_, '&lt;'); } if (str.indexOf('>') != -1) { str = str.replace(goog.string.GT_RE_, '&gt;'); } if (str.indexOf('"') != -1) { str = str.replace(goog.string.QUOT_RE_, '&quot;'); } if (str.indexOf('\'') != -1) { str = str.replace(goog.string.SINGLE_QUOTE_RE_, '&#39;'); } if (str.indexOf('\x00') != -1) { str = str.replace(goog.string.NULL_RE_, '&#0;'); } if (goog.string.DETECT_DOUBLE_ESCAPING && str.indexOf('e') != -1) { str = str.replace(goog.string.E_RE_, '&#101;'); } return str; } }; /** * Regular expression that matches an ampersand, for use in escaping. * @const {!RegExp} * @private */ goog.string.AMP_RE_ = /&/g; /** * Regular expression that matches a less than sign, for use in escaping. * @const {!RegExp} * @private */ goog.string.LT_RE_ = /</g; /** * Regular expression that matches a greater than sign, for use in escaping. * @const {!RegExp} * @private */ goog.string.GT_RE_ = />/g; /** * Regular expression that matches a double quote, for use in escaping. * @const {!RegExp} * @private */ goog.string.QUOT_RE_ = /"/g; /** * Regular expression that matches a single quote, for use in escaping. * @const {!RegExp} * @private */ goog.string.SINGLE_QUOTE_RE_ = /'/g; /** * Regular expression that matches null character, for use in escaping. * @const {!RegExp} * @private */ goog.string.NULL_RE_ = /\x00/g; /** * Regular expression that matches a lowercase letter "e", for use in escaping. * @const {!RegExp} * @private */ goog.string.E_RE_ = /e/g; /** * Regular expression that matches any character that needs to be escaped. * @const {!RegExp} * @private */ goog.string.ALL_RE_ = (goog.string.DETECT_DOUBLE_ESCAPING ? /[\x00&<>"'e]/ : /[\x00&<>"']/); /** * Unescapes an HTML string. * * @param {string} str The string to unescape. * @return {string} An unescaped copy of `str`. */ goog.string.unescapeEntities = function(str) { if (goog.string.contains(str, '&')) { // We are careful not to use a DOM if we do not have one or we explicitly // requested non-DOM html unescaping. if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING && 'document' in goog.global) { return goog.string.unescapeEntitiesUsingDom_(str); } else { // Fall back on pure XML entities return goog.string.unescapePureXmlEntities_(str); } } return str; }; /** * Unescapes a HTML string using the provided document. * * @param {string} str The string to unescape. * @param {!Document} document A document to use in escaping the string. * @return {string} An unescaped copy of `str`. */ goog.string.unescapeEntitiesWithDocument = function(str, document) { if (goog.string.contains(str, '&')) { return goog.string.unescapeEntitiesUsingDom_(str, document); } return str; }; /** * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric * entities. This function is XSS-safe and whitespace-preserving. * @private * @param {string} str The string to unescape. * @param {Document=} opt_document An optional document to use for creating * elements. If this is not specified then the default window.document * will be used. * @return {string} The unescaped `str` string. */ goog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) { /** @type {!Object<string, string>} */ var seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"'}; var div; if (opt_document) { div = opt_document.createElement('div'); } else { div = goog.global.document.createElement('div'); } // Match as many valid entity characters as possible. If the actual entity // happens to be shorter, it will still work as innerHTML will return the // trailing characters unchanged. Since the entity characters do not include // open angle bracket, there is no chance of XSS from the innerHTML use. // Since no whitespace is passed to innerHTML, whitespace is preserved. return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) { // Check for cached entity. var value = seen[s]; if (value) { return value; } // Check for numeric entity. if (entity.charAt(0) == '#') { // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers. var n = Number('0' + entity.substr(1)); if (!isNaN(n)) { value = String.fromCharCode(n); } } // Fall back to innerHTML otherwise. if (!value) { // Append a non-entity character to avoid a bug in Webkit that parses // an invalid entity at the end of innerHTML text as the empty string. div.innerHTML = s + ' '; // Then remove the trailing character from the result. value = div.firstChild.nodeValue.slice(0, -1); } // Cache and return. return seen[s] = value; }); }; /** * Unescapes XML entities. * @private * @param {string} str The string to unescape. * @return {string} An unescaped copy of `str`. */ goog.string.unescapePureXmlEntities_ = function(str) { return str.replace(/&([^;]+);/g, function(s, entity) { switch (entity) { case 'amp': return '&'; case 'lt': return '<'; case 'gt': return '>'; case 'quot': return '"'; default: if (entity.charAt(0) == '#') { // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex. var n = Number('0' + entity.substr(1)); if (!isNaN(n)) { return String.fromCharCode(n); } } // For invalid entities we just return the entity return s; } }); }; /** * Regular expression that matches an HTML entity. * See also HTML5: Tokenization / Tokenizing character references. * @private * @type {!RegExp} */ goog.string.HTML_ENTITY_PATTERN_ = /&([^;\s<&]+);?/g; /** * Do escaping of whitespace to preserve spatial formatting. We use character * entity #160 to make it safer for xml. * @param {string} str The string in which to escape whitespace. * @param {boolean=} opt_xml Whether to use XML compatible tags. * @return {string} An escaped copy of `str`. */ goog.string.whitespaceEscape = function(str, opt_xml) { // This doesn't use goog.string.preserveSpaces for backwards compatibility. return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml); }; /** * Preserve spaces that would be otherwise collapsed in HTML by replacing them * with non-breaking space Unicode characters. * @param {string} str The string in which to preserve whitespace. * @return {string} A copy of `str` with preserved whitespace. */ goog.string.preserveSpaces = function(str) { return str.replace(/(^|[\n ]) /g, '$1' + goog.string.Unicode.NBSP); }; /** * Strip quote characters around a string. The second argument is a string of * characters to treat as quotes. This can be a single character or a string of * multiple character and in that case each of those are treated as possible * quote characters. For example: * * <pre> * goog.string.stripQuotes('"abc"', '"`') --> 'abc' * goog.string.stripQuotes('`abc`', '"`') --> 'abc' * </pre> * * @param {string} str The string to strip. * @param {string} quoteChars The quote characters to strip. * @return {string} A copy of `str` without the quotes. */ goog.string.stripQuotes = function(str, quoteChars) { var length = quoteChars.length; for (var i = 0; i < length; i++) { var quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i); if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) { return str.substring(1, str.length - 1); } } return str; }; /** * Truncates a string to a certain length and adds '...' if necessary. The * length also accounts for the ellipsis, so a maximum length of 10 and a string * 'Hello World!' produces 'Hello W...'. * @param {string} str The string to truncate. * @param {number} chars Max number of characters. * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped * characters from being cut off in the middle. * @return {string} The truncated `str` string. */ goog.string.truncate = function(str, chars, opt_protectEscapedCharacters) { if (opt_protectEscapedCharacters) { str = goog.string.unescapeEntities(str); } if (str.length > chars) { str = str.substring(0, chars - 3) + '...'; } if (opt_protectEscapedCharacters) { str = goog.string.htmlEscape(str); } return str; }; /** * Truncate a string in the middle, adding "..." if necessary, * and favoring the beginning of the string. * @param {string} str The string to truncate the middle of. * @param {number} chars Max number of characters. * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped * characters from being cutoff in the middle. * @param {number=} opt_trailingChars Optional number of trailing characters to * leave at the end of the string, instead of truncating as close to the * middle as possible. * @return {string} A truncated copy of `str`. */ goog.string.truncateMiddle = function( str, chars, opt_protectEscapedCharacters, opt_trailingChars) { if (opt_protectEscapedCharacters) { str = goog.string.unescapeEntities(str); } if (opt_trailingChars && str.length > chars) { if (opt_trailingChars > chars) { opt_trailingChars = chars; } var endPoint = str.length - opt_trailingChars; var startPoint = chars - opt_trailingChars; str = str.substring(0, startPoint) + '...' + str.substring(endPoint); } else if (str.length > chars) { // Favor the beginning of the string: var half = Math.floor(chars / 2); var endPos = str.length - half; half += chars % 2; str = str.substring(0, half) + '...' + str.substring(endPos); } if (opt_protectEscapedCharacters) { str = goog.string.htmlEscape(str); } return str; }; /** * Special chars that need to be escaped for goog.string.quote. * @private {!Object<string, string>} */ goog.string.specialEscapeChars_ = { '\0': '\\0', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t', '\x0B': '\\x0B', // '\v' is not supported in JScript '"': '\\"', '\\': '\\\\', // To support the use case of embedding quoted strings inside of script // tags, we have to make sure HTML comments and opening/closing script tags do // not appear in the resulting string. The specific strings that must be // escaped are documented at: // http://www.w3.org/TR/html51/semantics.html#restrictions-for-contents-of-script-elements '<': '\x3c' }; /** * Character mappings used internally for goog.string.escapeChar. * @private {!Object<string, string>} */ goog.string.jsEscapeCache_ = { '\'': '\\\'' }; /** * Encloses a string in double quotes and escapes characters so that the * string is a valid JS string. The resulting string is safe to embed in * `<script>` tags as "<" is escaped. * @param {string} s The string to quote. * @return {string} A copy of `s` surrounded by double quotes. */ goog.string.quote = function(s) { s = String(s); var sb = ['"']; for (var i = 0; i < s.length; i++) { var ch = s.charAt(i); var cc = ch.charCodeAt(0); sb[i + 1] = goog.string.specialEscapeChars_[ch] || ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch)); } sb.push('"'); return sb.join(''); }; /** * Takes a string and returns the escaped string for that input string. * @param {string} str The string to escape. * @return {string} An escaped string representing `str`. */ goog.string.escapeString = function(str) { var sb = []; for (var i = 0; i < str.length; i++) { sb[i] = goog.string.escapeChar(str.charAt(i)); } return sb.join(''); }; /** * Takes a character and returns the escaped string for that character. For * example escapeChar(String.fromCharCode(15)) -> "\\x0E". * @param {string} c The character to escape. * @return {string} An escaped string representing `c`. */ goog.string.escapeChar = function(c) { if (c in goog.string.jsEscapeCache_) { return goog.string.jsEscapeCache_[c]; } if (c in goog.string.specialEscapeChars_) { return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c]; } var rv = c; var cc = c.charCodeAt(0); if (cc > 31 && cc < 127) { rv = c; } else { // tab is 9 but handled above if (cc < 256) { rv = '\\x'; if (cc < 16 || cc > 256) { rv += '0'; } } else { rv = '\\u'; if (cc < 4096) { // \u1000 rv += '0'; } } rv += cc.toString(16).toUpperCase(); } return goog.string.jsEscapeCache_[c] = rv; }; /** * Determines whether a string contains a substring. * @param {string} str The string to search. * @param {string} subString The substring to search for. * @return {boolean} Whether `str` contains `subString`. */ goog.string.contains = function(str, subString) { return str.indexOf(subString) != -1; }; /** * Determines whether a string contains a substring, ignoring case. * @param {string} str The string to search. * @param {string} subString The substring to search for. * @return {boolean} Whether `str` contains `subString`. */ goog.string.caseInsensitiveContains = function(str, subString) { return goog.string.contains(str.toLowerCase(), subString.toLowerCase()); }; /** * Returns the non-overlapping occurrences of ss in s. * If either s or ss evalutes to false, then returns zero. * @param {string} s The string to look in. * @param {string} ss The string to look for. * @return {number} Number of occurrences of ss in s. */ goog.string.countOf = function(s, ss) { return s && ss ? s.split(ss).length - 1 : 0; }; /** * Removes a substring of a specified length at a specific * index in a string. * @param {string} s The base string from which to remove. * @param {number} index The index at which to remove the substring. * @param {number} stringLength The length of the substring to remove. * @return {string} A copy of `s` with the substring removed or the full * string if nothing is removed or the input is invalid. */ goog.string.removeAt = function(s, index, stringLength) { var resultStr = s; // If the index is greater or equal to 0 then remove substring if (index >= 0 && index < s.length && stringLength > 0) { resultStr = s.substr(0, index) + s.substr(index + stringLength, s.length - index - stringLength); } return resultStr; }; /** * Removes the first occurrence of a substring from a string. * @param {string} str The base string from which to remove. * @param {string} substr The string to remove. * @return {string} A copy of `str` with `substr` removed or the * full string if nothing is removed. */ goog.string.remove = function(str, substr) { return str.replace(substr, ''); }; /** * Removes all occurrences of a substring from a string. * @param {string} s The base string from which to remove. * @param {string} ss The string to remove. * @return {string} A copy of `s` with `ss` removed or the full * string if nothing is removed. */ goog.string.removeAll = function(s, ss) { var re = new RegExp(goog.string.regExpEscape(ss), 'g'); return s.replace(re, ''); }; /** * Replaces all occurrences of a substring of a string with a new substring. * @param {string} s The base string from which to remove. * @param {string} ss The string to replace. * @param {string} replacement The replacement string. * @return {string} A copy of `s` with `ss` replaced by * `replacement` or the original string if nothing is replaced. */ goog.string.replaceAll = function(s, ss, replacement) { var re = new RegExp(goog.string.regExpEscape(ss), 'g'); return s.replace(re, replacement.replace(/\$/g, '$$$$')); }; /** * Escapes characters in the string that are not safe to use in a RegExp. * @param {*} s The string to escape. If not a string, it will be casted * to one. * @return {string} A RegExp safe, escaped copy of `s`. */ goog.string.regExpEscape = function(s) { return String(s) .replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1') .replace(/\x08/g, '\\x08'); }; /** * Repeats a string n times. * @param {string} string The string to repeat. * @param {number} length The number of times to repeat. * @return {string} A string containing `length` repetitions of * `string`. */ goog.string.repeat = (String.prototype.repeat) ? function(string, length) { // The native method is over 100 times faster than the alternative. return string.repeat(length); } : function(string, length) { return new Array(length + 1).join(string); }; /** * Pads number to given length and optionally rounds it to a given precision. * For example: * <pre>padNumber(1.25, 2, 3) -> '01.250' * padNumber(1.25, 2) -> '01.25' * padNumber(1.25, 2, 1) -> '01.3' * padNumber(1.25, 0) -> '1.25'</pre> * * @param {number} num The number to pad. * @param {number} length The desired length. * @param {number=} opt_precision The desired precision. * @return {string} `num` as a string with the given options. */ goog.string.padNumber = function(num, length, opt_precision) { var s = goog.isDef(opt_precision) ? num.toFixed(opt_precision) : String(num); var index = s.indexOf('.'); if (index == -1) { index = s.length; } return goog.string.repeat('0', Math.max(0, length - index)) + s; }; /** * Returns a string representation of the given object, with * null and undefined being returned as the empty string. * * @param {*} obj The object to convert. * @return {string} A string representation of the `obj`. */ goog.string.makeSafe = function(obj) { return obj == null ? '' : String(obj); }; /** * Concatenates string expressions. This is useful * since some browsers are very inefficient when it comes to using plus to * concat strings. Be careful when using null and undefined here since * these will not be included in the result. If you need to represent these * be sure to cast the argument to a String first. * For example: * <pre>buildString('a', 'b', 'c', 'd') -> 'abcd' * buildString(null, undefined) -> '' * </pre> * @param {...*} var_args A list of strings to concatenate. If not a string, * it will be casted to one. * @return {string} The concatenation of `var_args`. */ goog.string.buildString = function(var_args) { return Array.prototype.join.call(arguments, ''); }; /** * Returns a string with at least 64-bits of randomness. * * Doesn't trust Javascript's random function entirely. Uses a combination of * random and current timestamp, and then encodes the string in base-36 to * make it shorter. * * @return {string} A random string, e.g. sn1s7vb4gcic. */ goog.string.getRandomString = function() { var x = 2147483648; return Math.floor(Math.random() * x).toString(36) + Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36); }; /** * Compares two version numbers. * * @param {string|number} version1 Version of first item. * @param {string|number} version2 Version of second item. * * @return {number} 1 if `version1` is higher. * 0 if arguments are equal. * -1 if `version2` is higher. */ goog.string.compareVersions = function(version1, version2) { var order = 0; // Trim leading and trailing whitespace and split the versions into // subversions. var v1Subs = goog.string.trim(String(version1)).split('.'); var v2Subs = goog.string.trim(String(version2)).split('.'); var subCount = Math.max(v1Subs.length, v2Subs.length); // Iterate over the subversions, as long as they appear to be equivalent. for (var subIdx = 0; order == 0 && subIdx < subCount; subIdx++) { var v1Sub = v1Subs[subIdx] || ''; var v2Sub = v2Subs[subIdx] || ''; do { // Split the subversions into pairs of numbers and qualifiers (like 'b'). // Two different RegExp objects are use to make it clear the code // is side-effect free var v1Comp = /(\d*)(\D*)(.*)/.exec(v1Sub) || ['', '', '', '']; var v2Comp = /(\d*)(\D*)(.*)/.exec(v2Sub) || ['', '', '', '']; // Break if there are no more matches. if (v1Comp[0].length == 0 && v2Comp[0].length == 0) { break; } // Parse the numeric part of the subversion. A missing number is // equivalent to 0. var v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10); var v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10); // Compare the subversion components. The number has the highest // precedence. Next, if the numbers are equal, a subversion without any // qualifier is always higher than a subversion with any qualifier. Next, // the qualifiers are compared as strings. order = goog.string.compareElements_(v1CompNum, v2CompNum) || goog.string.compareElements_( v1Comp[2].length == 0, v2Comp[2].length == 0) || goog.string.compareElements_(v1Comp[2], v2Comp[2]); // Stop as soon as an inequality is discovered. v1Sub = v1Comp[3]; v2Sub = v2Comp[3]; } while (order == 0); } return order; }; /** * Compares elements of a version number. * * @param {string|number|boolean} left An element from a version number. * @param {string|number|boolean} right An element from a version number. * * @return {number} 1 if `left` is higher. * 0 if arguments are equal. * -1 if `right` is higher. * @private */ goog.string.compareElements_ = function(left, right) { if (left < right) { return -1; } else if (left > right) { return 1; } return 0; }; /** * String hash function similar to java.lang.String.hashCode(). * The hash code for a string is computed as * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], * where s[i] is the ith character of the string and n is the length of * the string. We mod the result to make it between 0 (inclusive) and 2^32 * (exclusive). * @param {string} str A string. * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32 * (exclusive). The empty string returns 0. */ goog.string.hashCode = function(str) { var result = 0; for (var i = 0; i < str.length; ++i) { // Normalize to 4 byte range, 0 ... 2^32. result = (31 * result + str.charCodeAt(i)) >>> 0; } return result; }; /** * The most recent unique ID. |0 is equivalent to Math.floor in this case. * @type {number} * @private */ goog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0; /** * Generates and returns a string which is unique in the current document. * This is useful, for example, to create unique IDs for DOM elements. * @return {string} A unique id. */ goog.string.createUniqueString = function() { return 'goog_' + goog.string.uniqueStringCounter_++; }; /** * Converts the supplied string to a number, which may be Infinity or NaN. * This function strips whitespace: (toNumber(' 123') === 123) * This function accepts scientific notation: (toNumber('1e1') === 10) * * This is better than Javascript's built-in conversions because, sadly: * (Number(' ') === 0) and (parseFloat('123a') === 123) * * @param {string} str The string to convert. * @return {number} The number the supplied string represents, or NaN. */ goog.string.toNumber = function(str) { var num = Number(str); if (num == 0 && goog.string.isEmptyOrWhitespace(str)) { return NaN; } return num; }; /** * Returns whether the given string is lower camel case (e.g. "isFooBar"). * * Note that this assumes the string is entirely letters. * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms * * @param {string} str String to test. * @return {boolean} Whether the string is lower camel case. */ goog.string.isLowerCamelCase = function(str) { return /^[a-z]+([A-Z][a-z]*)*$/.test(str); }; /** * Returns whether the given string is upper camel case (e.g. "FooBarBaz"). * * Note that this assumes the string is entirely letters. * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms * * @param {string} str String to test. * @return {boolean} Whether the string is upper camel case. */ goog.string.isUpperCamelCase = function(str) { return /^([A-Z][a-z]*)+$/.test(str); }; /** * Converts a string from selector-case to camelCase (e.g. from * "multi-part-string" to "multiPartString"), useful for converting * CSS selectors and HTML dataset keys to their equivalent JS properties. * @param {string} str The string in selector-case form. * @return {string} The string in camelCase form. */ goog.string.toCamelCase = function(str) { return String(str).replace( /\-([a-z])/g, function(all, match) { return match.toUpperCase(); }); }; /** * Converts a string from camelCase to selector-case (e.g. from * "multiPartString" to "multi-part-string"), useful for converting JS * style and dataset properties to equivalent CSS selectors and HTML keys. * @param {string} str The string in camelCase form. * @return {string} The string in selector-case form. */ goog.string.toSelectorCase = function(str) { return String(str).replace(/([A-Z])/g, '-$1').toLowerCase(); }; /** * Converts a string into TitleCase. First character of the string is always * capitalized in addition to the first letter of every subsequent word. * Words are delimited by one or more whitespaces by default. Custom delimiters * can optionally be specified to replace the default, which doesn't preserve * whitespace delimiters and instead must be explicitly included if needed. * * Default delimiter => " ": * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree' * goog.string.toTitleCase('one two three') => 'One Two Three' * goog.string.toTitleCase(' one two ') => ' One Two ' * goog.string.toTitleCase('one_two_three') => 'One_two_three' * goog.string.toTitleCase('one-two-three') => 'One-two-three' * * Custom delimiter => "_-.": * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree' * goog.string.toTitleCase('one two three', '_-.') => 'One two three' * goog.string.toTitleCase(' one two ', '_-.') => ' one two ' * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three' * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three' * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three' * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three' * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three' * * @param {string} str String value in camelCase form. * @param {string=} opt_delimiters Custom delimiter character set used to * distinguish words in the string value. Each character represents a * single delimiter. When provided, default whitespace delimiter is * overridden and must be explicitly included if needed. * @return {string} String value in TitleCase form. */ goog.string.toTitleCase = function(str, opt_delimiters) { var delimiters = goog.isString(opt_delimiters) ? goog.string.regExpEscape(opt_delimiters) : '\\s'; // For IE8, we need to prevent using an empty character set. Otherwise, // incorrect matching will occur. delimiters = delimiters ? '|[' + delimiters + ']+' : ''; var regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g'); return str.replace( regexp, function(all, p1, p2) { return p1 + p2.toUpperCase(); }); }; /** * Capitalizes a string, i.e. converts the first letter to uppercase * and all other letters to lowercase, e.g.: * * goog.string.capitalize('one') => 'One' * goog.string.capitalize('ONE') => 'One' * goog.string.capitalize('one two') => 'One two' * * Note that this function does not trim initial whitespace. * * @param {string} str String value to capitalize. * @return {string} String value with first letter in uppercase. */ goog.string.capitalize = function(str) { return String(str.charAt(0)).toUpperCase() + String(str.substr(1)).toLowerCase(); }; /** * Parse a string in decimal or hexidecimal ('0xFFFF') form. * * To parse a particular radix, please use parseInt(string, radix) directly. See * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt * * This is a wrapper for the built-in parseInt function that will only parse * numbers as base 10 or base 16. Some JS implementations assume strings * starting with "0" are intended to be octal. ES3 allowed but discouraged * this behavior. ES5 forbids it. This function emulates the ES5 behavior. * * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj * * @param {string|number|null|undefined} value The value to be parsed. * @return {number} The number, parsed. If the string failed to parse, this * will be NaN. */ goog.string.parseInt = function(value) { // Force finite numbers to strings. if (isFinite(value)) { value = String(value); } if (goog.isString(value)) { // If the string starts with '0x' or '-0x', parse as hex. return /^\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10); } return NaN; }; /** * Splits a string on a separator a limited number of times. * * This implementation is more similar to Python or Java, where the limit * parameter specifies the maximum number of splits rather than truncating * the number of results. * * See http://docs.python.org/2/library/stdtypes.html#str.split * See JavaDoc: http://goo.gl/F2AsY * See Mozilla reference: http://goo.gl/dZdZs * * @param {string} str String to split. * @param {string} separator The separator. * @param {number} limit The limit to the number of splits. The resulting array * will have a maximum length of limit+1. Negative numbers are the same * as zero. * @return {!Array<string>} The string, split. */ goog.string.splitLimit = function(str, separator, limit) { var parts = str.split(separator); var returnVal = []; // Only continue doing this while we haven't hit the limit and we have // parts left. while (limit > 0 && parts.length) { returnVal.push(parts.shift()); limit--; } // If there are remaining parts, append them to the end. if (parts.length) { returnVal.push(parts.join(separator)); } return returnVal; }; /** * Finds the characters to the right of the last instance of any separator * * This function is similar to goog.string.path.baseName, except it can take a * list of characters to split the string on. It will return the rightmost * grouping of characters to the right of any separator as a left-to-right * oriented string. * * @see goog.string.path.baseName * @param {string} str The string * @param {string|!Array<string>} separators A list of separator characters * @return {string} The last part of the string with respect to the separators */ goog.string.lastComponent = function(str, separators) { if (!separators) { return str; } else if (typeof separators == 'string') { separators = [separators]; } var lastSeparatorIndex = -1; for (var i = 0; i < separators.length; i++) { if (separators[i] == '') { continue; } var currentSeparatorIndex = str.lastIndexOf(separators[i]); if (currentSeparatorIndex > lastSeparatorIndex) { lastSeparatorIndex = currentSeparatorIndex; } } if (lastSeparatorIndex == -1) { return str; } return str.slice(lastSeparatorIndex + 1); }; /** * Computes the Levenshtein edit distance between two strings. * @param {string} a * @param {string} b * @return {number} The edit distance between the two strings. */ goog.string.editDistance = function(a, b) { var v0 = []; var v1 = []; if (a == b) { return 0; } if (!a.length || !b.length) { return Math.max(a.length, b.length); } for (var i = 0; i < b.length + 1; i++) { v0[i] = i; } for (var i = 0; i < a.length; i++) { v1[0] = i + 1; for (var j = 0; j < b.length; j++) { var cost = Number(a[i] != b[j]); // Cost for the substring is the minimum of adding one character, removing // one character, or a swap. v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost); } for (var j = 0; j < v0.length; j++) { v0[j] = v1[j]; } } return v1[b.length]; }; //javascript/closure/labs/useragent/util.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities used by goog.labs.userAgent tools. These functions * should not be used outside of goog.labs.userAgent.*. * * @visibility {//javascript/abc/libs/objects3d:__subpackages__} * @visibility {//javascript/closure/bin/sizetests:__pkg__} * @visibility {//javascript/closure/dom:__subpackages__} * @visibility {//javascript/closure/style:__pkg__} * @visibility {//javascript/closure/testing:__pkg__} * @visibility {//javascript/closure/useragent:__subpackages__} * @visibility {//testing/puppet/modules:__pkg__} * @visibility {:util_legacy_users} * * @author <EMAIL> (<NAME>) */ goog.provide('goog.labs.userAgent.util'); goog.require('goog.string'); /** * Gets the native userAgent string from navigator if it exists. * If navigator or navigator.userAgent string is missing, returns an empty * string. * @return {string} * @private */ goog.labs.userAgent.util.getNativeUserAgentString_ = function() { var navigator = goog.labs.userAgent.util.getNavigator_(); if (navigator) { var userAgent = navigator.userAgent; if (userAgent) { return userAgent; } } return ''; }; /** * Getter for the native navigator. * This is a separate function so it can be stubbed out in testing. * @return {Navigator} * @private */ goog.labs.userAgent.util.getNavigator_ = function() { return goog.global.navigator; }; /** * A possible override for applications which wish to not check * navigator.userAgent but use a specified value for detection instead. * @private {string} */ goog.labs.userAgent.util.userAgent_ = goog.labs.userAgent.util.getNativeUserAgentString_(); /** * Applications may override browser detection on the built in * navigator.userAgent object by setting this string. Set to null to use the * browser object instead. * @param {?string=} opt_userAgent The User-Agent override. */ goog.labs.userAgent.util.setUserAgent = function(opt_userAgent) { goog.labs.userAgent.util.userAgent_ = opt_userAgent || goog.labs.userAgent.util.getNativeUserAgentString_(); }; /** * @return {string} The user agent string. */ goog.labs.userAgent.util.getUserAgent = function() { return goog.labs.userAgent.util.userAgent_; }; /** * @param {string} str * @return {boolean} Whether the user agent contains the given string. */ goog.labs.userAgent.util.matchUserAgent = function(str) { var userAgent = goog.labs.userAgent.util.getUserAgent(); return goog.string.contains(userAgent, str); }; /** * @param {string} str * @return {boolean} Whether the user agent contains the given string, ignoring * case. */ goog.labs.userAgent.util.matchUserAgentIgnoreCase = function(str) { var userAgent = goog.labs.userAgent.util.getUserAgent(); return goog.string.caseInsensitiveContains(userAgent, str); }; /** * Parses the user agent into tuples for each section. * @param {string} userAgent * @return {!Array<!Array<string>>} Tuples of key, version, and the contents * of the parenthetical. */ goog.labs.userAgent.util.extractVersionTuples = function(userAgent) { // Matches each section of a user agent string. // Example UA: // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 // This has three version tuples: Mozilla, AppleWebKit, and Mobile. var versionRegExp = new RegExp( // Key. Note that a key may have a space. // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0') '(\\w[\\w ]+)' + '/' + // slash '([^\\s]+)' + // version (i.e. '5.0b') '\\s*' + // whitespace '(?:\\((.*?)\\))?', // parenthetical info. parentheses not matched. 'g'); var data = []; var match; // Iterate and collect the version tuples. Each iteration will be the // next regex match. while (match = versionRegExp.exec(userAgent)) { data.push([ match[1], // key match[2], // value // || undefined as this is not undefined in IE7 and IE8 match[3] || undefined // info ]); } return data; }; //javascript/closure/object/object.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities for manipulating objects/maps/hashes. * @author <EMAIL> (<NAME>) */ goog.provide('goog.object'); /** * Whether two values are not observably distinguishable. This * correctly detects that 0 is not the same as -0 and two NaNs are * practically equivalent. * * The implementation is as suggested by harmony:egal proposal. * * @param {*} v The first value to compare. * @param {*} v2 The second value to compare. * @return {boolean} Whether two values are not observably distinguishable. * @see http://wiki.ecmascript.org/doku.php?id=harmony:egal */ goog.object.is = function(v, v2) { if (v === v2) { // 0 === -0, but they are not identical. // We need the cast because the compiler requires that v2 is a // number (although 1/v2 works with non-number). We cast to ? to // stop the compiler from type-checking this statement. return v !== 0 || 1 / v === 1 / /** @type {?} */ (v2); } // NaN is non-reflexive: NaN !== NaN, although they are identical. return v !== v && v2 !== v2; }; /** * Calls a function for each element in an object/map/hash. * * @param {Object<K,V>} obj The object over which to iterate. * @param {function(this:T,V,?,Object<K,V>):?} f The function to call * for every element. This function takes 3 arguments (the value, the * key and the object) and the return value is ignored. * @param {T=} opt_obj This is used as the 'this' object within f. * @template T,K,V */ goog.object.forEach = function(obj, f, opt_obj) { for (var key in obj) { f.call(/** @type {?} */ (opt_obj), obj[key], key, obj); } }; /** * Calls a function for each element in an object/map/hash. If that call returns * true, adds the element to a new object. * * @param {Object<K,V>} obj The object over which to iterate. * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to call * for every element. This * function takes 3 arguments (the value, the key and the object) * and should return a boolean. If the return value is true the * element is added to the result object. If it is false the * element is not included. * @param {T=} opt_obj This is used as the 'this' object within f. * @return {!Object<K,V>} a new object in which only elements that passed the * test are present. * @template T,K,V */ goog.object.filter = function(obj, f, opt_obj) { var res = {}; for (var key in obj) { if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) { res[key] = obj[key]; } } return res; }; /** * For every element in an object/map/hash calls a function and inserts the * result into a new object. * * @param {Object<K,V>} obj The object over which to iterate. * @param {function(this:T,V,?,Object<K,V>):R} f The function to call * for every element. This function * takes 3 arguments (the value, the key and the object) * and should return something. The result will be inserted * into a new object. * @param {T=} opt_obj This is used as the 'this' object within f. * @return {!Object<K,R>} a new object with the results from f. * @template T,K,V,R */ goog.object.map = function(obj, f, opt_obj) { var res = {}; for (var key in obj) { res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj); } return res; }; /** * Calls a function for each element in an object/map/hash. If any * call returns true, returns true (without checking the rest). If * all calls return false, returns false. * * @param {Object<K,V>} obj The object to check. * @param {function(this:T,V,?,Object<K,V>):boolean} f The function to * call for every element. This function * takes 3 arguments (the value, the key and the object) and should * return a boolean. * @param {T=} opt_obj This is used as the 'this' object within f. * @return {boolean} true if any element passes the test. * @template T,K,V */ goog.object.some = function(obj, f, opt_obj) { for (var key in obj) { if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) { return true; } } return false; }; /** * Calls a function for each element in an object/map/hash. If * all calls return true, returns true. If any call returns false, returns * false at this point and does not continue to check the remaining elements. * * @param {Object<K,V>} obj The object to check. * @param {?function(this:T,V,?,Object<K,V>):boolean} f The function to * call for every element. This function * takes 3 arguments (the value, the key and the object) and should * return a boolean. * @param {T=} opt_obj This is used as the 'this' object within f. * @return {boolean} false if any element fails the test. * @template T,K,V */ goog.object.every = function(obj, f, opt_obj) { for (var key in obj) { if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) { return false; } } return true; }; /** * Returns the number of key-value pairs in the object map. * * @param {Object} obj The object for which to get the number of key-value * pairs. * @return {number} The number of key-value pairs in the object map. */ goog.object.getCount = function(obj) { var rv = 0; for (var key in obj) { rv++; } return rv; }; /** * Returns one key from the object map, if any exists. * For map literals the returned key will be the first one in most of the * browsers (a know exception is Konqueror). * * @param {Object} obj The object to pick a key from. * @return {string|undefined} The key or undefined if the object is empty. */ goog.object.getAnyKey = function(obj) { for (var key in obj) { return key; } }; /** * Returns one value from the object map, if any exists. * For map literals the returned value will be the first one in most of the * browsers (a know exception is Konqueror). * * @param {Object<K,V>} obj The object to pick a value from. * @return {V|undefined} The value or undefined if the object is empty. * @template K,V */ goog.object.getAnyValue = function(obj) { for (var key in obj) { return obj[key]; } }; /** * Whether the object/hash/map contains the given object as a value. * An alias for goog.object.containsValue(obj, val). * * @param {Object<K,V>} obj The object in which to look for val. * @param {V} val The object for which to check. * @return {boolean} true if val is present. * @template K,V */ goog.object.contains = function(obj, val) { return goog.object.containsValue(obj, val); }; /** * Returns the values of the object/map/hash. * * @param {Object<K,V>} obj The object from which to get the values. * @return {!Array<V>} The values in the object/map/hash. * @template K,V */ goog.object.getValues = function(obj) { var res = []; var i = 0; for (var key in obj) { res[i++] = obj[key]; } return res; }; /** * Returns the keys of the object/map/hash. * * @param {Object} obj The object from which to get the keys. * @return {!Array<string>} Array of property keys. */ goog.object.getKeys = function(obj) { var res = []; var i = 0; for (var key in obj) { res[i++] = key; } return res; }; /** * Get a value from an object multiple levels deep. This is useful for * pulling values from deeply nested objects, such as JSON responses. * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3) * * @param {!Object} obj An object to get the value from. Can be array-like. * @param {...(string|number|!IArrayLike<number|string>)} * var_args A number of keys * (as strings, or numbers, for array-like objects). Can also be * specified as a single array of keys. * @return {*} The resulting value. If, at any point, the value for a key * in the current object is null or undefined, returns undefined. */ goog.object.getValueByKeys = function(obj, var_args) { var isArrayLike = goog.isArrayLike(var_args); var keys = isArrayLike ? /** @type {!IArrayLike<number|string>} */ (var_args) : arguments; // Start with the 2nd parameter for the variable parameters syntax. for (var i = isArrayLike ? 0 : 1; i < keys.length; i++) { if (obj == null) return undefined; obj = obj[keys[i]]; } return obj; }; /** * Whether the object/map/hash contains the given key. * * @param {Object} obj The object in which to look for key. * @param {?} key The key for which to check. * @return {boolean} true If the map contains the key. */ goog.object.containsKey = function(obj, key) { return obj !== null && key in obj; }; /** * Whether the object/map/hash contains the given value. This is O(n). * * @param {Object<K,V>} obj The object in which to look for val. * @param {V} val The value for which to check. * @return {boolean} true If the map contains the value. * @template K,V */ goog.object.containsValue = function(obj, val) { for (var key in obj) { if (obj[key] == val) { return true; } } return false; }; /** * Searches an object for an element that satisfies the given condition and * returns its key. * @param {Object<K,V>} obj The object to search in. * @param {function(this:T,V,string,Object<K,V>):boolean} f The * function to call for every element. Takes 3 arguments (the value, * the key and the object) and should return a boolean. * @param {T=} opt_this An optional "this" context for the function. * @return {string|undefined} The key of an element for which the function * returns true or undefined if no such element is found. * @template T,K,V */ goog.object.findKey = function(obj, f, opt_this) { for (var key in obj) { if (f.call(/** @type {?} */ (opt_this), obj[key], key, obj)) { return key; } } return undefined; }; /** * Searches an object for an element that satisfies the given condition and * returns its value. * @param {Object<K,V>} obj The object to search in. * @param {function(this:T,V,string,Object<K,V>):boolean} f The function * to call for every element. Takes 3 arguments (the value, the key * and the object) and should return a boolean. * @param {T=} opt_this An optional "this" context for the function. * @return {V} The value of an element for which the function returns true or * undefined if no such element is found. * @template T,K,V */ goog.object.findValue = function(obj, f, opt_this) { var key = goog.object.findKey(obj, f, opt_this); return key && obj[key]; }; /** * Whether the object/map/hash is empty. * * @param {Object} obj The object to test. * @return {boolean} true if obj is empty. */ goog.object.isEmpty = function(obj) { for (var key in obj) { return false; } return true; }; /** * Removes all key value pairs from the object/map/hash. * * @param {Object} obj The object to clear. */ goog.object.clear = function(obj) { for (var i in obj) { delete obj[i]; } }; /** * Removes a key-value pair based on the key. * * @param {Object} obj The object from which to remove the key. * @param {?} key The key to remove. * @return {boolean} Whether an element was removed. */ goog.object.remove = function(obj, key) { var rv; if (rv = key in /** @type {!Object} */ (obj)) { delete obj[key]; } return rv; }; /** * Adds a key-value pair to the object. Throws an exception if the key is * already in use. Use set if you want to change an existing pair. * * @param {Object<K,V>} obj The object to which to add the key-value pair. * @param {string} key The key to add. * @param {V} val The value to add. * @template K,V */ goog.object.add = function(obj, key, val) { if (obj !== null && key in obj) { throw new Error('The object already contains the key "' + key + '"'); } goog.object.set(obj, key, val); }; /** * Returns the value for the given key. * * @param {Object<K,V>} obj The object from which to get the value. * @param {string} key The key for which to get the value. * @param {R=} opt_val The value to return if no item is found for the given * key (default is undefined). * @return {V|R|undefined} The value for the given key. * @template K,V,R */ goog.object.get = function(obj, key, opt_val) { if (obj !== null && key in obj) { return obj[key]; } return opt_val; }; /** * Adds a key-value pair to the object/map/hash. * * @param {Object<K,V>} obj The object to which to add the key-value pair. * @param {string} key The key to add. * @param {V} value The value to add. * @template K,V */ goog.object.set = function(obj, key, value) { obj[key] = value; }; /** * Adds a key-value pair to the object/map/hash if it doesn't exist yet. * * @param {Object<K,V>} obj The object to which to add the key-value pair. * @param {string} key The key to add. * @param {V} value The value to add if the key wasn't present. * @return {V} The value of the entry at the end of the function. * @template K,V */ goog.object.setIfUndefined = function(obj, key, value) { return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value); }; /** * Sets a key and value to an object if the key is not set. The value will be * the return value of the given function. If the key already exists, the * object will not be changed and the function will not be called (the function * will be lazily evaluated -- only called if necessary). * * This function is particularly useful for use with a map used a as a cache. * * @param {!Object<K,V>} obj The object to which to add the key-value pair. * @param {string} key The key to add. * @param {function():V} f The value to add if the key wasn't present. * @return {V} The value of the entry at the end of the function. * @template K,V */ goog.object.setWithReturnValueIfNotSet = function(obj, key, f) { if (key in obj) { return obj[key]; } var val = f(); obj[key] = val; return val; }; /** * Compares two objects for equality using === on the values. * * @param {!Object<K,V>} a * @param {!Object<K,V>} b * @return {boolean} * @template K,V */ goog.object.equals = function(a, b) { for (var k in a) { if (!(k in b) || a[k] !== b[k]) { return false; } } for (var k in b) { if (!(k in a)) { return false; } } return true; }; /** * Returns a shallow clone of the object. * * @param {Object<K,V>} obj Object to clone. * @return {!Object<K,V>} Clone of the input object. * @template K,V */ goog.object.clone = function(obj) { // We cannot use the prototype trick because a lot of methods depend on where // the actual key is set. var res = {}; for (var key in obj) { res[key] = obj[key]; } return res; // We could also use goog.mixin but I wanted this to be independent from that. }; /** * Clones a value. The input may be an Object, Array, or basic type. Objects and * arrays will be cloned recursively. * * WARNINGS: * <code>goog.object.unsafeClone</code> does not detect reference loops. Objects * that refer to themselves will cause infinite recursion. * * <code>goog.object.unsafeClone</code> is unaware of unique identifiers, and * copies UIDs created by <code>getUid</code> into cloned results. * * @param {T} obj The value to clone. * @return {T} A clone of the input value. * @template T */ goog.object.unsafeClone = function(obj) { var type = goog.typeOf(obj); if (type == 'object' || type == 'array') { if (goog.isFunction(obj.clone)) { return obj.clone(); } var clone = type == 'array' ? [] : {}; for (var key in obj) { clone[key] = goog.object.unsafeClone(obj[key]); } return clone; } return obj; }; /** * Returns a new object in which all the keys and values are interchanged * (keys become values and values become keys). If multiple keys map to the * same value, the chosen transposed value is implementation-dependent. * * @param {Object} obj The object to transpose. * @return {!Object} The transposed object. */ goog.object.transpose = function(obj) { var transposed = {}; for (var key in obj) { transposed[obj[key]] = key; } return transposed; }; /** * The names of the fields that are defined on Object.prototype. * @type {Array<string>} * @private */ goog.object.PROTOTYPE_FIELDS_ = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** * Extends an object with another object. * This operates 'in-place'; it does not create a new Object. * * Example: * var o = {}; * goog.object.extend(o, {a: 0, b: 1}); * o; // {a: 0, b: 1} * goog.object.extend(o, {b: 2, c: 3}); * o; // {a: 0, b: 2, c: 3} * * @param {Object} target The object to modify. Existing properties will be * overwritten if they are also present in one of the objects in * `var_args`. * @param {...Object} var_args The objects from which values will be copied. */ goog.object.extend = function(target, var_args) { var key, source; for (var i = 1; i < arguments.length; i++) { source = arguments[i]; for (key in source) { target[key] = source[key]; } // For IE the for-in-loop does not contain any properties that are not // enumerable on the prototype object (for example isPrototypeOf from // Object.prototype) and it will also not include 'replace' on objects that // extend String and change 'replace' (not that it is common for anyone to // extend anything except Object). for (var j = 0; j < goog.object.PROTOTYPE_FIELDS_.length; j++) { key = goog.object.PROTOTYPE_FIELDS_[j]; if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } }; /** * Creates a new object built from the key-value pairs provided as arguments. * @param {...*} var_args If only one argument is provided and it is an array * then this is used as the arguments, otherwise even arguments are used as * the property names and odd arguments are used as the property values. * @return {!Object} The new object. * @throws {Error} If there are uneven number of arguments or there is only one * non array argument. */ goog.object.create = function(var_args) { var argLength = arguments.length; if (argLength == 1 && goog.isArray(arguments[0])) { return goog.object.create.apply(null, arguments[0]); } if (argLength % 2) { throw new Error('Uneven number of arguments'); } var rv = {}; for (var i = 0; i < argLength; i += 2) { rv[arguments[i]] = arguments[i + 1]; } return rv; }; /** * Creates a new object where the property names come from the arguments but * the value is always set to true * @param {...*} var_args If only one argument is provided and it is an array * then this is used as the arguments, otherwise the arguments are used * as the property names. * @return {!Object} The new object. */ goog.object.createSet = function(var_args) { var argLength = arguments.length; if (argLength == 1 && goog.isArray(arguments[0])) { return goog.object.createSet.apply(null, arguments[0]); } var rv = {}; for (var i = 0; i < argLength; i++) { rv[arguments[i]] = true; } return rv; }; /** * Creates an immutable view of the underlying object, if the browser * supports immutable objects. * * In default mode, writes to this view will fail silently. In strict mode, * they will throw an error. * * @param {!Object<K,V>} obj An object. * @return {!Object<K,V>} An immutable view of that object, or the * original object if this browser does not support immutables. * @template K,V */ goog.object.createImmutableView = function(obj) { var result = obj; if (Object.isFrozen && !Object.isFrozen(obj)) { result = Object.create(obj); Object.freeze(result); } return result; }; /** * @param {!Object} obj An object. * @return {boolean} Whether this is an immutable view of the object. */ goog.object.isImmutableView = function(obj) { return !!Object.isFrozen && Object.isFrozen(obj); }; /** * Get all properties names on a given Object regardless of enumerability. * * <p> If the browser does not support `Object.getOwnPropertyNames` nor * `Object.getPrototypeOf` then this is equivalent to using * `goog.object.getKeys` * * @param {?Object} obj The object to get the properties of. * @param {boolean=} opt_includeObjectPrototype Whether properties defined on * `Object.prototype` should be included in the result. * @param {boolean=} opt_includeFunctionPrototype Whether properties defined on * `Function.prototype` should be included in the result. * @return {!Array<string>} * @public */ goog.object.getAllPropertyNames = function( obj, opt_includeObjectPrototype, opt_includeFunctionPrototype) { if (!obj) { return []; } // Naively use a for..in loop to get the property names if the browser doesn't // support any other APIs for getting it. if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) { return goog.object.getKeys(obj); } var visitedSet = {}; // Traverse the prototype chain and add all properties to the visited set. var proto = obj; while (proto && (proto !== Object.prototype || !!opt_includeObjectPrototype) && (proto !== Function.prototype || !!opt_includeFunctionPrototype)) { var names = Object.getOwnPropertyNames(proto); for (var i = 0; i < names.length; i++) { visitedSet[names[i]] = true; } proto = Object.getPrototypeOf(proto); } return goog.object.getKeys(visitedSet); }; //javascript/closure/labs/useragent/browser.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Closure user agent detection (Browser). * @see <a href="http://www.useragentstring.com/">User agent strings</a> * For more information on rendering engine, platform, or device see the other * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform, * goog.labs.userAgent.device respectively.) * * @author <EMAIL> (<NAME>) */ goog.provide('goog.labs.userAgent.browser'); goog.require('goog.array'); goog.require('goog.labs.userAgent.util'); goog.require('goog.object'); goog.require('goog.string'); // TODO(nnaze): Refactor to remove excessive exclusion logic in matching // functions. /** * @return {boolean} Whether the user's browser is Opera. Note: Chromium * based Opera (Opera 15+) is detected as Chrome to avoid unnecessary * special casing. * @private */ goog.labs.userAgent.browser.matchOpera_ = function() { return goog.labs.userAgent.util.matchUserAgent('Opera'); }; /** * @return {boolean} Whether the user's browser is IE. * @private */ goog.labs.userAgent.browser.matchIE_ = function() { return goog.labs.userAgent.util.matchUserAgent('Trident') || goog.labs.userAgent.util.matchUserAgent('MSIE'); }; /** * @return {boolean} Whether the user's browser is Edge. * @private */ goog.labs.userAgent.browser.matchEdge_ = function() { return goog.labs.userAgent.util.matchUserAgent('Edge'); }; /** * @return {boolean} Whether the user's browser is Firefox. * @private */ goog.labs.userAgent.browser.matchFirefox_ = function() { return goog.labs.userAgent.util.matchUserAgent('Firefox'); }; /** * @return {boolean} Whether the user's browser is Safari. * @private */ goog.labs.userAgent.browser.matchSafari_ = function() { return goog.labs.userAgent.util.matchUserAgent('Safari') && !(goog.labs.userAgent.browser.matchChrome_() || goog.labs.userAgent.browser.matchCoast_() || goog.labs.userAgent.browser.matchOpera_() || goog.labs.userAgent.browser.matchEdge_() || goog.labs.userAgent.browser.isSilk() || goog.labs.userAgent.util.matchUserAgent('Android')); }; /** * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based * iOS browser). * @private */ goog.labs.userAgent.browser.matchCoast_ = function() { return goog.labs.userAgent.util.matchUserAgent('Coast'); }; /** * @return {boolean} Whether the user's browser is iOS Webview. * @private */ goog.labs.userAgent.browser.matchIosWebview_ = function() { // iOS Webview does not show up as Chrome or Safari. Also check for Opera's // WebKit-based iOS browser, Coast. return (goog.labs.userAgent.util.matchUserAgent('iPad') || goog.labs.userAgent.util.matchUserAgent('iPhone')) && !goog.labs.userAgent.browser.matchSafari_() && !goog.labs.userAgent.browser.matchChrome_() && !goog.labs.userAgent.browser.matchCoast_() && goog.labs.userAgent.util.matchUserAgent('AppleWebKit'); }; /** * @return {boolean} Whether the user's browser is Chrome. * @private */ goog.labs.userAgent.browser.matchChrome_ = function() { return (goog.labs.userAgent.util.matchUserAgent('Chrome') || goog.labs.userAgent.util.matchUserAgent('CriOS')) && !goog.labs.userAgent.browser.matchEdge_(); }; /** * @return {boolean} Whether the user's browser is the Android browser. * @private */ goog.labs.userAgent.browser.matchAndroidBrowser_ = function() { // Android can appear in the user agent string for Chrome on Android. // This is not the Android standalone browser if it does. return goog.labs.userAgent.util.matchUserAgent('Android') && !(goog.labs.userAgent.browser.isChrome() || goog.labs.userAgent.browser.isFirefox() || goog.labs.userAgent.browser.isOpera() || goog.labs.userAgent.browser.isSilk()); }; /** * @return {boolean} Whether the user's browser is Opera. */ goog.labs.userAgent.browser.isOpera = goog.labs.userAgent.browser.matchOpera_; /** * @return {boolean} Whether the user's browser is IE. */ goog.labs.userAgent.browser.isIE = goog.labs.userAgent.browser.matchIE_; /** * @return {boolean} Whether the user's browser is Edge. */ goog.labs.userAgent.browser.isEdge = goog.labs.userAgent.browser.matchEdge_; /** * @return {boolean} Whether the user's browser is Firefox. */ goog.labs.userAgent.browser.isFirefox = goog.labs.userAgent.browser.matchFirefox_; /** * @return {boolean} Whether the user's browser is Safari. */ goog.labs.userAgent.browser.isSafari = goog.labs.userAgent.browser.matchSafari_; /** * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based * iOS browser). */ goog.labs.userAgent.browser.isCoast = goog.labs.userAgent.browser.matchCoast_; /** * @return {boolean} Whether the user's browser is iOS Webview. */ goog.labs.userAgent.browser.isIosWebview = goog.labs.userAgent.browser.matchIosWebview_; /** * @return {boolean} Whether the user's browser is Chrome. */ goog.labs.userAgent.browser.isChrome = goog.labs.userAgent.browser.matchChrome_; /** * @return {boolean} Whether the user's browser is the Android browser. */ goog.labs.userAgent.browser.isAndroidBrowser = goog.labs.userAgent.browser.matchAndroidBrowser_; /** * For more information, see: * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html * @return {boolean} Whether the user's browser is Silk. */ goog.labs.userAgent.browser.isSilk = function() { return goog.labs.userAgent.util.matchUserAgent('Silk'); }; /** * @return {string} The browser version or empty string if version cannot be * determined. Note that for Internet Explorer, this returns the version of * the browser, not the version of the rendering engine. (IE 8 in * compatibility mode will return 8.0 rather than 7.0. To determine the * rendering engine version, look at document.documentMode instead. See * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more * details.) */ goog.labs.userAgent.browser.getVersion = function() { var userAgentString = goog.labs.userAgent.util.getUserAgent(); // Special case IE since IE's version is inside the parenthesis and // without the '/'. if (goog.labs.userAgent.browser.isIE()) { return goog.labs.userAgent.browser.getIEVersion_(userAgentString); } var versionTuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString); // Construct a map for easy lookup. var versionMap = {}; goog.array.forEach(versionTuples, function(tuple) { // Note that the tuple is of length three, but we only care about the // first two. var key = tuple[0]; var value = tuple[1]; versionMap[key] = value; }); var versionMapHasKey = goog.partial(goog.object.containsKey, versionMap); // Gives the value with the first key it finds, otherwise empty string. function lookUpValueWithKeys(keys) { var key = goog.array.find(keys, versionMapHasKey); return versionMap[key] || ''; } // Check Opera before Chrome since Opera 15+ has "Chrome" in the string. // See // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond if (goog.labs.userAgent.browser.isOpera()) { // Opera 10 has Version/10.0 but Opera/9.8, so look for "Version" first. // Opera uses 'OPR' for more recent UAs. return lookUpValueWithKeys(['Version', 'Opera']); } // Check Edge before Chrome since it has Chrome in the string. if (goog.labs.userAgent.browser.isEdge()) { return lookUpValueWithKeys(['Edge']); } if (goog.labs.userAgent.browser.isChrome()) { return lookUpValueWithKeys(['Chrome', 'CriOS']); } // Usually products browser versions are in the third tuple after "Mozilla" // and the engine. var tuple = versionTuples[2]; return tuple && tuple[1] || ''; }; /** * @param {string|number} version The version to check. * @return {boolean} Whether the browser version is higher or the same as the * given version. */ goog.labs.userAgent.browser.isVersionOrHigher = function(version) { return goog.string.compareVersions( goog.labs.userAgent.browser.getVersion(), version) >= 0; }; /** * Determines IE version. More information: * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx * * @param {string} userAgent the User-Agent. * @return {string} * @private */ goog.labs.userAgent.browser.getIEVersion_ = function(userAgent) { // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade // bug. Example UA: // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) // like Gecko. // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments. var rv = /rv: *([\d\.]*)/.exec(userAgent); if (rv && rv[1]) { return rv[1]; } var version = ''; var msie = /MSIE +([\d\.]+)/.exec(userAgent); if (msie && msie[1]) { // IE in compatibility mode usually identifies itself as MSIE 7.0; in this // case, use the Trident version to determine the version of IE. For more // details, see the links above. var tridentVersion = /Trident\/(\d.\d)/.exec(userAgent); if (msie[1] == '7.0') { if (tridentVersion && tridentVersion[1]) { switch (tridentVersion[1]) { case '4.0': version = '8.0'; break; case '5.0': version = '9.0'; break; case '6.0': version = '10.0'; break; case '7.0': version = '11.0'; break; } } else { version = '7.0'; } } else { version = msie[1]; } } return version; }; //javascript/closure/labs/useragent/engine.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Closure user agent detection. * @see http://en.wikipedia.org/wiki/User_agent * For more information on browser brand, platform, or device see the other * sub-namespaces in goog.labs.userAgent (browser, platform, and device). * */ goog.provide('goog.labs.userAgent.engine'); goog.require('goog.array'); goog.require('goog.labs.userAgent.util'); goog.require('goog.string'); /** * @return {boolean} Whether the rendering engine is Presto. */ goog.labs.userAgent.engine.isPresto = function() { return goog.labs.userAgent.util.matchUserAgent('Presto'); }; /** * @return {boolean} Whether the rendering engine is Trident. */ goog.labs.userAgent.engine.isTrident = function() { // IE only started including the Trident token in IE8. return goog.labs.userAgent.util.matchUserAgent('Trident') || goog.labs.userAgent.util.matchUserAgent('MSIE'); }; /** * @return {boolean} Whether the rendering engine is Edge. */ goog.labs.userAgent.engine.isEdge = function() { return goog.labs.userAgent.util.matchUserAgent('Edge'); }; /** * @return {boolean} Whether the rendering engine is WebKit. */ goog.labs.userAgent.engine.isWebKit = function() { return goog.labs.userAgent.util.matchUserAgentIgnoreCase('WebKit') && !goog.labs.userAgent.engine.isEdge(); }; /** * @return {boolean} Whether the rendering engine is Gecko. */ goog.labs.userAgent.engine.isGecko = function() { return goog.labs.userAgent.util.matchUserAgent('Gecko') && !goog.labs.userAgent.engine.isWebKit() && !goog.labs.userAgent.engine.isTrident() && !goog.labs.userAgent.engine.isEdge(); }; /** * @return {string} The rendering engine's version or empty string if version * can't be determined. */ goog.labs.userAgent.engine.getVersion = function() { var userAgentString = goog.labs.userAgent.util.getUserAgent(); if (userAgentString) { var tuples = goog.labs.userAgent.util.extractVersionTuples(userAgentString); var engineTuple = goog.labs.userAgent.engine.getEngineTuple_(tuples); if (engineTuple) { // In Gecko, the version string is either in the browser info or the // Firefox version. See Gecko user agent string reference: // http://goo.gl/mULqa if (engineTuple[0] == 'Gecko') { return goog.labs.userAgent.engine.getVersionForKey_(tuples, 'Firefox'); } return engineTuple[1]; } // MSIE has only one version identifier, and the Trident version is // specified in the parenthetical. IE Edge is covered in the engine tuple // detection. var browserTuple = tuples[0]; var info; if (browserTuple && (info = browserTuple[2])) { var match = /Trident\/([^\s;]+)/.exec(info); if (match) { return match[1]; } } } return ''; }; /** * @param {!Array<!Array<string>>} tuples Extracted version tuples. * @return {!Array<string>|undefined} The engine tuple or undefined if not * found. * @private */ goog.labs.userAgent.engine.getEngineTuple_ = function(tuples) { if (!goog.labs.userAgent.engine.isEdge()) { return tuples[1]; } for (var i = 0; i < tuples.length; i++) { var tuple = tuples[i]; if (tuple[0] == 'Edge') { return tuple; } } }; /** * @param {string|number} version The version to check. * @return {boolean} Whether the rendering engine version is higher or the same * as the given version. */ goog.labs.userAgent.engine.isVersionOrHigher = function(version) { return goog.string.compareVersions( goog.labs.userAgent.engine.getVersion(), version) >= 0; }; /** * @param {!Array<!Array<string>>} tuples Version tuples. * @param {string} key The key to look for. * @return {string} The version string of the given key, if present. * Otherwise, the empty string. * @private */ goog.labs.userAgent.engine.getVersionForKey_ = function(tuples, key) { // TODO(nnaze): Move to util if useful elsewhere. var pair = goog.array.find(tuples, function(pair) { return key == pair[0]; }); return pair && pair[1] || ''; }; //javascript/closure/labs/useragent/platform.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Closure user agent platform detection. * @see <a href="http://www.useragentstring.com/">User agent strings</a> * For more information on browser brand, rendering engine, or device see the * other sub-namespaces in goog.labs.userAgent (browser, engine, and device * respectively). * */ goog.provide('goog.labs.userAgent.platform'); goog.require('goog.labs.userAgent.util'); goog.require('goog.string'); /** * @return {boolean} Whether the platform is Android. */ goog.labs.userAgent.platform.isAndroid = function() { return goog.labs.userAgent.util.matchUserAgent('Android'); }; /** * @return {boolean} Whether the platform is iPod. */ goog.labs.userAgent.platform.isIpod = function() { return goog.labs.userAgent.util.matchUserAgent('iPod'); }; /** * @return {boolean} Whether the platform is iPhone. */ goog.labs.userAgent.platform.isIphone = function() { return goog.labs.userAgent.util.matchUserAgent('iPhone') && !goog.labs.userAgent.util.matchUserAgent('iPod') && !goog.labs.userAgent.util.matchUserAgent('iPad'); }; /** * @return {boolean} Whether the platform is iPad. */ goog.labs.userAgent.platform.isIpad = function() { return goog.labs.userAgent.util.matchUserAgent('iPad'); }; /** * @return {boolean} Whether the platform is iOS. */ goog.labs.userAgent.platform.isIos = function() { return goog.labs.userAgent.platform.isIphone() || goog.labs.userAgent.platform.isIpad() || goog.labs.userAgent.platform.isIpod(); }; /** * @return {boolean} Whether the platform is Mac. */ goog.labs.userAgent.platform.isMacintosh = function() { return goog.labs.userAgent.util.matchUserAgent('Macintosh'); }; /** * Note: ChromeOS is not considered to be Linux as it does not report itself * as Linux in the user agent string. * @return {boolean} Whether the platform is Linux. */ goog.labs.userAgent.platform.isLinux = function() { return goog.labs.userAgent.util.matchUserAgent('Linux'); }; /** * @return {boolean} Whether the platform is Windows. */ goog.labs.userAgent.platform.isWindows = function() { return goog.labs.userAgent.util.matchUserAgent('Windows'); }; /** * @return {boolean} Whether the platform is ChromeOS. */ goog.labs.userAgent.platform.isChromeOS = function() { return goog.labs.userAgent.util.matchUserAgent('CrOS'); }; /** * @return {boolean} Whether the platform is Chromecast. */ goog.labs.userAgent.platform.isChromecast = function() { return goog.labs.userAgent.util.matchUserAgent('CrKey'); }; /** * The version of the platform. We only determine the version for Windows, * Mac, and Chrome OS. It doesn't make much sense on Linux. For Windows, we only * look at the NT version. Non-NT-based versions (e.g. 95, 98, etc.) are given * version 0.0. * * @return {string} The platform version or empty string if version cannot be * determined. */ goog.labs.userAgent.platform.getVersion = function() { var userAgentString = goog.labs.userAgent.util.getUserAgent(); var version = '', re; if (goog.labs.userAgent.platform.isWindows()) { re = /Windows (?:NT|Phone) ([0-9.]+)/; var match = re.exec(userAgentString); if (match) { version = match[1]; } else { version = '0.0'; } } else if (goog.labs.userAgent.platform.isIos()) { re = /(?:iPhone|iPod|iPad|CPU)\s+OS\s+(\S+)/; var match = re.exec(userAgentString); // Report the version as x.y.z and not x_y_z version = match && match[1].replace(/_/g, '.'); } else if (goog.labs.userAgent.platform.isMacintosh()) { re = /Mac OS X ([0-9_.]+)/; var match = re.exec(userAgentString); // Note: some old versions of Camino do not report an OSX version. // Default to 10. version = match ? match[1].replace(/_/g, '.') : '10'; } else if (goog.labs.userAgent.platform.isAndroid()) { re = /Android\s+([^\);]+)(\)|;)/; var match = re.exec(userAgentString); version = match && match[1]; } else if (goog.labs.userAgent.platform.isChromeOS()) { re = /(?:CrOS\s+(?:i686|x86_64)\s+([0-9.]+))/; var match = re.exec(userAgentString); version = match && match[1]; } return version || ''; }; /** * @param {string|number} version The version to check. * @return {boolean} Whether the browser version is higher or the same as the * given version. */ goog.labs.userAgent.platform.isVersionOrHigher = function(version) { return goog.string.compareVersions( goog.labs.userAgent.platform.getVersion(), version) >= 0; }; //javascript/closure/reflect/reflect.js // Copyright 2009 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Useful compiler idioms. * * @author <EMAIL> (<NAME>) */ goog.provide('goog.reflect'); /** * Syntax for object literal casts. * @see http://go/jscompiler-renaming * @see https://goo.gl/CRs09P * * Use this if you have an object literal whose keys need to have the same names * as the properties of some class even after they are renamed by the compiler. * * @param {!Function} type Type to cast to. * @param {Object} object Object literal to cast. * @return {Object} The object literal. */ goog.reflect.object = function(type, object) { return object; }; /** * Syntax for renaming property strings. * @see http://go/jscompiler-renaming * @see https://goo.gl/CRs09P * * Use this if you have an need to access a property as a string, but want * to also have the property renamed by the compiler. In contrast to * goog.reflect.object, this method takes an instance of an object. * * Properties must be simple names (not qualified names). * * @param {string} prop Name of the property * @param {!Object} object Instance of the object whose type will be used * for renaming * @return {string} The renamed property. */ goog.reflect.objectProperty = function(prop, object) { return prop; }; /** * To assert to the compiler that an operation is needed when it would * otherwise be stripped. For example: * <code> * // Force a layout * goog.reflect.sinkValue(dialog.offsetHeight); * </code> * @param {T} x * @return {T} * @template T */ goog.reflect.sinkValue = function(x) { goog.reflect.sinkValue[' '](x); return x; }; /** * The compiler should optimize this function away iff no one ever uses * goog.reflect.sinkValue. */ goog.reflect.sinkValue[' '] = goog.nullFunction; /** * Check if a property can be accessed without throwing an exception. * @param {Object} obj The owner of the property. * @param {string} prop The property name. * @return {boolean} Whether the property is accessible. Will also return true * if obj is null. */ goog.reflect.canAccessProperty = function(obj, prop) { try { goog.reflect.sinkValue(obj[prop]); return true; } catch (e) { } return false; }; /** * Retrieves a value from a cache given a key. The compiler provides special * consideration for this call such that it is generally considered side-effect * free. However, if the `opt_keyFn` or `valueFn` have side-effects * then the entire call is considered to have side-effects. * * Conventionally storing the value on the cache would be considered a * side-effect and preclude unused calls from being pruned, ie. even if * the value was never used, it would still always be stored in the cache. * * Providing a side-effect free `valueFn` and `opt_keyFn` * allows unused calls to `goog.reflect.cache` to be pruned. * * @param {!Object<K, V>} cacheObj The object that contains the cached values. * @param {?} key The key to lookup in the cache. If it is not string or number * then a `opt_keyFn` should be provided. The key is also used as the * parameter to the `valueFn`. * @param {function(?):V} valueFn The value provider to use to calculate the * value to store in the cache. This function should be side-effect free * to take advantage of the optimization. * @param {function(?):K=} opt_keyFn The key provider to determine the cache * map key. This should be used if the given key is not a string or number. * If not provided then the given key is used. This function should be * side-effect free to take advantage of the optimization. * @return {V} The cached or calculated value. * @template K * @template V */ goog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) { var storedKey = opt_keyFn ? opt_keyFn(key) : key; if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) { return cacheObj[storedKey]; } return (cacheObj[storedKey] = valueFn(key)); }; //javascript/closure/useragent/useragent.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Rendering engine detection. * @see <a href="http://www.useragentstring.com/">User agent strings</a> * For information on the browser brand (such as Safari versus Chrome), see * goog.userAgent.product. * @author <EMAIL> (<NAME>) * @see ../demos/useragent.html */ goog.provide('goog.userAgent'); goog.require('goog.labs.userAgent.browser'); goog.require('goog.labs.userAgent.engine'); goog.require('goog.labs.userAgent.platform'); goog.require('goog.labs.userAgent.util'); goog.require('goog.reflect'); goog.require('goog.string'); /** * @define {boolean} Whether we know at compile-time that the browser is IE. */ goog.define('goog.userAgent.ASSUME_IE', false); /** * @define {boolean} Whether we know at compile-time that the browser is EDGE. */ goog.define('goog.userAgent.ASSUME_EDGE', false); /** * @define {boolean} Whether we know at compile-time that the browser is GECKO. */ goog.define('goog.userAgent.ASSUME_GECKO', false); /** * @define {boolean} Whether we know at compile-time that the browser is WEBKIT. */ goog.define('goog.userAgent.ASSUME_WEBKIT', false); /** * @define {boolean} Whether we know at compile-time that the browser is a * mobile device running WebKit e.g. iPhone or Android. */ goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false); /** * @define {boolean} Whether we know at compile-time that the browser is OPERA. */ goog.define('goog.userAgent.ASSUME_OPERA', false); /** * @define {boolean} Whether the * `goog.userAgent.isVersionOrHigher` * function will return true for any version. */ goog.define('goog.userAgent.ASSUME_ANY_VERSION', false); /** * Whether we know the browser engine at compile-time. * @type {boolean} * @private */ goog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE || goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO || goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_OPERA; /** * Returns the userAgent string for the current browser. * * @return {string} The userAgent string. */ goog.userAgent.getUserAgentString = function() { return goog.labs.userAgent.util.getUserAgent(); }; /** * @return {?Navigator} The native navigator object. */ goog.userAgent.getNavigatorTyped = function() { // Need a local navigator reference instead of using the global one, // to avoid the rare case where they reference different objects. // (in a WorkerPool, for example). return goog.global['navigator'] || null; }; /** * TODO(nnaze): Change type to "Navigator" and update compilation targets. * @return {?Object} The native navigator object. */ goog.userAgent.getNavigator = function() { return goog.userAgent.getNavigatorTyped(); }; /** * Whether the user agent is Opera. * @type {boolean} */ goog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_OPERA : goog.labs.userAgent.browser.isOpera(); /** * Whether the user agent is Internet Explorer. * @type {boolean} */ goog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_IE : goog.labs.userAgent.browser.isIE(); /** * Whether the user agent is Microsoft Edge. * @type {boolean} */ goog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_EDGE : goog.labs.userAgent.engine.isEdge(); /** * Whether the user agent is MS Internet Explorer or MS Edge. * @type {boolean} */ goog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE; /** * Whether the user agent is Gecko. Gecko is the rendering engine used by * Mozilla, Firefox, and others. * @type {boolean} */ goog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_GECKO : goog.labs.userAgent.engine.isGecko(); /** * Whether the user agent is WebKit. WebKit is the rendering engine that * Safari, Android and others use. * @type {boolean} */ goog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ? goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT : goog.labs.userAgent.engine.isWebKit(); /** * Whether the user agent is running on a mobile device. * * This is a separate function so that the logic can be tested. * * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile(). * * @return {boolean} Whether the user agent is running on a mobile device. * @private */ goog.userAgent.isMobile_ = function() { return goog.userAgent.WEBKIT && goog.labs.userAgent.util.matchUserAgent('Mobile'); }; /** * Whether the user agent is running on a mobile device. * * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent * is promoted as the gecko/webkit logic is likely inaccurate. * * @type {boolean} */ goog.userAgent.MOBILE = goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_(); /** * Used while transitioning code to use WEBKIT instead. * @type {boolean} * @deprecated Use {@link goog.userAgent.product.SAFARI} instead. * TODO(nicksantos): Delete this from goog.userAgent. */ goog.userAgent.SAFARI = goog.userAgent.WEBKIT; /** * @return {string} the platform (operating system) the user agent is running * on. Default to empty string because navigator.platform may not be defined * (on Rhino, for example). * @private */ goog.userAgent.determinePlatform_ = function() { var navigator = goog.userAgent.getNavigatorTyped(); return navigator && navigator.platform || ''; }; /** * The platform (operating system) the user agent is running on. Default to * empty string because navigator.platform may not be defined (on Rhino, for * example). * @type {string} */ goog.userAgent.PLATFORM = goog.userAgent.determinePlatform_(); /** * @define {boolean} Whether the user agent is running on a Macintosh operating * system. */ goog.define('goog.userAgent.ASSUME_MAC', false); /** * @define {boolean} Whether the user agent is running on a Windows operating * system. */ goog.define('goog.userAgent.ASSUME_WINDOWS', false); /** * @define {boolean} Whether the user agent is running on a Linux operating * system. */ goog.define('goog.userAgent.ASSUME_LINUX', false); /** * @define {boolean} Whether the user agent is running on a X11 windowing * system. */ goog.define('goog.userAgent.ASSUME_X11', false); /** * @define {boolean} Whether the user agent is running on Android. */ goog.define('goog.userAgent.ASSUME_ANDROID', false); /** * @define {boolean} Whether the user agent is running on an iPhone. */ goog.define('goog.userAgent.ASSUME_IPHONE', false); /** * @define {boolean} Whether the user agent is running on an iPad. */ goog.define('goog.userAgent.ASSUME_IPAD', false); /** * @define {boolean} Whether the user agent is running on an iPod. */ goog.define('goog.userAgent.ASSUME_IPOD', false); /** * @type {boolean} * @private */ goog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC || goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX || goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID || goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD || goog.userAgent.ASSUME_IPOD; /** * Whether the user agent is running on a Macintosh operating system. * @type {boolean} */ goog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_MAC : goog.labs.userAgent.platform.isMacintosh(); /** * Whether the user agent is running on a Windows operating system. * @type {boolean} */ goog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_WINDOWS : goog.labs.userAgent.platform.isWindows(); /** * Whether the user agent is Linux per the legacy behavior of * goog.userAgent.LINUX, which considered ChromeOS to also be * Linux. * @return {boolean} * @private */ goog.userAgent.isLegacyLinux_ = function() { return goog.labs.userAgent.platform.isLinux() || goog.labs.userAgent.platform.isChromeOS(); }; /** * Whether the user agent is running on a Linux operating system. * * Note that goog.userAgent.LINUX considers ChromeOS to be Linux, * while goog.labs.userAgent.platform considers ChromeOS and * Linux to be different OSes. * * @type {boolean} */ goog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_LINUX : goog.userAgent.isLegacyLinux_(); /** * @return {boolean} Whether the user agent is an X11 windowing system. * @private */ goog.userAgent.isX11_ = function() { var navigator = goog.userAgent.getNavigatorTyped(); return !!navigator && goog.string.contains(navigator['appVersion'] || '', 'X11'); }; /** * Whether the user agent is running on a X11 windowing system. * @type {boolean} */ goog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_X11 : goog.userAgent.isX11_(); /** * Whether the user agent is running on Android. * @type {boolean} */ goog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_ANDROID : goog.labs.userAgent.platform.isAndroid(); /** * Whether the user agent is running on an iPhone. * @type {boolean} */ goog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPHONE : goog.labs.userAgent.platform.isIphone(); /** * Whether the user agent is running on an iPad. * @type {boolean} */ goog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPAD : goog.labs.userAgent.platform.isIpad(); /** * Whether the user agent is running on an iPod. * @type {boolean} */ goog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ? goog.userAgent.ASSUME_IPOD : goog.labs.userAgent.platform.isIpod(); /** * Whether the user agent is running on iOS. * @type {boolean} */ goog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ? (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD || goog.userAgent.ASSUME_IPOD) : goog.labs.userAgent.platform.isIos(); /** * @return {string} The string that describes the version number of the user * agent. * @private */ goog.userAgent.determineVersion_ = function() { // All browsers have different ways to detect the version and they all have // different naming schemes. // version is a string rather than a number because it may contain 'b', 'a', // and so on. var version = ''; var arr = goog.userAgent.getVersionRegexResult_(); if (arr) { version = arr ? arr[1] : ''; } if (goog.userAgent.IE) { // IE9 can be in document mode 9 but be reporting an inconsistent user agent // version. If it is identifying as a version lower than 9 we take the // documentMode as the version instead. IE8 has similar behavior. // It is recommended to set the X-UA-Compatible header to ensure that IE9 // uses documentMode 9. var docMode = goog.userAgent.getDocumentMode_(); if (docMode != null && docMode > parseFloat(version)) { return String(docMode); } } return version; }; /** * @return {?Array|undefined} The version regex matches from parsing the user * agent string. These regex statements must be executed inline so they can * be compiled out by the closure compiler with the rest of the useragent * detection logic when ASSUME_* is specified. * @private */ goog.userAgent.getVersionRegexResult_ = function() { var userAgent = goog.userAgent.getUserAgentString(); if (goog.userAgent.GECKO) { return /rv\:([^\);]+)(\)|;)/.exec(userAgent); } if (goog.userAgent.EDGE) { return /Edge\/([\d\.]+)/.exec(userAgent); } if (goog.userAgent.IE) { return /\b(?:MSIE|rv)[: ]([^\);]+)(\)|;)/.exec(userAgent); } if (goog.userAgent.WEBKIT) { // WebKit/125.4 return /WebKit\/(\S+)/.exec(userAgent); } if (goog.userAgent.OPERA) { // If none of the above browsers were detected but the browser is Opera, the // only string that is of interest is 'Version/<number>'. return /(?:Version)[ \/]?(\S+)/.exec(userAgent); } return undefined; }; /** * @return {number|undefined} Returns the document mode (for testing). * @private */ goog.userAgent.getDocumentMode_ = function() { // NOTE(user): goog.userAgent may be used in context where there is no DOM. var doc = goog.global['document']; return doc ? doc['documentMode'] : undefined; }; /** * The version of the user agent. This is a string because it might contain * 'b' (as in beta) as well as multiple dots. * @type {string} */ goog.userAgent.VERSION = goog.userAgent.determineVersion_(); /** * Compares two version numbers. * * @param {string} v1 Version of first item. * @param {string} v2 Version of second item. * * @return {number} 1 if first argument is higher * 0 if arguments are equal * -1 if second argument is higher. * @deprecated Use goog.string.compareVersions. */ goog.userAgent.compare = function(v1, v2) { return goog.string.compareVersions(v1, v2); }; /** * Cache for {@link goog.userAgent.isVersionOrHigher}. * Calls to compareVersions are surprisingly expensive and, as a browser's * version number is unlikely to change during a session, we cache the results. * @const * @private */ goog.userAgent.isVersionOrHigherCache_ = {}; /** * Whether the user agent version is higher or the same as the given version. * NOTE: When checking the version numbers for Firefox and Safari, be sure to * use the engine's version, not the browser's version number. For example, * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11. * Opera and Internet Explorer versions match the product release number.<br> * @see <a href="http://en.wikipedia.org/wiki/Safari_version_history"> * Webkit</a> * @see <a href="http://en.wikipedia.org/wiki/Gecko_engine">Gecko</a> * * @param {string|number} version The version to check. * @return {boolean} Whether the user agent version is higher or the same as * the given version. */ goog.userAgent.isVersionOrHigher = function(version) { return goog.userAgent.ASSUME_ANY_VERSION || goog.reflect.cache( goog.userAgent.isVersionOrHigherCache_, version, function() { return goog.string.compareVersions( goog.userAgent.VERSION, version) >= 0; }); }; /** * Deprecated alias to `goog.userAgent.isVersionOrHigher`. * @param {string|number} version The version to check. * @return {boolean} Whether the user agent version is higher or the same as * the given version. * @deprecated Use goog.userAgent.isVersionOrHigher(). */ goog.userAgent.isVersion = goog.userAgent.isVersionOrHigher; /** * Whether the IE effective document mode is higher or the same as the given * document mode version. * NOTE: Only for IE, return false for another browser. * * @param {number} documentMode The document mode version to check. * @return {boolean} Whether the IE effective document mode is higher or the * same as the given version. */ goog.userAgent.isDocumentModeOrHigher = function(documentMode) { return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode; }; /** * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`. * @param {number} version The version to check. * @return {boolean} Whether the IE effective document mode is higher or the * same as the given version. * @deprecated Use goog.userAgent.isDocumentModeOrHigher(). */ goog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher; /** * For IE version < 7, documentMode is undefined, so attempt to use the * CSS1Compat property to see if we are in standards mode. If we are in * standards mode, treat the browser version as the document mode. Otherwise, * IE is emulating version 5. * @type {number|undefined} * @const */ goog.userAgent.DOCUMENT_MODE = (function() { var doc = goog.global['document']; var mode = goog.userAgent.getDocumentMode_(); if (!doc || !goog.userAgent.IE) { return undefined; } return mode || (doc['compatMode'] == 'CSS1Compat' ? parseInt(goog.userAgent.VERSION, 10) : 5); })(); //javascript/closure/debug/debug.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Logging and debugging utilities. * * @see ../demos/debug.html */ goog.provide('goog.debug'); goog.require('goog.array'); goog.require('goog.debug.errorcontext'); goog.require('goog.userAgent'); /** @define {boolean} Whether logging should be enabled. */ goog.define('goog.debug.LOGGING_ENABLED', goog.DEBUG); /** @define {boolean} Whether to force "sloppy" stack building. */ goog.define('goog.debug.FORCE_SLOPPY_STACKS', false); /** * Catches onerror events fired by windows and similar objects. * @param {function(Object)} logFunc The function to call with the error * information. * @param {boolean=} opt_cancel Whether to stop the error from reaching the * browser. * @param {Object=} opt_target Object that fires onerror events. * @suppress {strictMissingProperties} onerror is not defined as a property * on Object. */ goog.debug.catchErrors = function(logFunc, opt_cancel, opt_target) { var target = opt_target || goog.global; var oldErrorHandler = target.onerror; var retVal = !!opt_cancel; // Chrome interprets onerror return value backwards (http://crbug.com/92062) // until it was fixed in webkit revision r94061 (Webkit 535.3). This // workaround still needs to be skipped in Safari after the webkit change // gets pushed out in Safari. // See https://bugs.webkit.org/show_bug.cgi?id=67119 if (goog.userAgent.WEBKIT && !goog.userAgent.isVersionOrHigher('535.3')) { retVal = !retVal; } /** * New onerror handler for this target. This onerror handler follows the spec * according to * http://www.whatwg.org/specs/web-apps/current-work/#runtime-script-errors * The spec was changed in August 2013 to support receiving column information * and an error object for all scripts on the same origin or cross origin * scripts with the proper headers. See * https://mikewest.org/2013/08/debugging-runtime-errors-with-window-onerror * * @param {string} message The error message. For cross-origin errors, this * will be scrubbed to just "Script error.". For new browsers that have * updated to follow the latest spec, errors that come from origins that * have proper cross origin headers will not be scrubbed. * @param {string} url The URL of the script that caused the error. The URL * will be scrubbed to "" for cross origin scripts unless the script has * proper cross origin headers and the browser has updated to the latest * spec. * @param {number} line The line number in the script that the error * occurred on. * @param {number=} opt_col The optional column number that the error * occurred on. Only browsers that have updated to the latest spec will * include this. * @param {Error=} opt_error The optional actual error object for this * error that should include the stack. Only browsers that have updated * to the latest spec will inlude this parameter. * @return {boolean} Whether to prevent the error from reaching the browser. */ target.onerror = function(message, url, line, opt_col, opt_error) { if (oldErrorHandler) { oldErrorHandler(message, url, line, opt_col, opt_error); } logFunc({ message: message, fileName: url, line: line, lineNumber: line, col: opt_col, error: opt_error }); return retVal; }; }; /** * Creates a string representing an object and all its properties. * @param {Object|null|undefined} obj Object to expose. * @param {boolean=} opt_showFn Show the functions as well as the properties, * default is false. * @return {string} The string representation of `obj`. */ goog.debug.expose = function(obj, opt_showFn) { if (typeof obj == 'undefined') { return 'undefined'; } if (obj == null) { return 'NULL'; } var str = []; for (var x in obj) { if (!opt_showFn && goog.isFunction(obj[x])) { continue; } var s = x + ' = '; try { s += obj[x]; } catch (e) { s += '*** ' + e + ' ***'; } str.push(s); } return str.join('\n'); }; /** * Creates a string representing a given primitive or object, and for an * object, all its properties and nested objects. NOTE: The output will include * Uids on all objects that were exposed. Any added Uids will be removed before * returning. * @param {*} obj Object to expose. * @param {boolean=} opt_showFn Also show properties that are functions (by * default, functions are omitted). * @return {string} A string representation of `obj`. */ goog.debug.deepExpose = function(obj, opt_showFn) { var str = []; // Track any objects where deepExpose added a Uid, so they can be cleaned up // before return. We do this globally, rather than only on ancestors so that // if the same object appears in the output, you can see it. var uidsToCleanup = []; var ancestorUids = {}; var helper = function(obj, space) { var nestspace = space + ' '; var indentMultiline = function(str) { return str.replace(/\n/g, '\n' + space); }; try { if (!goog.isDef(obj)) { str.push('undefined'); } else if (goog.isNull(obj)) { str.push('NULL'); } else if (goog.isString(obj)) { str.push('"' + indentMultiline(obj) + '"'); } else if (goog.isFunction(obj)) { str.push(indentMultiline(String(obj))); } else if (goog.isObject(obj)) { // Add a Uid if needed. The struct calls implicitly adds them. if (!goog.hasUid(obj)) { uidsToCleanup.push(obj); } var uid = goog.getUid(obj); if (ancestorUids[uid]) { str.push('*** reference loop detected (id=' + uid + ') ***'); } else { ancestorUids[uid] = true; str.push('{'); for (var x in obj) { if (!opt_showFn && goog.isFunction(obj[x])) { continue; } str.push('\n'); str.push(nestspace); str.push(x + ' = '); helper(obj[x], nestspace); } str.push('\n' + space + '}'); delete ancestorUids[uid]; } } else { str.push(obj); } } catch (e) { str.push('*** ' + e + ' ***'); } }; helper(obj, ''); // Cleanup any Uids that were added by the deepExpose. for (var i = 0; i < uidsToCleanup.length; i++) { goog.removeUid(uidsToCleanup[i]); } return str.join(''); }; /** * Recursively outputs a nested array as a string. * @param {Array<?>} arr The array. * @return {string} String representing nested array. */ goog.debug.exposeArray = function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (goog.isArray(arr[i])) { str.push(goog.debug.exposeArray(arr[i])); } else { str.push(arr[i]); } } return '[ ' + str.join(', ') + ' ]'; }; /** * Normalizes the error/exception object between browsers. * @param {*} err Raw error object. * @return {!{ * message: (?|undefined), * name: (?|undefined), * lineNumber: (?|undefined), * fileName: (?|undefined), * stack: (?|undefined) * }} Normalized error object. * @suppress {strictMissingProperties} properties not defined on err */ goog.debug.normalizeErrorObject = function(err) { var href = goog.getObjectByName('window.location.href'); if (goog.isString(err)) { return { 'message': err, 'name': 'Unknown error', 'lineNumber': 'Not available', 'fileName': href, 'stack': 'Not available' }; } var lineNumber, fileName; var threwError = false; try { lineNumber = err.lineNumber || err.line || 'Not available'; } catch (e) { // Firefox 2 sometimes throws an error when accessing 'lineNumber': // Message: Permission denied to get property UnnamedClass.lineNumber lineNumber = 'Not available'; threwError = true; } try { fileName = err.fileName || err.filename || err.sourceURL || // $googDebugFname may be set before a call to eval to set the filename // that the eval is supposed to present. goog.global['$googDebugFname'] || href; } catch (e) { // Firefox 2 may also throw an error when accessing 'filename'. fileName = 'Not available'; threwError = true; } // The IE Error object contains only the name and the message. // The Safari Error object uses the line and sourceURL fields. if (threwError || !err.lineNumber || !err.fileName || !err.stack || !err.message || !err.name) { return { 'message': err.message || 'Not available', 'name': err.name || 'UnknownError', 'lineNumber': lineNumber, 'fileName': fileName, 'stack': err.stack || 'Not available' }; } // Standards error object // Typed !Object. Should be a subtype of the return type, but it's not. return /** @type {?} */ (err); }; /** * Converts an object to an Error using the object's toString if it's not * already an Error, adds a stacktrace if there isn't one, and optionally adds * an extra message. * @param {*} err The original thrown error, object, or string. * @param {string=} opt_message optional additional message to add to the * error. * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise, * it is converted to an Error which is enhanced and returned. */ goog.debug.enhanceError = function(err, opt_message) { var error; if (!(err instanceof Error)) { error = Error(err); if (Error.captureStackTrace) { // Trim this function off the call stack, if we can. Error.captureStackTrace(error, goog.debug.enhanceError); } } else { error = err; } if (!error.stack) { error.stack = goog.debug.getStacktrace(goog.debug.enhanceError); } if (opt_message) { // find the first unoccupied 'messageX' property var x = 0; while (error['message' + x]) { ++x; } error['message' + x] = String(opt_message); } return error; }; /** * Converts an object to an Error using the object's toString if it's not * already an Error, adds a stacktrace if there isn't one, and optionally adds * context to the Error, which is reported by the closure error reporter. * @param {*} err The original thrown error, object, or string. * @param {!Object<string, string>=} opt_context Key-value context to add to the * Error. * @return {!Error} If err is an Error, it is enhanced and returned. Otherwise, * it is converted to an Error which is enhanced and returned. */ goog.debug.enhanceErrorWithContext = function(err, opt_context) { var error = goog.debug.enhanceError(err); if (opt_context) { for (var key in opt_context) { goog.debug.errorcontext.addErrorContext(error, key, opt_context[key]); } } return error; }; /** * Gets the current stack trace. Simple and iterative - doesn't worry about * catching circular references or getting the args. * @param {number=} opt_depth Optional maximum depth to trace back to. * @return {string} A string with the function names of all functions in the * stack, separated by \n. * @suppress {es5Strict} */ goog.debug.getStacktraceSimple = function(opt_depth) { if (!goog.debug.FORCE_SLOPPY_STACKS) { var stack = goog.debug.getNativeStackTrace_(goog.debug.getStacktraceSimple); if (stack) { return stack; } // NOTE: browsers that have strict mode support also have native "stack" // properties. Fall-through for legacy browser support. } var sb = []; var fn = arguments.callee.caller; var depth = 0; while (fn && (!opt_depth || depth < opt_depth)) { sb.push(goog.debug.getFunctionName(fn)); sb.push('()\n'); try { fn = fn.caller; } catch (e) { sb.push('[exception trying to get caller]\n'); break; } depth++; if (depth >= goog.debug.MAX_STACK_DEPTH) { sb.push('[...long stack...]'); break; } } if (opt_depth && depth >= opt_depth) { sb.push('[...reached max depth limit...]'); } else { sb.push('[end]'); } return sb.join(''); }; /** * Max length of stack to try and output * @type {number} */ goog.debug.MAX_STACK_DEPTH = 50; /** * @param {Function} fn The function to start getting the trace from. * @return {?string} * @private */ goog.debug.getNativeStackTrace_ = function(fn) { var tempErr = new Error(); if (Error.captureStackTrace) { Error.captureStackTrace(tempErr, fn); return String(tempErr.stack); } else { // IE10, only adds stack traces when an exception is thrown. try { throw tempErr; } catch (e) { tempErr = e; } var stack = tempErr.stack; if (stack) { return String(stack); } } return null; }; /** * Gets the current stack trace, either starting from the caller or starting * from a specified function that's currently on the call stack. * @param {?Function=} fn If provided, when collecting the stack trace all * frames above the topmost call to this function, including that call, * will be left out of the stack trace. * @return {string} Stack trace. * @suppress {es5Strict} */ goog.debug.getStacktrace = function(fn) { var stack; if (!goog.debug.FORCE_SLOPPY_STACKS) { // Try to get the stack trace from the environment if it is available. var contextFn = fn || goog.debug.getStacktrace; stack = goog.debug.getNativeStackTrace_(contextFn); } if (!stack) { // NOTE: browsers that have strict mode support also have native "stack" // properties. This function will throw in strict mode. stack = goog.debug.getStacktraceHelper_(fn || arguments.callee.caller, []); } return stack; }; /** * Private helper for getStacktrace(). * @param {?Function} fn If provided, when collecting the stack trace all * frames above the topmost call to this function, including that call, * will be left out of the stack trace. * @param {Array<!Function>} visited List of functions visited so far. * @return {string} Stack trace starting from function fn. * @suppress {es5Strict} * @private */ goog.debug.getStacktraceHelper_ = function(fn, visited) { var sb = []; // Circular reference, certain functions like bind seem to cause a recursive // loop so we need to catch circular references if (goog.array.contains(visited, fn)) { sb.push('[...circular reference...]'); // Traverse the call stack until function not found or max depth is reached } else if (fn && visited.length < goog.debug.MAX_STACK_DEPTH) { sb.push(goog.debug.getFunctionName(fn) + '('); var args = fn.arguments; // Args may be null for some special functions such as host objects or eval. for (var i = 0; args && i < args.length; i++) { if (i > 0) { sb.push(', '); } var argDesc; var arg = args[i]; switch (typeof arg) { case 'object': argDesc = arg ? 'object' : 'null'; break; case 'string': argDesc = arg; break; case 'number': argDesc = String(arg); break; case 'boolean': argDesc = arg ? 'true' : 'false'; break; case 'function': argDesc = goog.debug.getFunctionName(arg); argDesc = argDesc ? argDesc : '[fn]'; break; case 'undefined': default: argDesc = typeof arg; break; } if (argDesc.length > 40) { argDesc = argDesc.substr(0, 40) + '...'; } sb.push(argDesc); } visited.push(fn); sb.push(')\n'); try { sb.push(goog.debug.getStacktraceHelper_(fn.caller, visited)); } catch (e) { sb.push('[exception trying to get caller]\n'); } } else if (fn) { sb.push('[...long stack...]'); } else { sb.push('[end]'); } return sb.join(''); }; /** * Set a custom function name resolver. * @param {function(Function): string} resolver Resolves functions to their * names. */ goog.debug.setFunctionResolver = function(resolver) { goog.debug.fnNameResolver_ = resolver; }; /** * Gets a function name * @param {Function} fn Function to get name of. * @return {string} Function's name. */ goog.debug.getFunctionName = function(fn) { if (goog.debug.fnNameCache_[fn]) { return goog.debug.fnNameCache_[fn]; } if (goog.debug.fnNameResolver_) { var name = goog.debug.fnNameResolver_(fn); if (name) { goog.debug.fnNameCache_[fn] = name; return name; } } // Heuristically determine function name based on code. var functionSource = String(fn); if (!goog.debug.fnNameCache_[functionSource]) { var matches = /function ([^\(]+)/.exec(functionSource); if (matches) { var method = matches[1]; goog.debug.fnNameCache_[functionSource] = method; } else { goog.debug.fnNameCache_[functionSource] = '[Anonymous]'; } } return goog.debug.fnNameCache_[functionSource]; }; /** * Makes whitespace visible by replacing it with printable characters. * This is useful in finding diffrences between the expected and the actual * output strings of a testcase. * @param {string} string whose whitespace needs to be made visible. * @return {string} string whose whitespace is made visible. */ goog.debug.makeWhitespaceVisible = function(string) { return string.replace(/ /g, '[_]') .replace(/\f/g, '[f]') .replace(/\n/g, '[n]\n') .replace(/\r/g, '[r]') .replace(/\t/g, '[t]'); }; /** * Returns the type of a value. If a constructor is passed, and a suitable * string cannot be found, 'unknown type name' will be returned. * * <p>Forked rather than moved from {@link goog.asserts.getType_} * to avoid adding a dependency to goog.asserts. * @param {*} value A constructor, object, or primitive. * @return {string} The best display name for the value, or 'unknown type name'. */ goog.debug.runtimeType = function(value) { if (value instanceof Function) { return value.displayName || value.name || 'unknown type name'; } else if (value instanceof Object) { return /** @type {string} */ (value.constructor.displayName) || value.constructor.name || Object.prototype.toString.call(value); } else { return value === null ? 'null' : typeof value; } }; /** * Hash map for storing function names that have already been looked up. * @type {Object} * @private */ goog.debug.fnNameCache_ = {}; /** * Resolves functions to their names. Resolved function names will be cached. * @type {function(Function):string} * @private */ goog.debug.fnNameResolver_; /** * Private internal function to support goog.debug.freeze. * @param {T} arg * @return {T} * @template T * @private */ goog.debug.freezeInternal_ = goog.DEBUG && Object.freeze || function(arg) { return arg; }; /** * Freezes the given object, but only in debug mode (and in browsers that * support it). Note that this is a shallow freeze, so for deeply nested * objects it must be called at every level to ensure deep immutability. * @param {T} arg * @return {T} * @template T */ goog.debug.freeze = function(arg) { // NOTE: this compiles to nothing, but hides the possible side effect of // freezeInternal_ from the compiler so that the entire call can be // removed if the result is not used. return { valueOf: function() { return goog.debug.freezeInternal_(arg); } }.valueOf(); }; //javascript/closure/dom/htmlelement.js // Copyright 2017 The Closure Library Authors. All Rights Reserved. // // 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. goog.provide('goog.dom.HtmlElement'); /** * This subclass of HTMLElement is used when only a HTMLElement is possible and * not any of its subclasses. Normally, a type can refer to an instance of * itself or an instance of any subtype. More concretely, if HTMLElement is used * then the compiler must assume that it might still be e.g. HTMLScriptElement. * With this, the type check knows that it couldn't be any special element. * * @constructor * @extends {HTMLElement} */ goog.dom.HtmlElement = function() {}; //javascript/closure/dom/tagname.js // Copyright 2007 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Defines the goog.dom.TagName class. Its constants enumerate * all HTML tag names specified in either the the W3C HTML 4.01 index of * elements or the HTML5.1 specification. * * References: * https://www.w3.org/TR/html401/index/elements.html * https://www.w3.org/TR/html51/dom.html#elements */ goog.provide('goog.dom.TagName'); goog.require('goog.dom.HtmlElement'); /** * A tag name with the type of the element stored in the generic. * @param {string} tagName * @constructor * @template T */ goog.dom.TagName = function(tagName) { /** @private {string} */ this.tagName_ = tagName; }; /** * Returns the tag name. * @return {string} * @override */ goog.dom.TagName.prototype.toString = function() { return this.tagName_; }; // Closure Compiler unconditionally converts the following constants to their // string value (goog.dom.TagName.A -> 'A'). These are the consequences: // 1. Don't add any members or static members to goog.dom.TagName as they // couldn't be accessed after this optimization. // 2. Keep the constant name and its string value the same: // goog.dom.TagName.X = new goog.dom.TagName('Y'); // is converted to 'X', not 'Y'. /** @type {!goog.dom.TagName<!HTMLAnchorElement>} */ goog.dom.TagName.A = new goog.dom.TagName('A'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.ABBR = new goog.dom.TagName('ABBR'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.ACRONYM = new goog.dom.TagName('ACRONYM'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.ADDRESS = new goog.dom.TagName('ADDRESS'); /** @type {!goog.dom.TagName<!HTMLAppletElement>} */ goog.dom.TagName.APPLET = new goog.dom.TagName('APPLET'); /** @type {!goog.dom.TagName<!HTMLAreaElement>} */ goog.dom.TagName.AREA = new goog.dom.TagName('AREA'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.ARTICLE = new goog.dom.TagName('ARTICLE'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.ASIDE = new goog.dom.TagName('ASIDE'); /** @type {!goog.dom.TagName<!HTMLAudioElement>} */ goog.dom.TagName.AUDIO = new goog.dom.TagName('AUDIO'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.B = new goog.dom.TagName('B'); /** @type {!goog.dom.TagName<!HTMLBaseElement>} */ goog.dom.TagName.BASE = new goog.dom.TagName('BASE'); /** @type {!goog.dom.TagName<!HTMLBaseFontElement>} */ goog.dom.TagName.BASEFONT = new goog.dom.TagName('BASEFONT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.BDI = new goog.dom.TagName('BDI'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.BDO = new goog.dom.TagName('BDO'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.BIG = new goog.dom.TagName('BIG'); /** @type {!goog.dom.TagName<!HTMLQuoteElement>} */ goog.dom.TagName.BLOCKQUOTE = new goog.dom.TagName('BLOCKQUOTE'); /** @type {!goog.dom.TagName<!HTMLBodyElement>} */ goog.dom.TagName.BODY = new goog.dom.TagName('BODY'); /** @type {!goog.dom.TagName<!HTMLBRElement>} */ goog.dom.TagName.BR = new goog.dom.TagName('BR'); /** @type {!goog.dom.TagName<!HTMLButtonElement>} */ goog.dom.TagName.BUTTON = new goog.dom.TagName('BUTTON'); /** @type {!goog.dom.TagName<!HTMLCanvasElement>} */ goog.dom.TagName.CANVAS = new goog.dom.TagName('CANVAS'); /** @type {!goog.dom.TagName<!HTMLTableCaptionElement>} */ goog.dom.TagName.CAPTION = new goog.dom.TagName('CAPTION'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.CENTER = new goog.dom.TagName('CENTER'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.CITE = new goog.dom.TagName('CITE'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.CODE = new goog.dom.TagName('CODE'); /** @type {!goog.dom.TagName<!HTMLTableColElement>} */ goog.dom.TagName.COL = new goog.dom.TagName('COL'); /** @type {!goog.dom.TagName<!HTMLTableColElement>} */ goog.dom.TagName.COLGROUP = new goog.dom.TagName('COLGROUP'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.COMMAND = new goog.dom.TagName('COMMAND'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.DATA = new goog.dom.TagName('DATA'); /** @type {!goog.dom.TagName<!HTMLDataListElement>} */ goog.dom.TagName.DATALIST = new goog.dom.TagName('DATALIST'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.DD = new goog.dom.TagName('DD'); /** @type {!goog.dom.TagName<!HTMLModElement>} */ goog.dom.TagName.DEL = new goog.dom.TagName('DEL'); /** @type {!goog.dom.TagName<!HTMLDetailsElement>} */ goog.dom.TagName.DETAILS = new goog.dom.TagName('DETAILS'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.DFN = new goog.dom.TagName('DFN'); /** @type {!goog.dom.TagName<!HTMLDialogElement>} */ goog.dom.TagName.DIALOG = new goog.dom.TagName('DIALOG'); /** @type {!goog.dom.TagName<!HTMLDirectoryElement>} */ goog.dom.TagName.DIR = new goog.dom.TagName('DIR'); /** @type {!goog.dom.TagName<!HTMLDivElement>} */ goog.dom.TagName.DIV = new goog.dom.TagName('DIV'); /** @type {!goog.dom.TagName<!HTMLDListElement>} */ goog.dom.TagName.DL = new goog.dom.TagName('DL'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.DT = new goog.dom.TagName('DT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.EM = new goog.dom.TagName('EM'); /** @type {!goog.dom.TagName<!HTMLEmbedElement>} */ goog.dom.TagName.EMBED = new goog.dom.TagName('EMBED'); /** @type {!goog.dom.TagName<!HTMLFieldSetElement>} */ goog.dom.TagName.FIELDSET = new goog.dom.TagName('FIELDSET'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.FIGCAPTION = new goog.dom.TagName('FIGCAPTION'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.FIGURE = new goog.dom.TagName('FIGURE'); /** @type {!goog.dom.TagName<!HTMLFontElement>} */ goog.dom.TagName.FONT = new goog.dom.TagName('FONT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.FOOTER = new goog.dom.TagName('FOOTER'); /** @type {!goog.dom.TagName<!HTMLFormElement>} */ goog.dom.TagName.FORM = new goog.dom.TagName('FORM'); /** @type {!goog.dom.TagName<!HTMLFrameElement>} */ goog.dom.TagName.FRAME = new goog.dom.TagName('FRAME'); /** @type {!goog.dom.TagName<!HTMLFrameSetElement>} */ goog.dom.TagName.FRAMESET = new goog.dom.TagName('FRAMESET'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H1 = new goog.dom.TagName('H1'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H2 = new goog.dom.TagName('H2'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H3 = new goog.dom.TagName('H3'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H4 = new goog.dom.TagName('H4'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H5 = new goog.dom.TagName('H5'); /** @type {!goog.dom.TagName<!HTMLHeadingElement>} */ goog.dom.TagName.H6 = new goog.dom.TagName('H6'); /** @type {!goog.dom.TagName<!HTMLHeadElement>} */ goog.dom.TagName.HEAD = new goog.dom.TagName('HEAD'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.HEADER = new goog.dom.TagName('HEADER'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.HGROUP = new goog.dom.TagName('HGROUP'); /** @type {!goog.dom.TagName<!HTMLHRElement>} */ goog.dom.TagName.HR = new goog.dom.TagName('HR'); /** @type {!goog.dom.TagName<!HTMLHtmlElement>} */ goog.dom.TagName.HTML = new goog.dom.TagName('HTML'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.I = new goog.dom.TagName('I'); /** @type {!goog.dom.TagName<!HTMLIFrameElement>} */ goog.dom.TagName.IFRAME = new goog.dom.TagName('IFRAME'); /** @type {!goog.dom.TagName<!HTMLImageElement>} */ goog.dom.TagName.IMG = new goog.dom.TagName('IMG'); /** @type {!goog.dom.TagName<!HTMLInputElement>} */ goog.dom.TagName.INPUT = new goog.dom.TagName('INPUT'); /** @type {!goog.dom.TagName<!HTMLModElement>} */ goog.dom.TagName.INS = new goog.dom.TagName('INS'); /** @type {!goog.dom.TagName<!HTMLIsIndexElement>} */ goog.dom.TagName.ISINDEX = new goog.dom.TagName('ISINDEX'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.KBD = new goog.dom.TagName('KBD'); // HTMLKeygenElement is deprecated. /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.KEYGEN = new goog.dom.TagName('KEYGEN'); /** @type {!goog.dom.TagName<!HTMLLabelElement>} */ goog.dom.TagName.LABEL = new goog.dom.TagName('LABEL'); /** @type {!goog.dom.TagName<!HTMLLegendElement>} */ goog.dom.TagName.LEGEND = new goog.dom.TagName('LEGEND'); /** @type {!goog.dom.TagName<!HTMLLIElement>} */ goog.dom.TagName.LI = new goog.dom.TagName('LI'); /** @type {!goog.dom.TagName<!HTMLLinkElement>} */ goog.dom.TagName.LINK = new goog.dom.TagName('LINK'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.MAIN = new goog.dom.TagName('MAIN'); /** @type {!goog.dom.TagName<!HTMLMapElement>} */ goog.dom.TagName.MAP = new goog.dom.TagName('MAP'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.MARK = new goog.dom.TagName('MARK'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.MATH = new goog.dom.TagName('MATH'); /** @type {!goog.dom.TagName<!HTMLMenuElement>} */ goog.dom.TagName.MENU = new goog.dom.TagName('MENU'); /** @type {!goog.dom.TagName<!HTMLMenuItemElement>} */ goog.dom.TagName.MENUITEM = new goog.dom.TagName('MENUITEM'); /** @type {!goog.dom.TagName<!HTMLMetaElement>} */ goog.dom.TagName.META = new goog.dom.TagName('META'); /** @type {!goog.dom.TagName<!HTMLMeterElement>} */ goog.dom.TagName.METER = new goog.dom.TagName('METER'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.NAV = new goog.dom.TagName('NAV'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.NOFRAMES = new goog.dom.TagName('NOFRAMES'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.NOSCRIPT = new goog.dom.TagName('NOSCRIPT'); /** @type {!goog.dom.TagName<!HTMLObjectElement>} */ goog.dom.TagName.OBJECT = new goog.dom.TagName('OBJECT'); /** @type {!goog.dom.TagName<!HTMLOListElement>} */ goog.dom.TagName.OL = new goog.dom.TagName('OL'); /** @type {!goog.dom.TagName<!HTMLOptGroupElement>} */ goog.dom.TagName.OPTGROUP = new goog.dom.TagName('OPTGROUP'); /** @type {!goog.dom.TagName<!HTMLOptionElement>} */ goog.dom.TagName.OPTION = new goog.dom.TagName('OPTION'); /** @type {!goog.dom.TagName<!HTMLOutputElement>} */ goog.dom.TagName.OUTPUT = new goog.dom.TagName('OUTPUT'); /** @type {!goog.dom.TagName<!HTMLParagraphElement>} */ goog.dom.TagName.P = new goog.dom.TagName('P'); /** @type {!goog.dom.TagName<!HTMLParamElement>} */ goog.dom.TagName.PARAM = new goog.dom.TagName('PARAM'); /** @type {!goog.dom.TagName<!HTMLPictureElement>} */ goog.dom.TagName.PICTURE = new goog.dom.TagName('PICTURE'); /** @type {!goog.dom.TagName<!HTMLPreElement>} */ goog.dom.TagName.PRE = new goog.dom.TagName('PRE'); /** @type {!goog.dom.TagName<!HTMLProgressElement>} */ goog.dom.TagName.PROGRESS = new goog.dom.TagName('PROGRESS'); /** @type {!goog.dom.TagName<!HTMLQuoteElement>} */ goog.dom.TagName.Q = new goog.dom.TagName('Q'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.RP = new goog.dom.TagName('RP'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.RT = new goog.dom.TagName('RT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.RTC = new goog.dom.TagName('RTC'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.RUBY = new goog.dom.TagName('RUBY'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.S = new goog.dom.TagName('S'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SAMP = new goog.dom.TagName('SAMP'); /** @type {!goog.dom.TagName<!HTMLScriptElement>} */ goog.dom.TagName.SCRIPT = new goog.dom.TagName('SCRIPT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SECTION = new goog.dom.TagName('SECTION'); /** @type {!goog.dom.TagName<!HTMLSelectElement>} */ goog.dom.TagName.SELECT = new goog.dom.TagName('SELECT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SMALL = new goog.dom.TagName('SMALL'); /** @type {!goog.dom.TagName<!HTMLSourceElement>} */ goog.dom.TagName.SOURCE = new goog.dom.TagName('SOURCE'); /** @type {!goog.dom.TagName<!HTMLSpanElement>} */ goog.dom.TagName.SPAN = new goog.dom.TagName('SPAN'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.STRIKE = new goog.dom.TagName('STRIKE'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.STRONG = new goog.dom.TagName('STRONG'); /** @type {!goog.dom.TagName<!HTMLStyleElement>} */ goog.dom.TagName.STYLE = new goog.dom.TagName('STYLE'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SUB = new goog.dom.TagName('SUB'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SUMMARY = new goog.dom.TagName('SUMMARY'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SUP = new goog.dom.TagName('SUP'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.SVG = new goog.dom.TagName('SVG'); /** @type {!goog.dom.TagName<!HTMLTableElement>} */ goog.dom.TagName.TABLE = new goog.dom.TagName('TABLE'); /** @type {!goog.dom.TagName<!HTMLTableSectionElement>} */ goog.dom.TagName.TBODY = new goog.dom.TagName('TBODY'); /** @type {!goog.dom.TagName<!HTMLTableCellElement>} */ goog.dom.TagName.TD = new goog.dom.TagName('TD'); /** @type {!goog.dom.TagName<!HTMLTemplateElement>} */ goog.dom.TagName.TEMPLATE = new goog.dom.TagName('TEMPLATE'); /** @type {!goog.dom.TagName<!HTMLTextAreaElement>} */ goog.dom.TagName.TEXTAREA = new goog.dom.TagName('TEXTAREA'); /** @type {!goog.dom.TagName<!HTMLTableSectionElement>} */ goog.dom.TagName.TFOOT = new goog.dom.TagName('TFOOT'); /** @type {!goog.dom.TagName<!HTMLTableCellElement>} */ goog.dom.TagName.TH = new goog.dom.TagName('TH'); /** @type {!goog.dom.TagName<!HTMLTableSectionElement>} */ goog.dom.TagName.THEAD = new goog.dom.TagName('THEAD'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.TIME = new goog.dom.TagName('TIME'); /** @type {!goog.dom.TagName<!HTMLTitleElement>} */ goog.dom.TagName.TITLE = new goog.dom.TagName('TITLE'); /** @type {!goog.dom.TagName<!HTMLTableRowElement>} */ goog.dom.TagName.TR = new goog.dom.TagName('TR'); /** @type {!goog.dom.TagName<!HTMLTrackElement>} */ goog.dom.TagName.TRACK = new goog.dom.TagName('TRACK'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.TT = new goog.dom.TagName('TT'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.U = new goog.dom.TagName('U'); /** @type {!goog.dom.TagName<!HTMLUListElement>} */ goog.dom.TagName.UL = new goog.dom.TagName('UL'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.VAR = new goog.dom.TagName('VAR'); /** @type {!goog.dom.TagName<!HTMLVideoElement>} */ goog.dom.TagName.VIDEO = new goog.dom.TagName('VIDEO'); /** @type {!goog.dom.TagName<!goog.dom.HtmlElement>} */ goog.dom.TagName.WBR = new goog.dom.TagName('WBR'); //javascript/closure/dom/tags.js // Copyright 2014 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities for HTML element tag names. */ goog.provide('goog.dom.tags'); goog.require('goog.object'); /** * The void elements specified by * http://www.w3.org/TR/html-markup/syntax.html#void-elements. * @const @private {!Object<string, boolean>} */ goog.dom.tags.VOID_TAGS_ = goog.object.createSet( 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'); /** * Checks whether the tag is void (with no contents allowed and no legal end * tag), for example 'br'. * @param {string} tagName The tag name in lower case. * @return {boolean} */ goog.dom.tags.isVoidTag = function(tagName) { return goog.dom.tags.VOID_TAGS_[tagName] === true; }; //javascript/closure/i18n/uchar.js // Copyright 2009 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Collection of utility functions for Unicode character. * */ goog.provide('goog.i18n.uChar'); // Constants for handling Unicode supplementary characters (surrogate pairs). /** * The minimum value for Supplementary code points. * @type {number} * @private */ goog.i18n.uChar.SUPPLEMENTARY_CODE_POINT_MIN_VALUE_ = 0x10000; /** * The highest Unicode code point value (scalar value) according to the Unicode * Standard. * @type {number} * @private */ goog.i18n.uChar.CODE_POINT_MAX_VALUE_ = 0x10FFFF; /** * Lead surrogate minimum value. * @type {number} * @private */ goog.i18n.uChar.LEAD_SURROGATE_MIN_VALUE_ = 0xD800; /** * Lead surrogate maximum value. * @type {number} * @private */ goog.i18n.uChar.LEAD_SURROGATE_MAX_VALUE_ = 0xDBFF; /** * Trail surrogate minimum value. * @type {number} * @private */ goog.i18n.uChar.TRAIL_SURROGATE_MIN_VALUE_ = 0xDC00; /** * Trail surrogate maximum value. * @type {number} * @private */ goog.i18n.uChar.TRAIL_SURROGATE_MAX_VALUE_ = 0xDFFF; /** * The number of least significant bits of a supplementary code point that in * UTF-16 become the least significant bits of the trail surrogate. The rest of * the in-use bits of the supplementary code point become the least significant * bits of the lead surrogate. * @type {number} * @private */ goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_ = 10; /** * Gets the U+ notation string of a Unicode character. Ex: 'U+0041' for 'A'. * @param {string} ch The given character. * @return {string} The U+ notation of the given character. */ goog.i18n.uChar.toHexString = function(ch) { var chCode = goog.i18n.uChar.toCharCode(ch); var chCodeStr = 'U+' + goog.i18n.uChar.padString_(chCode.toString(16).toUpperCase(), 4, '0'); return chCodeStr; }; /** * Gets a string padded with given character to get given size. * @param {string} str The given string to be padded. * @param {number} length The target size of the string. * @param {string} ch The character to be padded with. * @return {string} The padded string. * @private */ goog.i18n.uChar.padString_ = function(str, length, ch) { while (str.length < length) { str = ch + str; } return str; }; /** * Gets Unicode value of the given character. * @param {string} ch The given character, which in the case of a supplementary * character is actually a surrogate pair. The remainder of the string is * ignored. * @return {number} The Unicode value of the character. */ goog.i18n.uChar.toCharCode = function(ch) { return goog.i18n.uChar.getCodePointAround(ch, 0); }; /** * Gets a character from the given Unicode value. If the given code point is not * a valid Unicode code point, null is returned. * @param {number} code The Unicode value of the character. * @return {?string} The character corresponding to the given Unicode value. */ goog.i18n.uChar.fromCharCode = function(code) { if (!goog.isDefAndNotNull(code) || !(code >= 0 && code <= goog.i18n.uChar.CODE_POINT_MAX_VALUE_)) { return null; } if (goog.i18n.uChar.isSupplementaryCodePoint(code)) { // First, we split the code point into the trail surrogate part (the // TRAIL_SURROGATE_BIT_COUNT_ least significant bits) and the lead surrogate // part (the rest of the bits, shifted down; note that for now this includes // the supplementary offset, also shifted down, to be subtracted off below). var leadBits = code >> goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_; var trailBits = code & // A bit-mask to get the TRAIL_SURROGATE_BIT_COUNT_ (i.e. 10) least // significant bits. 1 << 10 = 0x0400. 0x0400 - 1 = 0x03FF. ((1 << goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_) - 1); // Now we calculate the code point of each surrogate by adding each offset // to the corresponding base code point. var leadCodePoint = leadBits + (goog.i18n.uChar.LEAD_SURROGATE_MIN_VALUE_ - // Subtract off the supplementary offset, which had been shifted down // with the rest of leadBits. We do this here instead of before the // shift in order to save a separate subtraction step. (goog.i18n.uChar.SUPPLEMENTARY_CODE_POINT_MIN_VALUE_ >> goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_)); var trailCodePoint = trailBits + goog.i18n.uChar.TRAIL_SURROGATE_MIN_VALUE_; // Convert the code points into a 2-character long string. return String.fromCharCode(leadCodePoint) + String.fromCharCode(trailCodePoint); } return String.fromCharCode(code); }; /** * Returns the Unicode code point at the specified index. * * If the char value specified at the given index is in the leading-surrogate * range, and the following index is less than the length of `string`, and * the char value at the following index is in the trailing-surrogate range, * then the supplementary code point corresponding to this surrogate pair is * returned. * * If the char value specified at the given index is in the trailing-surrogate * range, and the preceding index is not before the start of `string`, and * the char value at the preceding index is in the leading-surrogate range, then * the negated supplementary code point corresponding to this surrogate pair is * returned. * * The negation allows the caller to differentiate between the case where the * given index is at the leading surrogate and the one where it is at the * trailing surrogate, and thus deduce where the next character starts and * preceding character ends. * * Otherwise, the char value at the given index is returned. Thus, a leading * surrogate is returned when it is not followed by a trailing surrogate, and a * trailing surrogate is returned when it is not preceded by a leading * surrogate. * * @param {string} string The string. * @param {number} index The index from which the code point is to be retrieved. * @return {number} The code point at the given index. If the given index is * that of the start (i.e. lead surrogate) of a surrogate pair, returns the code * point encoded by the pair. If the given index is that of the end (i.e. trail * surrogate) of a surrogate pair, returns the negated code pointed encoded by * the pair. */ goog.i18n.uChar.getCodePointAround = function(string, index) { var charCode = string.charCodeAt(index); if (goog.i18n.uChar.isLeadSurrogateCodePoint(charCode) && index + 1 < string.length) { var trail = string.charCodeAt(index + 1); if (goog.i18n.uChar.isTrailSurrogateCodePoint(trail)) { // Part of a surrogate pair. return /** @type {number} */ ( goog.i18n.uChar.buildSupplementaryCodePoint(charCode, trail)); } } else if (goog.i18n.uChar.isTrailSurrogateCodePoint(charCode) && index > 0) { var lead = string.charCodeAt(index - 1); if (goog.i18n.uChar.isLeadSurrogateCodePoint(lead)) { // Part of a surrogate pair. return /** @type {number} */ ( -goog.i18n.uChar.buildSupplementaryCodePoint(lead, charCode)); } } return charCode; }; /** * Determines the length of the string needed to represent the specified * Unicode code point. * @param {number} codePoint * @return {number} 2 if codePoint is a supplementary character, 1 otherwise. */ goog.i18n.uChar.charCount = function(codePoint) { return goog.i18n.uChar.isSupplementaryCodePoint(codePoint) ? 2 : 1; }; /** * Determines whether the specified Unicode code point is in the supplementary * Unicode characters range. * @param {number} codePoint * @return {boolean} Whether then given code point is a supplementary character. */ goog.i18n.uChar.isSupplementaryCodePoint = function(codePoint) { return codePoint >= goog.i18n.uChar.SUPPLEMENTARY_CODE_POINT_MIN_VALUE_ && codePoint <= goog.i18n.uChar.CODE_POINT_MAX_VALUE_; }; /** * Gets whether the given code point is a leading surrogate character. * @param {number} codePoint * @return {boolean} Whether the given code point is a leading surrogate * character. */ goog.i18n.uChar.isLeadSurrogateCodePoint = function(codePoint) { return codePoint >= goog.i18n.uChar.LEAD_SURROGATE_MIN_VALUE_ && codePoint <= goog.i18n.uChar.LEAD_SURROGATE_MAX_VALUE_; }; /** * Gets whether the given code point is a trailing surrogate character. * @param {number} codePoint * @return {boolean} Whether the given code point is a trailing surrogate * character. */ goog.i18n.uChar.isTrailSurrogateCodePoint = function(codePoint) { return codePoint >= goog.i18n.uChar.TRAIL_SURROGATE_MIN_VALUE_ && codePoint <= goog.i18n.uChar.TRAIL_SURROGATE_MAX_VALUE_; }; /** * Composes a supplementary Unicode code point from the given UTF-16 surrogate * pair. If leadSurrogate isn't a leading surrogate code point or trailSurrogate * isn't a trailing surrogate code point, null is returned. * @param {number} lead The leading surrogate code point. * @param {number} trail The trailing surrogate code point. * @return {?number} The supplementary Unicode code point obtained by decoding * the given UTF-16 surrogate pair. */ goog.i18n.uChar.buildSupplementaryCodePoint = function(lead, trail) { if (goog.i18n.uChar.isLeadSurrogateCodePoint(lead) && goog.i18n.uChar.isTrailSurrogateCodePoint(trail)) { var shiftedLeadOffset = (lead << goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_) - (goog.i18n.uChar.LEAD_SURROGATE_MIN_VALUE_ << goog.i18n.uChar.TRAIL_SURROGATE_BIT_COUNT_); var trailOffset = trail - goog.i18n.uChar.TRAIL_SURROGATE_MIN_VALUE_ + goog.i18n.uChar.SUPPLEMENTARY_CODE_POINT_MIN_VALUE_; return shiftedLeadOffset + trailOffset; } return null; }; //javascript/closure/structs/inversionmap.js // Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Provides inversion and inversion map functionality for storing * integer ranges and corresponding values. * */ goog.provide('goog.structs.InversionMap'); goog.require('goog.array'); goog.require('goog.asserts'); /** * Maps ranges to values. * @param {Array<number>} rangeArray An array of monotonically * increasing integer values, with at least one instance. * @param {Array<T>} valueArray An array of corresponding values. * Length must be the same as rangeArray. * @param {boolean=} opt_delta If true, saves only delta from previous value. * @constructor * @template T */ goog.structs.InversionMap = function(rangeArray, valueArray, opt_delta) { /** * @protected {Array<number>} */ this.rangeArray = null; goog.asserts.assert( rangeArray.length == valueArray.length, 'rangeArray and valueArray must have the same length.'); this.storeInversion_(rangeArray, opt_delta); /** @protected {Array<T>} */ this.values = valueArray; }; /** * Stores the integers as ranges (half-open). * If delta is true, the integers are delta from the previous value and * will be restored to the absolute value. * When used as a set, even indices are IN, and odd are OUT. * @param {Array<number>} rangeArray An array of monotonically * increasing integer values, with at least one instance. * @param {boolean=} opt_delta If true, saves only delta from previous value. * @private */ goog.structs.InversionMap.prototype.storeInversion_ = function( rangeArray, opt_delta) { this.rangeArray = rangeArray; for (var i = 1; i < rangeArray.length; i++) { if (rangeArray[i] == null) { rangeArray[i] = rangeArray[i - 1] + 1; } else if (opt_delta) { rangeArray[i] += rangeArray[i - 1]; } } }; /** * Splices a range -> value map into this inversion map. * @param {Array<number>} rangeArray An array of monotonically * increasing integer values, with at least one instance. * @param {Array<T>} valueArray An array of corresponding values. * Length must be the same as rangeArray. * @param {boolean=} opt_delta If true, saves only delta from previous value. */ goog.structs.InversionMap.prototype.spliceInversion = function( rangeArray, valueArray, opt_delta) { // By building another inversion map, we build the arrays that we need // to splice in. var otherMap = new goog.structs.InversionMap(rangeArray, valueArray, opt_delta); // Figure out where to splice those arrays. var startRange = otherMap.rangeArray[0]; var endRange = /** @type {number} */ (goog.array.peek(otherMap.rangeArray)); var startSplice = this.getLeast(startRange); var endSplice = this.getLeast(endRange); // The inversion map works by storing the start points of ranges... if (startRange != this.rangeArray[startSplice]) { // ...if we're splicing in a start point that isn't already here, // then we need to insert it after the insertion point. startSplice++; } // otherwise we overwrite the insertion point. this.rangeArray = this.rangeArray.slice(0, startSplice) .concat(otherMap.rangeArray) .concat(this.rangeArray.slice(endSplice + 1)); this.values = this.values.slice(0, startSplice) .concat(otherMap.values) .concat(this.values.slice(endSplice + 1)); }; /** * Gets the value corresponding to a number from the inversion map. * @param {number} intKey The number for which value needs to be retrieved * from inversion map. * @return {T|null} Value retrieved from inversion map; null if not found. */ goog.structs.InversionMap.prototype.at = function(intKey) { var index = this.getLeast(intKey); if (index < 0) { return null; } return this.values[index]; }; /** * Gets the largest index such that rangeArray[index] <= intKey from the * inversion map. * @param {number} intKey The probe for which rangeArray is searched. * @return {number} Largest index such that rangeArray[index] <= intKey. * @protected */ goog.structs.InversionMap.prototype.getLeast = function(intKey) { var arr = this.rangeArray; var low = 0; var high = arr.length; while (high - low > 8) { var mid = (high + low) >> 1; if (arr[mid] <= intKey) { low = mid; } else { high = mid; } } for (; low < high; ++low) { if (intKey < arr[low]) { break; } } return low - 1; }; //javascript/closure/i18n/graphemebreak.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Detect Grapheme Cluster Break in a pair of codepoints. Follows * Unicode 10 UAX#29. Tailoring for Virama × Indic Letters is used. * * Reference: http://unicode.org/reports/tr29 * */ goog.provide('goog.i18n.GraphemeBreak'); goog.require('goog.asserts'); goog.require('goog.i18n.uChar'); goog.require('goog.structs.InversionMap'); /** * Enum for all Grapheme Cluster Break properties. * These enums directly corresponds to Grapheme_Cluster_Break property values * mentioned in http://unicode.org/reports/tr29 table 2. VIRAMA and * INDIC_LETTER are for the Virama × Base tailoring mentioned in the notes. * * @protected @enum {number} */ goog.i18n.GraphemeBreak.property = { OTHER: 0, CONTROL: 1, EXTEND: 2, PREPEND: 3, SPACING_MARK: 4, INDIC_LETTER: 5, VIRAMA: 6, L: 7, V: 8, T: 9, LV: 10, LVT: 11, CR: 12, LF: 13, REGIONAL_INDICATOR: 14, ZWJ: 15, E_BASE: 16, GLUE_AFTER_ZWJ: 17, E_MODIFIER: 18, E_BASE_GAZ: 19 }; /** * Grapheme Cluster Break property values for all codepoints as inversion map. * Constructed lazily. * * @private {?goog.structs.InversionMap} */ goog.i18n.GraphemeBreak.inversions_ = null; /** * Indicates if a and b form a grapheme cluster. * * This implements the rules in: * http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules * * @param {number|string} a Code point or string with the first side of * grapheme cluster. * @param {number|string} b Code point or string with the second side of * grapheme cluster. * @param {boolean} extended If true, indicates extended grapheme cluster; * If false, indicates legacy cluster. * @return {boolean} True if a & b do not form a cluster; False otherwise. * @private */ goog.i18n.GraphemeBreak.applyBreakRules_ = function(a, b, extended) { var prop = goog.i18n.GraphemeBreak.property; var aCode = goog.isString(a) ? goog.i18n.GraphemeBreak.getCodePoint_(a, a.length - 1) : a; var bCode = goog.isString(b) ? goog.i18n.GraphemeBreak.getCodePoint_(b, 0) : b; var aProp = goog.i18n.GraphemeBreak.getBreakProp_(aCode); var bProp = goog.i18n.GraphemeBreak.getBreakProp_(bCode); var isString = goog.isString(a); // GB3. if (aProp === prop.CR && bProp === prop.LF) { return false; } // GB4. if (aProp === prop.CONTROL || aProp === prop.CR || aProp === prop.LF) { return true; } // GB5. if (bProp === prop.CONTROL || bProp === prop.CR || bProp === prop.LF) { return true; } // GB6. if (aProp === prop.L && (bProp === prop.L || bProp === prop.V || bProp === prop.LV || bProp === prop.LVT)) { return false; } // GB7. if ((aProp === prop.LV || aProp === prop.V) && (bProp === prop.V || bProp === prop.T)) { return false; } // GB8. if ((aProp === prop.LVT || aProp === prop.T) && bProp === prop.T) { return false; } // GB9. if (bProp === prop.EXTEND || bProp === prop.ZWJ || bProp === prop.VIRAMA) { return false; } // GB9a, GB9b. if (extended && (aProp === prop.PREPEND || bProp === prop.SPACING_MARK)) { return false; } // Tailorings for basic aksara support. if (extended && aProp === prop.VIRAMA && bProp === prop.INDIC_LETTER) { return false; } var aStr, index, codePoint, codePointProp; // GB10. if (isString) { if (bProp === prop.E_MODIFIER) { // If using new API, consume the string's code points starting from the // end and test the left side of: (E_Base | EBG) Extend* × E_Modifier. aStr = /** @type {string} */ (a); index = aStr.length - 1; codePoint = aCode; codePointProp = aProp; while (index > 0 && codePointProp === prop.EXTEND) { index -= goog.i18n.uChar.charCount(codePoint); codePoint = goog.i18n.GraphemeBreak.getCodePoint_(aStr, index); codePointProp = goog.i18n.GraphemeBreak.getBreakProp_(codePoint); } if (codePointProp === prop.E_BASE || codePointProp === prop.E_BASE_GAZ) { return false; } } } else { // If using legacy API, return best effort by testing: // (E_Base | EBG) × E_Modifier. if ((aProp === prop.E_BASE || aProp === prop.E_BASE_GAZ) && bProp === prop.E_MODIFIER) { return false; } } // GB11. if (aProp === prop.ZWJ && (bProp === prop.GLUE_AFTER_ZWJ || bProp === prop.E_BASE_GAZ)) { return false; } // GB12, GB13. if (isString) { if (bProp === prop.REGIONAL_INDICATOR) { // If using new API, consume the string's code points starting from the // end and test the left side of these rules: // - sot (RI RI)* RI × RI // - [^RI] (RI RI)* RI × RI. var numberOfRi = 0; aStr = /** @type {string} */ (a); index = aStr.length - 1; codePoint = aCode; codePointProp = aProp; while (index > 0 && codePointProp === prop.REGIONAL_INDICATOR) { numberOfRi++; index -= goog.i18n.uChar.charCount(codePoint); codePoint = goog.i18n.GraphemeBreak.getCodePoint_(aStr, index); codePointProp = goog.i18n.GraphemeBreak.getBreakProp_(codePoint); } if (codePointProp === prop.REGIONAL_INDICATOR) { numberOfRi++; } if (numberOfRi % 2 === 1) { return false; } } } else { // If using legacy API, return best effort by testing: RI × RI. if (aProp === prop.REGIONAL_INDICATOR && bProp === prop.REGIONAL_INDICATOR) { return false; } } // GB999. return true; }; /** * Method to return property enum value of the code point. If it is Hangul LV or * LVT, then it is computed; for the rest it is picked from the inversion map. * * @param {number} codePoint The code point value of the character. * @return {number} Property enum value of code point. * @private */ goog.i18n.GraphemeBreak.getBreakProp_ = function(codePoint) { if (0xAC00 <= codePoint && codePoint <= 0xD7A3) { var prop = goog.i18n.GraphemeBreak.property; if (codePoint % 0x1C === 0x10) { return prop.LV; } return prop.LVT; } else { if (!goog.i18n.GraphemeBreak.inversions_) { goog.i18n.GraphemeBreak.inversions_ = new goog.structs.InversionMap( [ 0, 10, 1, 2, 1, 18, 95, 33, 13, 1, 594, 112, 275, 7, 263, 45, 1, 1, 1, 2, 1, 2, 1, 1, 56, 6, 10, 11, 1, 1, 46, 21, 16, 1, 101, 7, 1, 1, 6, 2, 2, 1, 4, 33, 1, 1, 1, 30, 27, 91, 11, 58, 9, 34, 4, 1, 9, 1, 3, 1, 5, 43, 3, 120, 14, 1, 32, 1, 17, 37, 1, 1, 1, 1, 3, 8, 4, 1, 2, 1, 7, 8, 2, 2, 21, 7, 1, 1, 2, 17, 39, 1, 1, 1, 2, 6, 6, 1, 9, 5, 4, 2, 2, 12, 2, 15, 2, 1, 17, 39, 2, 3, 12, 4, 8, 6, 17, 2, 3, 14, 1, 17, 39, 1, 1, 3, 8, 4, 1, 20, 2, 29, 1, 2, 17, 39, 1, 1, 2, 1, 6, 6, 9, 6, 4, 2, 2, 13, 1, 16, 1, 18, 41, 1, 1, 1, 12, 1, 9, 1, 40, 1, 3, 17, 31, 1, 5, 4, 3, 5, 7, 8, 3, 2, 8, 2, 29, 1, 2, 17, 39, 1, 1, 1, 1, 2, 1, 3, 1, 5, 1, 8, 9, 1, 3, 2, 29, 1, 2, 17, 38, 3, 1, 2, 5, 7, 1, 1, 8, 1, 10, 2, 30, 2, 22, 48, 5, 1, 2, 6, 7, 1, 18, 2, 13, 46, 2, 1, 1, 1, 6, 1, 12, 8, 50, 46, 2, 1, 1, 1, 9, 11, 6, 14, 2, 58, 2, 27, 1, 1, 1, 1, 1, 4, 2, 49, 14, 1, 4, 1, 1, 2, 5, 48, 9, 1, 57, 33, 12, 4, 1, 6, 1, 2, 2, 2, 1, 16, 2, 4, 2, 2, 4, 3, 1, 3, 2, 7, 3, 4, 13, 1, 1, 1, 2, 6, 1, 1, 14, 1, 98, 96, 72, 88, 349, 3, 931, 15, 2, 1, 14, 15, 2, 1, 14, 15, 2, 15, 15, 14, 35, 17, 2, 1, 7, 8, 1, 2, 9, 1, 1, 9, 1, 45, 3, 1, 118, 2, 34, 1, 87, 28, 3, 3, 4, 2, 9, 1, 6, 3, 20, 19, 29, 44, 84, 23, 2, 2, 1, 4, 45, 6, 2, 1, 1, 1, 8, 1, 1, 1, 2, 8, 6, 13, 48, 84, 1, 14, 33, 1, 1, 5, 1, 1, 5, 1, 1, 1, 7, 31, 9, 12, 2, 1, 7, 23, 1, 4, 2, 2, 2, 2, 2, 11, 3, 2, 36, 2, 1, 1, 2, 3, 1, 1, 3, 2, 12, 36, 8, 8, 2, 2, 21, 3, 128, 3, 1, 13, 1, 7, 4, 1, 4, 2, 1, 3, 2, 198, 64, 523, 1, 1, 1, 2, 24, 7, 49, 16, 96, 33, 1324, 1, 34, 1, 1, 1, 82, 2, 98, 1, 14, 1, 1, 4, 86, 1, 1418, 3, 141, 1, 96, 32, 554, 6, 105, 2, 30164, 4, 1, 10, 32, 2, 80, 2, 272, 1, 3, 1, 4, 1, 23, 2, 2, 1, 24, 30, 4, 4, 3, 8, 1, 1, 13, 2, 16, 34, 16, 1, 1, 26, 18, 24, 24, 4, 8, 2, 23, 11, 1, 1, 12, 32, 3, 1, 5, 3, 3, 36, 1, 2, 4, 2, 1, 3, 1, 36, 1, 32, 35, 6, 2, 2, 2, 2, 12, 1, 8, 1, 1, 18, 16, 1, 3, 6, 1, 1, 1, 3, 48, 1, 1, 3, 2, 2, 5, 2, 1, 1, 32, 9, 1, 2, 2, 5, 1, 1, 201, 14, 2, 1, 1, 9, 8, 2, 1, 2, 1, 2, 1, 1, 1, 18, 11184, 27, 49, 1028, 1024, 6942, 1, 737, 16, 16, 16, 207, 1, 158, 2, 89, 3, 513, 1, 226, 1, 149, 5, 1670, 15, 40, 7, 1, 165, 2, 1305, 1, 1, 1, 53, 14, 1, 56, 1, 2, 1, 45, 3, 4, 2, 1, 1, 2, 1, 66, 3, 36, 5, 1, 6, 2, 62, 1, 12, 2, 1, 48, 3, 9, 1, 1, 1, 2, 6, 3, 95, 3, 3, 2, 1, 1, 2, 6, 1, 160, 1, 3, 7, 1, 21, 2, 2, 56, 1, 1, 1, 1, 1, 12, 1, 9, 1, 10, 4, 15, 192, 3, 8, 2, 1, 2, 1, 1, 105, 1, 2, 6, 1, 1, 2, 1, 1, 2, 1, 1, 1, 235, 1, 2, 6, 4, 2, 1, 1, 1, 27, 2, 82, 3, 8, 2, 1, 1, 1, 1, 106, 1, 1, 1, 2, 6, 1, 1, 101, 3, 2, 4, 1, 4, 1, 1283, 1, 14, 1, 1, 82, 23, 1, 7, 1, 2, 1, 2, 20025, 5, 59, 7, 1050, 62, 4, 19722, 2, 1, 4, 5313, 1, 1, 3, 3, 1, 5, 8, 8, 2, 7, 30, 4, 148, 3, 1979, 55, 4, 50, 8, 1, 14, 1, 22, 1424, 2213, 7, 109, 7, 2203, 26, 264, 1, 53, 1, 52, 1, 17, 1, 13, 1, 16, 1, 3, 1, 25, 3, 2, 1, 2, 3, 30, 1, 1, 1, 13, 5, 66, 2, 2, 11, 21, 4, 4, 1, 1, 9, 3, 1, 4, 3, 1, 3, 3, 1, 30, 1, 16, 2, 106, 1, 4, 1, 71, 2, 4, 1, 21, 1, 4, 2, 81, 1, 92, 3, 3, 5, 48, 1, 17, 1, 16, 1, 16, 3, 9, 1, 11, 1, 587, 5, 1, 1, 7, 1, 9, 10, 3, 2, 788162, 31 ], [ 1, 13, 1, 12, 1, 0, 1, 0, 1, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 3, 0, 2, 0, 1, 0, 2, 0, 2, 0, 2, 3, 0, 2, 0, 2, 0, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 3, 2, 4, 0, 5, 2, 4, 2, 0, 4, 2, 4, 6, 4, 0, 2, 5, 0, 2, 0, 5, 0, 2, 4, 0, 5, 2, 0, 2, 4, 2, 4, 6, 0, 2, 5, 0, 2, 0, 5, 0, 2, 4, 0, 5, 2, 4, 2, 6, 2, 5, 0, 2, 0, 2, 4, 0, 5, 2, 0, 4, 2, 4, 6, 0, 2, 0, 2, 4, 0, 5, 2, 0, 2, 4, 2, 4, 6, 2, 5, 0, 2, 0, 5, 0, 2, 0, 5, 2, 4, 2, 4, 6, 0, 2, 0, 2, 4, 0, 5, 0, 5, 0, 2, 4, 2, 6, 2, 5, 0, 2, 0, 2, 4, 0, 5, 2, 0, 4, 2, 4, 2, 4, 2, 4, 2, 6, 2, 5, 0, 2, 0, 2, 4, 0, 5, 0, 2, 4, 2, 4, 6, 3, 0, 2, 0, 2, 0, 4, 0, 5, 6, 2, 4, 2, 4, 2, 0, 4, 0, 5, 0, 2, 0, 4, 2, 6, 0, 2, 0, 5, 0, 2, 0, 4, 2, 0, 2, 0, 5, 0, 2, 0, 2, 0, 2, 0, 2, 0, 4, 5, 2, 4, 2, 6, 0, 2, 0, 2, 0, 2, 0, 5, 0, 2, 4, 2, 0, 6, 4, 2, 5, 0, 5, 0, 4, 2, 5, 2, 5, 0, 5, 0, 5, 2, 5, 2, 0, 4, 2, 0, 2, 5, 0, 2, 0, 7, 8, 9, 0, 2, 0, 5, 2, 6, 0, 5, 2, 6, 0, 5, 2, 0, 5, 2, 5, 0, 2, 4, 2, 4, 2, 4, 2, 6, 2, 0, 2, 0, 2, 1, 0, 2, 0, 2, 0, 5, 0, 2, 4, 2, 4, 2, 4, 2, 0, 5, 0, 5, 0, 5, 2, 4, 2, 0, 5, 0, 5, 4, 2, 4, 2, 6, 0, 2, 0, 2, 4, 2, 0, 2, 4, 0, 5, 2, 4, 2, 4, 2, 4, 2, 4, 6, 5, 0, 2, 0, 2, 4, 0, 5, 4, 2, 4, 2, 6, 2, 5, 0, 5, 0, 5, 0, 2, 4, 2, 4, 2, 4, 2, 6, 0, 5, 4, 2, 4, 2, 0, 5, 0, 2, 0, 2, 4, 2, 0, 2, 0, 4, 2, 0, 2, 0, 2, 0, 1, 2, 15, 1, 0, 1, 0, 1, 0, 2, 0, 16, 0, 17, 0, 17, 0, 17, 0, 16, 0, 17, 0, 16, 0, 17, 0, 2, 0, 6, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 6, 5, 2, 5, 4, 2, 4, 0, 5, 0, 5, 0, 5, 0, 5, 0, 4, 0, 5, 4, 6, 2, 0, 2, 0, 5, 0, 2, 0, 5, 2, 4, 6, 0, 7, 2, 4, 0, 5, 0, 5, 2, 4, 2, 4, 2, 4, 6, 0, 2, 0, 5, 2, 4, 2, 4, 2, 0, 2, 0, 2, 4, 0, 5, 0, 5, 0, 5, 0, 2, 0, 5, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 5, 4, 2, 4, 0, 4, 6, 0, 5, 0, 5, 0, 5, 0, 4, 2, 4, 2, 4, 0, 4, 6, 0, 11, 8, 9, 0, 2, 0, 2, 0, 2, 0, 2, 0, 1, 0, 2, 0, 1, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 6, 0, 2, 0, 4, 2, 4, 0, 2, 6, 0, 6, 2, 4, 0, 4, 2, 4, 6, 2, 0, 3, 0, 2, 0, 2, 4, 2, 6, 0, 2, 0, 2, 4, 0, 4, 2, 4, 6, 0, 3, 0, 2, 0, 4, 2, 4, 2, 6, 2, 0, 2, 0, 2, 4, 2, 6, 0, 2, 4, 0, 2, 0, 2, 4, 2, 4, 6, 0, 2, 0, 4, 2, 0, 4, 2, 4, 6, 2, 4, 2, 0, 2, 4, 2, 4, 2, 4, 2, 4, 2, 4, 6, 2, 0, 2, 4, 2, 4, 2, 4, 6, 2, 0, 2, 0, 4, 2, 4, 2, 4, 6, 2, 0, 2, 4, 2, 4, 2, 6, 2, 0, 2, 4, 2, 4, 2, 6, 0, 4, 2, 4, 6, 0, 2, 4, 2, 4, 2, 4, 2, 0, 2, 0, 2, 0, 4, 2, 0, 2, 0, 1, 0, 2, 4, 2, 0, 4, 2, 1, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 0, 14, 0, 17, 0, 17, 0, 17, 0, 16, 0, 17, 0, 17, 0, 17, 0, 16, 0, 16, 0, 16, 0, 17, 0, 17, 0, 18, 0, 16, 0, 16, 0, 19, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 17, 0, 16, 0, 17, 0, 17, 0, 17, 0, 16, 0, 16, 0, 16, 0, 16, 0, 17, 0, 16, 0, 16, 0, 17, 0, 17, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 16, 0, 1, 2 ], true); } return /** @type {number} */ ( goog.i18n.GraphemeBreak.inversions_.at(codePoint)); } }; /** * Extracts a code point from a string at the specified index. * * @param {string} str * @param {number} index * @return {number} Extracted code point. * @private */ goog.i18n.GraphemeBreak.getCodePoint_ = function(str, index) { var codePoint = goog.i18n.uChar.getCodePointAround(str, index); return (codePoint < 0) ? -codePoint : codePoint; }; /** * Indicates if there is a grapheme cluster boundary between a and b. * * Legacy function. Does not cover cases where a sequence of code points is * required in order to decide if there is a grapheme cluster boundary, such as * emoji modifier sequences and emoji flag sequences. To cover all cases please * use `hasGraphemeBreakStrings`. * * There are two kinds of grapheme clusters: 1) Legacy 2) Extended. This method * is to check for both using a boolean flag to switch between them. If no flag * is provided rules for the extended clusters will be used by default. * * @param {number} a The code point value of the first character. * @param {number} b The code point value of the second character. * @param {boolean=} opt_extended If true, indicates extended grapheme cluster; * If false, indicates legacy cluster. Default value is true. * @return {boolean} True if there is a grapheme cluster boundary between * a and b; False otherwise. */ goog.i18n.GraphemeBreak.hasGraphemeBreak = function(a, b, opt_extended) { return goog.i18n.GraphemeBreak.applyBreakRules_(a, b, opt_extended !== false); }; /** * Indicates if there is a grapheme cluster boundary between a and b. * * There are two kinds of grapheme clusters: 1) Legacy 2) Extended. This method * is to check for both using a boolean flag to switch between them. If no flag * is provided rules for the extended clusters will be used by default. * * @param {string} a String with the first sequence of characters. * @param {string} b String with the second sequence of characters. * @param {boolean=} opt_extended If true, indicates extended grapheme cluster; * If false, indicates legacy cluster. Default value is true. * @return {boolean} True if there is a grapheme cluster boundary between * a and b; False otherwise. */ goog.i18n.GraphemeBreak.hasGraphemeBreakStrings = function(a, b, opt_extended) { goog.asserts.assert(goog.isDef(a), 'First string should be defined.'); goog.asserts.assert(goog.isDef(b), 'Second string should be defined.'); // Break if any of the strings is empty. if (a.length === 0 || b.length === 0) { return true; } return goog.i18n.GraphemeBreak.applyBreakRules_(a, b, opt_extended !== false); }; //javascript/closure/format/format.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Provides utility functions for formatting strings, numbers etc. * */ goog.provide('goog.format'); goog.require('goog.i18n.GraphemeBreak'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * Formats a number of bytes in human readable form. * 54, 450K, 1.3M, 5G etc. * @param {number} bytes The number of bytes to show. * @param {number=} opt_decimals The number of decimals to use. Defaults to 2. * @return {string} The human readable form of the byte size. */ goog.format.fileSize = function(bytes, opt_decimals) { return goog.format.numBytesToString(bytes, opt_decimals, false); }; /** * Checks whether string value containing scaling units (K, M, G, T, P, m, * u, n) can be converted to a number. * * Where there is a decimal, there must be a digit to the left of the * decimal point. * * Negative numbers are valid. * * Examples: * 0, 1, 1.0, 10.4K, 2.3M, -0.3P, 1.2m * * @param {string} val String value to check. * @return {boolean} True if string could be converted to a numeric value. */ goog.format.isConvertableScaledNumber = function(val) { return goog.format.SCALED_NUMERIC_RE_.test(val); }; /** * Converts a string to numeric value, taking into account the units. * If string ends in 'B', use binary conversion. * @param {string} stringValue String to be converted to numeric value. * @return {number} Numeric value for string. */ goog.format.stringToNumericValue = function(stringValue) { if (goog.string.endsWith(stringValue, 'B')) { return goog.format.stringToNumericValue_( stringValue, goog.format.NUMERIC_SCALES_BINARY_); } return goog.format.stringToNumericValue_( stringValue, goog.format.NUMERIC_SCALES_SI_); }; /** * Converts a string to number of bytes, taking into account the units. * Binary conversion. * @param {string} stringValue String to be converted to numeric value. * @return {number} Numeric value for string. */ goog.format.stringToNumBytes = function(stringValue) { return goog.format.stringToNumericValue_( stringValue, goog.format.NUMERIC_SCALES_BINARY_); }; /** * Converts a numeric value to string representation. SI conversion. * @param {number} val Value to be converted. * @param {number=} opt_decimals The number of decimals to use. Defaults to 2. * @return {string} String representation of number. */ goog.format.numericValueToString = function(val, opt_decimals) { return goog.format.numericValueToString_( val, goog.format.NUMERIC_SCALES_SI_, opt_decimals); }; /** * Converts number of bytes to string representation. Binary conversion. * Default is to return the additional 'B' suffix only for scales greater than * 1K, e.g. '10.5KB' to minimize confusion with counts that are scaled by powers * of 1000. Otherwise, suffix is empty string. * @param {number} val Value to be converted. * @param {number=} opt_decimals The number of decimals to use. Defaults to 2. * @param {boolean=} opt_suffix If true, include trailing 'B' in returned * string. Default is true. * @param {boolean=} opt_useSeparator If true, number and scale will be * separated by a no break space. Default is false. * @return {string} String representation of number of bytes. */ goog.format.numBytesToString = function( val, opt_decimals, opt_suffix, opt_useSeparator) { var suffix = ''; if (!goog.isDef(opt_suffix) || opt_suffix) { suffix = 'B'; } return goog.format.numericValueToString_( val, goog.format.NUMERIC_SCALES_BINARY_, opt_decimals, suffix, opt_useSeparator); }; /** * Converts a string to numeric value, taking into account the units. * @param {string} stringValue String to be converted to numeric value. * @param {Object} conversion Dictionary of conversion scales. * @return {number} Numeric value for string. If it cannot be converted, * returns NaN. * @private */ goog.format.stringToNumericValue_ = function(stringValue, conversion) { var match = stringValue.match(goog.format.SCALED_NUMERIC_RE_); if (!match) { return NaN; } var val = Number(match[1]) * conversion[match[2]]; return val; }; /** * Converts a numeric value to string, using specified conversion * scales. * @param {number} val Value to be converted. * @param {Object} conversion Dictionary of scaling factors. * @param {number=} opt_decimals The number of decimals to use. Default is 2. * @param {string=} opt_suffix Optional suffix to append. * @param {boolean=} opt_useSeparator If true, number and scale will be * separated by a space. Default is false. * @return {string} The human readable form of the byte size. * @private */ goog.format.numericValueToString_ = function( val, conversion, opt_decimals, opt_suffix, opt_useSeparator) { var prefixes = goog.format.NUMERIC_SCALE_PREFIXES_; var orig_val = val; var symbol = ''; var separator = ''; var scale = 1; if (val < 0) { val = -val; } for (var i = 0; i < prefixes.length; i++) { var unit = prefixes[i]; scale = conversion[unit]; if (val >= scale || (scale <= 1 && val > 0.1 * scale)) { // Treat values less than 1 differently, allowing 0.5 to be "0.5" rather // than "500m" symbol = unit; break; } } if (!symbol) { scale = 1; } else { if (opt_suffix) { symbol += opt_suffix; } if (opt_useSeparator) { separator = ' '; } } var ex = Math.pow(10, goog.isDef(opt_decimals) ? opt_decimals : 2); return Math.round(orig_val / scale * ex) / ex + separator + symbol; }; /** * Regular expression for detecting scaling units, such as K, M, G, etc. for * converting a string representation to a numeric value. * * Also allow 'k' to be aliased to 'K'. These could be used for SI (powers * of 1000) or Binary (powers of 1024) conversions. * * Also allow final 'B' to be interpreted as byte-count, implicitly triggering * binary conversion (e.g., '10.2MB'). * * @type {RegExp} * @private */ goog.format.SCALED_NUMERIC_RE_ = /^([-]?\d+\.?\d*)([K,M,G,T,P,E,Z,Y,k,m,u,n]?)[B]?$/; /** * Ordered list of scaling prefixes in decreasing order. * @private {Array<string>} */ goog.format.NUMERIC_SCALE_PREFIXES_ = ['Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'K', '', 'm', 'u', 'n']; /** * Scaling factors for conversion of numeric value to string. SI conversion. * @type {Object} * @private */ goog.format.NUMERIC_SCALES_SI_ = { '': 1, 'n': 1e-9, 'u': 1e-6, 'm': 1e-3, 'k': 1e3, 'K': 1e3, 'M': 1e6, 'G': 1e9, 'T': 1e12, 'P': 1e15, 'E': 1e18, 'Z': 1e21, 'Y': 1e24 }; /** * Scaling factors for conversion of numeric value to string. Binary * conversion. * @type {Object} * @private */ goog.format.NUMERIC_SCALES_BINARY_ = { '': 1, 'n': Math.pow(1024, -3), 'u': Math.pow(1024, -2), 'm': 1.0 / 1024, 'k': 1024, 'K': 1024, 'M': Math.pow(1024, 2), 'G': Math.pow(1024, 3), 'T': Math.pow(1024, 4), 'P': Math.pow(1024, 5), 'E': Math.pow(1024, 6), 'Z': Math.pow(1024, 7), 'Y': Math.pow(1024, 8) }; /** * First Unicode code point that has the Mark property. * @type {number} * @private */ goog.format.FIRST_GRAPHEME_EXTEND_ = 0x300; /** * Returns true if and only if given character should be treated as a breaking * space. All ASCII control characters, the main Unicode range of spacing * characters (U+2000 to U+200B inclusive except for U+2007), and several other * Unicode space characters are treated as breaking spaces. * @param {number} charCode The character code under consideration. * @return {boolean} True if the character is a breaking space. * @private */ goog.format.isTreatedAsBreakingSpace_ = function(charCode) { return (charCode <= goog.format.WbrToken_.SPACE) || (charCode >= 0x1000 && ((charCode >= 0x2000 && charCode <= 0x2006) || (charCode >= 0x2008 && charCode <= 0x200B) || charCode == 0x1680 || charCode == 0x180E || charCode == 0x2028 || charCode == 0x2029 || charCode == 0x205f || charCode == 0x3000)); }; /** * Returns true if and only if given character is an invisible formatting * character. * @param {number} charCode The character code under consideration. * @return {boolean} True if the character is an invisible formatting character. * @private */ goog.format.isInvisibleFormattingCharacter_ = function(charCode) { // See: http://unicode.org/charts/PDF/U2000.pdf return (charCode >= 0x200C && charCode <= 0x200F) || (charCode >= 0x202A && charCode <= 0x202E); }; /** * Inserts word breaks into an HTML string at a given interval. The counter is * reset if a space or a character which behaves like a space is encountered, * but it isn't incremented if an invisible formatting character is encountered. * WBRs aren't inserted into HTML tags or entities. Entities count towards the * character count, HTML tags do not. * * With common strings aliased, objects allocations are constant based on the * length of the string: N + 3. This guarantee does not hold if the string * contains an element >= U+0300 and hasGraphemeBreak is non-trivial. * * @param {string} str HTML to insert word breaks into. * @param {function(number, number, boolean): boolean} hasGraphemeBreak A * function determining if there is a grapheme break between two characters, * in the same signature as goog.i18n.GraphemeBreak.hasGraphemeBreak. * @param {number=} opt_maxlen Maximum length after which to ensure * there is a break. Default is 10 characters. * @return {string} The string including word breaks. * @private */ goog.format.insertWordBreaksGeneric_ = function( str, hasGraphemeBreak, opt_maxlen) { var maxlen = opt_maxlen || 10; if (maxlen > str.length) return str; var rv = []; var n = 0; // The length of the current token // This will contain the ampersand or less-than character if one of the // two has been seen; otherwise, the value is zero. var nestingCharCode = 0; // First character position from input string that has not been outputted. var lastDumpPosition = 0; var charCode = 0; for (var i = 0; i < str.length; i++) { // Using charCodeAt versus charAt avoids allocating new string objects. var lastCharCode = charCode; charCode = str.charCodeAt(i); // Don't add a WBR before characters that might be grapheme extending. var isPotentiallyGraphemeExtending = charCode >= goog.format.FIRST_GRAPHEME_EXTEND_ && !hasGraphemeBreak(lastCharCode, charCode, true); // Don't add a WBR at the end of a word. For the purposes of determining // work breaks, all ASCII control characters and some commonly encountered // Unicode spacing characters are treated as breaking spaces. if (n >= maxlen && !goog.format.isTreatedAsBreakingSpace_(charCode) && !isPotentiallyGraphemeExtending) { // Flush everything seen so far, and append a word break. rv.push(str.substring(lastDumpPosition, i), goog.format.WORD_BREAK_HTML); lastDumpPosition = i; n = 0; } if (!nestingCharCode) { // Not currently within an HTML tag or entity if (charCode == goog.format.WbrToken_.LT || charCode == goog.format.WbrToken_.AMP) { // Entering an HTML Entity '&' or open tag '<' nestingCharCode = charCode; } else if (goog.format.isTreatedAsBreakingSpace_(charCode)) { // A space or control character -- reset the token length n = 0; } else if (!goog.format.isInvisibleFormattingCharacter_(charCode)) { // A normal flow character - increment. For grapheme extending // characters, this is not *technically* a new character. However, // since the grapheme break detector might be overly conservative, // we have to continue incrementing, or else we won't even be able // to add breaks when we get to things like punctuation. For the // case where we have a full grapheme break detector, it is okay if // we occasionally break slightly early. n++; } } else if ( charCode == goog.format.WbrToken_.GT && nestingCharCode == goog.format.WbrToken_.LT) { // Leaving an HTML tag, treat the tag as zero-length nestingCharCode = 0; } else if ( charCode == goog.format.WbrToken_.SEMI_COLON && nestingCharCode == goog.format.WbrToken_.AMP) { // Leaving an HTML entity, treat it as length one nestingCharCode = 0; n++; } } // Take care of anything we haven't flushed so far. rv.push(str.substr(lastDumpPosition)); return rv.join(''); }; /** * Inserts word breaks into an HTML string at a given interval. * * This method is as aggressive as possible, using a full table of Unicode * characters where it is legal to insert word breaks; however, this table * comes at a 2.5k pre-gzip (~1k post-gzip) size cost. Consider using * insertWordBreaksBasic to minimize the size impact. * * @param {string} str HTML to insert word breaks into. * @param {number=} opt_maxlen Maximum length after which to ensure there is a * break. Default is 10 characters. * @return {string} The string including word breaks. * @deprecated Prefer wrapping with CSS word-wrap: break-word. */ goog.format.insertWordBreaks = function(str, opt_maxlen) { return goog.format.insertWordBreaksGeneric_( str, goog.i18n.GraphemeBreak.hasGraphemeBreak, opt_maxlen); }; /** * Determines conservatively if a character has a Grapheme break. * * Conforms to a similar signature as goog.i18n.GraphemeBreak, but is overly * conservative, returning true only for characters in common scripts that * are simple to account for. * * @param {number} lastCharCode The previous character code. Ignored. * @param {number} charCode The character code under consideration. It must be * at least \u0300 as a precondition -- this case is covered by * insertWordBreaksGeneric_. * @param {boolean=} opt_extended Ignored, to conform with the interface. * @return {boolean} Whether it is one of the recognized subsets of characters * with a grapheme break. * @private */ goog.format.conservativelyHasGraphemeBreak_ = function( lastCharCode, charCode, opt_extended) { // Return false for everything except the most common Cyrillic characters. // Don't worry about Latin characters, because insertWordBreaksGeneric_ // itself already handles those. // TODO(gboyer): Also account for Greek, Armenian, and Georgian if it is // simple to do so. return charCode >= 0x400 && charCode < 0x523; }; // TODO(gboyer): Consider using a compile-time flag to switch implementations // rather than relying on the developers to toggle implementations. /** * Inserts word breaks into an HTML string at a given interval. * * This method is less aggressive than insertWordBreaks, only inserting * breaks next to punctuation and between Latin or Cyrillic characters. * However, this is good enough for the common case of URLs. It also * works for all Latin and Cyrillic languages, plus CJK has no need for word * breaks. When this method is used, goog.i18n.GraphemeBreak may be dead * code eliminated. * * @param {string} str HTML to insert word breaks into. * @param {number=} opt_maxlen Maximum length after which to ensure there is a * break. Default is 10 characters. * @return {string} The string including word breaks. * @deprecated Prefer wrapping with CSS word-wrap: break-word. */ goog.format.insertWordBreaksBasic = function(str, opt_maxlen) { return goog.format.insertWordBreaksGeneric_( str, goog.format.conservativelyHasGraphemeBreak_, opt_maxlen); }; /** * True iff the current userAgent is IE8 or above. * @type {boolean} * @private */ goog.format.IS_IE8_OR_ABOVE_ = goog.userAgent.IE && goog.userAgent.isVersionOrHigher(8); /** * Constant for the WBR replacement used by insertWordBreaks. Safari requires * <wbr></wbr>, Opera needs the &shy; entity, though this will give a visible * hyphen at breaks. IE8 uses a zero width space. * Other browsers just use <wbr>. * @type {string} */ goog.format.WORD_BREAK_HTML = goog.userAgent.WEBKIT ? '<wbr></wbr>' : goog.userAgent.OPERA ? '&shy;' : goog.format.IS_IE8_OR_ABOVE_ ? '&#8203;' : '<wbr>'; /** * Tokens used within insertWordBreaks. * @private * @enum {number} */ goog.format.WbrToken_ = { LT: 60, // '<'.charCodeAt(0) GT: 62, // '>'.charCodeAt(0) AMP: 38, // '&'.charCodeAt(0) SEMI_COLON: 59, // ';'.charCodeAt(0) SPACE: 32 // ' '.charCodeAt(0) }; //javascript/closure/fs/url.js // Copyright 2015 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Wrapper for URL and its createObjectUrl and revokeObjectUrl * methods that are part of the HTML5 File API. */ goog.provide('goog.fs.url'); /** * Creates a blob URL for a blob object. * Throws an error if the browser does not support Object Urls. * * @param {!Blob} blob The object for which to create the URL. * @return {string} The URL for the object. */ goog.fs.url.createObjectUrl = function(blob) { return goog.fs.url.getUrlObject_().createObjectURL(blob); }; /** * Revokes a URL created by {@link goog.fs.url.createObjectUrl}. * Throws an error if the browser does not support Object Urls. * * @param {string} url The URL to revoke. */ goog.fs.url.revokeObjectUrl = function(url) { goog.fs.url.getUrlObject_().revokeObjectURL(url); }; /** * @typedef {{createObjectURL: (function(!Blob): string), * revokeObjectURL: function(string): void}} */ goog.fs.url.UrlObject_; /** * Get the object that has the createObjectURL and revokeObjectURL functions for * this browser. * * @return {goog.fs.url.UrlObject_} The object for this browser. * @private */ goog.fs.url.getUrlObject_ = function() { var urlObject = goog.fs.url.findUrlObject_(); if (urlObject != null) { return urlObject; } else { throw new Error('This browser doesn\'t seem to support blob URLs'); } }; /** * Finds the object that has the createObjectURL and revokeObjectURL functions * for this browser. * * @return {?goog.fs.url.UrlObject_} The object for this browser or null if the * browser does not support Object Urls. * @private */ goog.fs.url.findUrlObject_ = function() { // This is what the spec says to do // http://dev.w3.org/2006/webapi/FileAPI/#dfn-createObjectURL if (goog.isDef(goog.global.URL) && goog.isDef(goog.global.URL.createObjectURL)) { return /** @type {goog.fs.url.UrlObject_} */ (goog.global.URL); // This is what Chrome does (as of 10.0.648.6 dev) } else if ( goog.isDef(goog.global.webkitURL) && goog.isDef(goog.global.webkitURL.createObjectURL)) { return /** @type {goog.fs.url.UrlObject_} */ (goog.global.webkitURL); // This is what the spec used to say to do } else if (goog.isDef(goog.global.createObjectURL)) { return /** @type {goog.fs.url.UrlObject_} */ (goog.global); } else { return null; } }; /** * Checks whether this browser supports Object Urls. If not, calls to * createObjectUrl and revokeObjectUrl will result in an error. * * @return {boolean} True if this browser supports Object Urls. */ goog.fs.url.browserSupportsObjectUrls = function() { return goog.fs.url.findUrlObject_() != null; }; //javascript/closure/functions/functions.js // Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utilities for creating functions. Loosely inspired by the * java classes: http://goo.gl/GM0Hmu and http://goo.gl/6k7nI8. * * @author <EMAIL> (<NAME>) */ goog.provide('goog.functions'); /** * Creates a function that always returns the same value. * @param {T} retValue The value to return. * @return {function():T} The new function. * @template T */ goog.functions.constant = function(retValue) { return function() { return retValue; }; }; /** * Always returns false. * @type {function(...): boolean} */ goog.functions.FALSE = goog.functions.constant(false); /** * Always returns true. * @type {function(...): boolean} */ goog.functions.TRUE = goog.functions.constant(true); /** * Always returns NULL. * @type {function(...): null} */ goog.functions.NULL = goog.functions.constant(null); /** * A simple function that returns the first argument of whatever is passed * into it. * @param {T=} opt_returnValue The single value that will be returned. * @param {...*} var_args Optional trailing arguments. These are ignored. * @return {T} The first argument passed in, or undefined if nothing was passed. * @template T */ goog.functions.identity = function(opt_returnValue, var_args) { return opt_returnValue; }; /** * Creates a function that always throws an error with the given message. * @param {string} message The error message. * @return {!Function} The error-throwing function. */ goog.functions.error = function(message) { return function() { throw new Error(message); }; }; /** * Creates a function that throws the given object. * @param {*} err An object to be thrown. * @return {!Function} The error-throwing function. */ goog.functions.fail = function(err) { return function() { throw err; }; }; /** * Given a function, create a function that keeps opt_numArgs arguments and * silently discards all additional arguments. * @param {Function} f The original function. * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0. * @return {!Function} A version of f that only keeps the first opt_numArgs * arguments. */ goog.functions.lock = function(f, opt_numArgs) { opt_numArgs = opt_numArgs || 0; return function() { var self = /** @type {*} */ (this); return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs)); }; }; /** * Creates a function that returns its nth argument. * @param {number} n The position of the return argument. * @return {!Function} A new function. */ goog.functions.nth = function(n) { return function() { return arguments[n]; }; }; /** * Like goog.partial(), except that arguments are added after arguments to the * returned function. * * Usage: * function f(arg1, arg2, arg3, arg4) { ... } * var g = goog.functions.partialRight(f, arg3, arg4); * g(arg1, arg2); * * @param {!Function} fn A function to partially apply. * @param {...*} var_args Additional arguments that are partially applied to fn * at the end. * @return {!Function} A partially-applied form of the function goog.partial() * was invoked as a method of. */ goog.functions.partialRight = function(fn, var_args) { var rightArgs = Array.prototype.slice.call(arguments, 1); return function() { var self = /** @type {*} */ (this); var newArgs = Array.prototype.slice.call(arguments); newArgs.push.apply(newArgs, rightArgs); return fn.apply(self, newArgs); }; }; /** * Given a function, create a new function that swallows its return value * and replaces it with a new one. * @param {Function} f A function. * @param {T} retValue A new return value. * @return {function(...?):T} A new function. * @template T */ goog.functions.withReturnValue = function(f, retValue) { return goog.functions.sequence(f, goog.functions.constant(retValue)); }; /** * Creates a function that returns whether its argument equals the given value. * * Example: * var key = goog.object.findKey(obj, goog.functions.equalTo('needle')); * * @param {*} value The value to compare to. * @param {boolean=} opt_useLooseComparison Whether to use a loose (==) * comparison rather than a strict (===) one. Defaults to false. * @return {function(*):boolean} The new function. */ goog.functions.equalTo = function(value, opt_useLooseComparison) { return function(other) { return opt_useLooseComparison ? (value == other) : (value === other); }; }; /** * Creates the composition of the functions passed in. * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)). * @param {function(...?):T} fn The final function. * @param {...Function} var_args A list of functions. * @return {function(...?):T} The composition of all inputs. * @template T */ goog.functions.compose = function(fn, var_args) { var functions = arguments; var length = functions.length; return function() { var self = /** @type {*} */ (this); var result; if (length) { result = functions[length - 1].apply(self, arguments); } for (var i = length - 2; i >= 0; i--) { result = functions[i].call(self, result); } return result; }; }; /** * Creates a function that calls the functions passed in in sequence, and * returns the value of the last function. For example, * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x). * @param {...Function} var_args A list of functions. * @return {!Function} A function that calls all inputs in sequence. */ goog.functions.sequence = function(var_args) { var functions = arguments; var length = functions.length; return function() { var self = /** @type {*} */ (this); var result; for (var i = 0; i < length; i++) { result = functions[i].apply(self, arguments); } return result; }; }; /** * Creates a function that returns true if each of its components evaluates * to true. The components are evaluated in order, and the evaluation will be * short-circuited as soon as a function returns false. * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x). * @param {...Function} var_args A list of functions. * @return {function(...?):boolean} A function that ANDs its component * functions. */ goog.functions.and = function(var_args) { var functions = arguments; var length = functions.length; return function() { var self = /** @type {*} */ (this); for (var i = 0; i < length; i++) { if (!functions[i].apply(self, arguments)) { return false; } } return true; }; }; /** * Creates a function that returns true if any of its components evaluates * to true. The components are evaluated in order, and the evaluation will be * short-circuited as soon as a function returns true. * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x). * @param {...Function} var_args A list of functions. * @return {function(...?):boolean} A function that ORs its component * functions. */ goog.functions.or = function(var_args) { var functions = arguments; var length = functions.length; return function() { var self = /** @type {*} */ (this); for (var i = 0; i < length; i++) { if (functions[i].apply(self, arguments)) { return true; } } return false; }; }; /** * Creates a function that returns the Boolean opposite of a provided function. * For example, (goog.functions.not(f))(x) is equivalent to !f(x). * @param {!Function} f The original function. * @return {function(...?):boolean} A function that delegates to f and returns * opposite. */ goog.functions.not = function(f) { return function() { var self = /** @type {*} */ (this); return !f.apply(self, arguments); }; }; /** * Generic factory function to construct an object given the constructor * and the arguments. Intended to be bound to create object factories. * * Example: * * var factory = goog.partial(goog.functions.create, Class); * * @param {function(new:T, ...)} constructor The constructor for the Object. * @param {...*} var_args The arguments to be passed to the constructor. * @return {T} A new instance of the class given in `constructor`. * @template T */ goog.functions.create = function(constructor, var_args) { /** * @constructor * @final */ var temp = function() {}; temp.prototype = constructor.prototype; // obj will have constructor's prototype in its chain and // 'obj instanceof constructor' will be true. var obj = new temp(); // obj is initialized by constructor. // arguments is only array-like so lacks shift(), but can be used with // the Array prototype function. constructor.apply(obj, Array.prototype.slice.call(arguments, 1)); return obj; }; /** * @define {boolean} Whether the return value cache should be used. * This should only be used to disable caches when testing. */ goog.define('goog.functions.CACHE_RETURN_VALUE', true); /** * Gives a wrapper function that caches the return value of a parameterless * function when first called. * * When called for the first time, the given function is called and its * return value is cached (thus this is only appropriate for idempotent * functions). Subsequent calls will return the cached return value. This * allows the evaluation of expensive functions to be delayed until first used. * * To cache the return values of functions with parameters, see goog.memoize. * * @param {function():T} fn A function to lazily evaluate. * @return {function():T} A wrapped version the function. * @template T */ goog.functions.cacheReturnValue = function(fn) { var called = false; var value; return function() { if (!goog.functions.CACHE_RETURN_VALUE) { return fn(); } if (!called) { value = fn(); called = true; } return value; }; }; /** * Wraps a function to allow it to be called, at most, once. All * additional calls are no-ops. * * This is particularly useful for initialization functions * that should be called, at most, once. * * @param {function():*} f Function to call. * @return {function():undefined} Wrapped function. */ goog.functions.once = function(f) { // Keep a reference to the function that we null out when we're done with // it -- that way, the function can be GC'd when we're done with it. var inner = f; return function() { if (inner) { var tmp = inner; inner = null; tmp(); } }; }; /** * Wraps a function to allow it to be called, at most, once per interval * (specified in milliseconds). If the wrapper function is called N times within * that interval, only the Nth call will go through. * * This is particularly useful for batching up repeated actions where the * last action should win. This can be used, for example, for refreshing an * autocomplete pop-up every so often rather than updating with every keystroke, * since the final text typed by the user is the one that should produce the * final autocomplete results. For more stateful debouncing with support for * pausing, resuming, and canceling debounced actions, use * `goog.async.Debouncer`. * * @param {function(this:SCOPE, ...?)} f Function to call. * @param {number} interval Interval over which to debounce. The function will * only be called after the full interval has elapsed since the last call. * @param {SCOPE=} opt_scope Object in whose scope to call the function. * @return {function(...?): undefined} Wrapped function. * @template SCOPE */ goog.functions.debounce = function(f, interval, opt_scope) { var timeout = 0; return /** @type {function(...?)} */ (function(var_args) { goog.global.clearTimeout(timeout); var args = arguments; timeout = goog.global.setTimeout(function() { f.apply(opt_scope, args); }, interval); }); }; /** * Wraps a function to allow it to be called, at most, once per interval * (specified in milliseconds). If the wrapper function is called N times in * that interval, both the 1st and the Nth calls will go through. * * This is particularly useful for limiting repeated user requests where the * the last action should win, but you also don't want to wait until the end of * the interval before sending a request out, as it leads to a perception of * slowness for the user. * * @param {function(this:SCOPE, ...?)} f Function to call. * @param {number} interval Interval over which to throttle. The function can * only be called once per interval. * @param {SCOPE=} opt_scope Object in whose scope to call the function. * @return {function(...?): undefined} Wrapped function. * @template SCOPE */ goog.functions.throttle = function(f, interval, opt_scope) { var timeout = 0; var shouldFire = false; var args = []; var handleTimeout = function() { timeout = 0; if (shouldFire) { shouldFire = false; fire(); } }; var fire = function() { timeout = goog.global.setTimeout(handleTimeout, interval); f.apply(opt_scope, args); }; return /** @type {function(...?)} */ (function(var_args) { args = arguments; if (!timeout) { fire(); } else { shouldFire = true; } }); }; /** * Wraps a function to allow it to be called, at most, once per interval * (specified in milliseconds). If the wrapper function is called N times within * that interval, only the 1st call will go through. * * This is particularly useful for limiting repeated user requests where the * first request is guaranteed to have all the data required to perform the * final action, so there's no need to wait until the end of the interval before * sending the request out. * * @param {function(this:SCOPE, ...?)} f Function to call. * @param {number} interval Interval over which to rate-limit. The function will * only be called once per interval, and ignored for the remainer of the * interval. * @param {SCOPE=} opt_scope Object in whose scope to call the function. * @return {function(...?): undefined} Wrapped function. * @template SCOPE */ goog.functions.rateLimit = function(f, interval, opt_scope) { var timeout = 0; var handleTimeout = function() { timeout = 0; }; return /** @type {function(...?)} */ (function(var_args) { if (!timeout) { timeout = goog.global.setTimeout(handleTimeout, interval); f.apply(opt_scope, arguments); } }); }; //javascript/closure/string/typedstring.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. goog.provide('goog.string.TypedString'); /** * Wrapper for strings that conform to a data type or language. * * Implementations of this interface are wrappers for strings, and typically * associate a type contract with the wrapped string. Concrete implementations * of this interface may choose to implement additional run-time type checking, * see for example `goog.html.SafeHtml`. If available, client code that * needs to ensure type membership of an object should use the type's function * to assert type membership, such as `goog.html.SafeHtml.unwrap`. * @interface */ goog.string.TypedString = function() {}; /** * Interface marker of the TypedString interface. * * This property can be used to determine at runtime whether or not an object * implements this interface. All implementations of this interface set this * property to `true`. * @type {boolean} */ goog.string.TypedString.prototype.implementsGoogStringTypedString; /** * Retrieves this wrapped string's value. * @return {string} The wrapped string's value. */ goog.string.TypedString.prototype.getTypedStringValue; //javascript/closure/string/const.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. goog.provide('goog.string.Const'); goog.require('goog.asserts'); goog.require('goog.string.TypedString'); /** * Wrapper for compile-time-constant strings. * * Const is a wrapper for strings that can only be created from program * constants (i.e., string literals). This property relies on a custom Closure * compiler check that `goog.string.Const.from` is only invoked on * compile-time-constant expressions. * * Const is useful in APIs whose correct and secure use requires that certain * arguments are not attacker controlled: Compile-time constants are inherently * under the control of the application and not under control of external * attackers, and hence are safe to use in such contexts. * * Instances of this type must be created via its factory method * `goog.string.Const.from` and not by invoking its constructor. The * constructor intentionally takes no parameters and the type is immutable; * hence only a default instance corresponding to the empty string can be * obtained via constructor invocation. * * @see goog.string.Const#from * @constructor * @final * @struct * @implements {goog.string.TypedString} */ goog.string.Const = function() { /** * The wrapped value of this Const object. The field has a purposely ugly * name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.string.Const#unwrap * @const {!Object} * @private */ this.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ = goog.string.Const.TYPE_MARKER_; }; /** * @override * @const */ goog.string.Const.prototype.implementsGoogStringTypedString = true; /** * Returns this Const's value a string. * * IMPORTANT: In code where it is security-relevant that an object's type is * indeed `goog.string.Const`, use `goog.string.Const.unwrap` * instead of this method. * * @see goog.string.Const#unwrap * @override */ goog.string.Const.prototype.getTypedStringValue = function() { return this.stringConstValueWithSecurityContract__googStringSecurityPrivate_; }; /** * Returns a debug-string representation of this value. * * To obtain the actual string value wrapped inside an object of this type, * use `goog.string.Const.unwrap`. * * @see goog.string.Const#unwrap * @override */ goog.string.Const.prototype.toString = function() { return 'Const{' + this.stringConstValueWithSecurityContract__googStringSecurityPrivate_ + '}'; }; /** * Performs a runtime check that the provided object is indeed an instance * of `goog.string.Const`, and returns its value. * @param {!goog.string.Const} stringConst The object to extract from. * @return {string} The Const object's contained string, unless the run-time * type check fails. In that case, `unwrap` returns an innocuous * string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.string.Const.unwrap = function(stringConst) { // Perform additional run-time type-checking to ensure that stringConst is // indeed an instance of the expected type. This provides some additional // protection against security bugs due to application code that disables type // checks. if (stringConst instanceof goog.string.Const && stringConst.constructor === goog.string.Const && stringConst.STRING_CONST_TYPE_MARKER__GOOG_STRING_SECURITY_PRIVATE_ === goog.string.Const.TYPE_MARKER_) { return stringConst .stringConstValueWithSecurityContract__googStringSecurityPrivate_; } else { goog.asserts.fail( 'expected object of type Const, got \'' + stringConst + '\''); return 'type_error:Const'; } }; /** * Creates a Const object from a compile-time constant string. * * It is illegal to invoke this function on an expression whose * compile-time-contant value cannot be determined by the Closure compiler. * * Correct invocations include, * <pre> * var s = goog.string.Const.from('hello'); * var t = goog.string.Const.from('hello' + 'world'); * </pre> * * In contrast, the following are illegal: * <pre> * var s = goog.string.Const.from(getHello()); * var t = goog.string.Const.from('hello' + world); * </pre> * * @param {string} s A constant string from which to create a Const. * @return {!goog.string.Const} A Const object initialized to stringConst. */ goog.string.Const.from = function(s) { return goog.string.Const.create__googStringSecurityPrivate_(s); }; /** * Type marker for the Const type, used to implement additional run-time * type checking. * @const {!Object} * @private */ goog.string.Const.TYPE_MARKER_ = {}; /** * Utility method to create Const instances. * @param {string} s The string to initialize the Const object with. * @return {!goog.string.Const} The initialized Const object. * @private */ goog.string.Const.create__googStringSecurityPrivate_ = function(s) { var stringConst = new goog.string.Const(); stringConst.stringConstValueWithSecurityContract__googStringSecurityPrivate_ = s; return stringConst; }; /** * A Const instance wrapping the empty string. * @const {!goog.string.Const} */ goog.string.Const.EMPTY = goog.string.Const.from(''); //javascript/closure/html/safescript.js // Copyright 2014 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The SafeScript type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.SafeScript'); goog.require('goog.asserts'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A string-like object which represents JavaScript code and that carries the * security type contract that its value, as a string, will not cause execution * of unconstrained attacker controlled code (XSS) when evaluated as JavaScript * in a browser. * * Instances of this type must be created via the factory method * `goog.html.SafeScript.fromConstant` and not by invoking its * constructor. The constructor intentionally takes no parameters and the type * is immutable; hence only a default instance corresponding to the empty string * can be obtained via constructor invocation. * * A SafeScript's string representation can safely be interpolated as the * content of a script element within HTML. The SafeScript string should not be * escaped before interpolation. * * Note that the SafeScript might contain text that is attacker-controlled but * that text should have been interpolated with appropriate escaping, * sanitization and/or validation into the right location in the script, such * that it is highly constrained in its effect (for example, it had to match a * set of whitelisted words). * * A SafeScript can be constructed via security-reviewed unchecked * conversions. In this case producers of SafeScript must ensure themselves that * the SafeScript does not contain unsafe script. Note in particular that * {@code &lt;} is dangerous, even when inside JavaScript strings, and so should * always be forbidden or JavaScript escaped in user controlled input. For * example, if {@code &lt;/script&gt;&lt;script&gt;evil&lt;/script&gt;"} were * interpolated inside a JavaScript string, it would break out of the context * of the original script element and `evil` would execute. Also note * that within an HTML script (raw text) element, HTML character references, * such as "&lt;" are not allowed. See * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements. * * @see goog.html.SafeScript#fromConstant * @constructor * @final * @struct * @implements {goog.string.TypedString} */ goog.html.SafeScript = function() { /** * The contained value of this SafeScript. The field has a purposely * ugly name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.SafeScript#unwrap * @const {!Object} * @private */ this.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; }; /** * @override * @const */ goog.html.SafeScript.prototype.implementsGoogStringTypedString = true; /** * Type marker for the SafeScript type, used to implement additional * run-time type checking. * @const {!Object} * @private */ goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Creates a SafeScript object from a compile-time constant string. * * @param {!goog.string.Const} script A compile-time-constant string from which * to create a SafeScript. * @return {!goog.html.SafeScript} A SafeScript object initialized to * `script`. */ goog.html.SafeScript.fromConstant = function(script) { var scriptString = goog.string.Const.unwrap(script); if (scriptString.length === 0) { return goog.html.SafeScript.EMPTY; } return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( scriptString); }; /** * Creates a SafeScript from a compile-time constant string but with arguments * that can vary at run-time. The code argument should be formatted as an * inline function (see example below). The arguments will be JSON-encoded and * provided as input to the function specified in code. * * Example Usage: * * let safeScript = SafeScript.fromConstantAndArgs( * Const.from('function(arg1, arg2) { doSomething(arg1, arg2); }'), * arg1, * arg2); * * This produces a SafeScript equivalent to the following: * * (function(arg1, arg2) { doSomething(arg1, arg2); })("value1", "value2"); * * @param {!goog.string.Const} code * @param {...*} var_args * @return {!goog.html.SafeScript} */ goog.html.SafeScript.fromConstantAndArgs = function(code, var_args) { var args = []; for (var i = 1; i < arguments.length; i++) { args.push(goog.html.SafeScript.stringify_(arguments[i])); } return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( '(' + goog.string.Const.unwrap(code) + ')(' + args.join(', ') + ');'); }; /** * Returns this SafeScript's value as a string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `SafeScript`, use `goog.html.SafeScript.unwrap` instead of * this method. If in doubt, assume that it's security relevant. In particular, * note that goog.html functions which return a goog.html type do not guarantee * the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml * // instanceof goog.html.SafeHtml. * </pre> * * @see goog.html.SafeScript#unwrap * @override */ goog.html.SafeScript.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseSafeScriptWrappedValue_; }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a SafeScript, use * `goog.html.SafeScript.unwrap`. * * @see goog.html.SafeScript#unwrap * @override */ goog.html.SafeScript.prototype.toString = function() { return 'SafeScript{' + this.privateDoNotAccessOrElseSafeScriptWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a * SafeScript object, and returns its value. * * @param {!goog.html.SafeScript} safeScript The object to extract from. * @return {string} The safeScript object's contained string, unless * the run-time type check fails. In that case, `unwrap` returns an * innocuous string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.SafeScript.unwrap = function(safeScript) { // Perform additional Run-time type-checking to ensure that // safeScript is indeed an instance of the expected type. This // provides some additional protection against security bugs due to // application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (safeScript instanceof goog.html.SafeScript && safeScript.constructor === goog.html.SafeScript && safeScript.SAFE_SCRIPT_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeScript.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return safeScript.privateDoNotAccessOrElseSafeScriptWrappedValue_; } else { goog.asserts.fail('expected object of type SafeScript, got \'' + safeScript + '\' of type ' + goog.typeOf(safeScript)); return 'type_error:SafeScript'; } }; /** * Converts the given value to a embeddabel JSON string and returns it. The * resulting string can be embedded in HTML because the '<' character is * encoded. * * @param {*} val * @return {!string} * @private */ goog.html.SafeScript.stringify_ = function(val) { var json = JSON.stringify(val); return json.replace(/</g, '\\x3c'); }; /** * Package-internal utility method to create SafeScript instances. * * @param {string} script The string to initialize the SafeScript object with. * @return {!goog.html.SafeScript} The initialized SafeScript object. * @package */ goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse = function(script) { return new goog.html.SafeScript().initSecurityPrivateDoNotAccessOrElse_( script); }; /** * Called from createSafeScriptSecurityPrivateDoNotAccessOrElse(). This * method exists only so that the compiler can dead code eliminate static * fields (like EMPTY) when they're not accessed. * @param {string} script * @return {!goog.html.SafeScript} * @private */ goog.html.SafeScript.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( script) { this.privateDoNotAccessOrElseSafeScriptWrappedValue_ = script; return this; }; /** * A SafeScript instance corresponding to the empty string. * @const {!goog.html.SafeScript} */ goog.html.SafeScript.EMPTY = goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse(''); //javascript/closure/i18n/bidi.js // Copyright 2007 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utility functions for supporting Bidi issues. */ /** * Namespace for bidi supporting functions. */ goog.provide('goog.i18n.bidi'); goog.provide('goog.i18n.bidi.Dir'); goog.provide('goog.i18n.bidi.DirectionalString'); goog.provide('goog.i18n.bidi.Format'); /** * @define {boolean} FORCE_RTL forces the {@link goog.i18n.bidi.IS_RTL} constant * to say that the current locale is a RTL locale. This should only be used * if you want to override the default behavior for deciding whether the * current locale is RTL or not. * * {@see goog.i18n.bidi.IS_RTL} */ goog.define('goog.i18n.bidi.FORCE_RTL', false); /** * Constant that defines whether or not the current locale is a RTL locale. * If {@link goog.i18n.bidi.FORCE_RTL} is not true, this constant will default * to check that {@link goog.LOCALE} is one of a few major RTL locales. * * <p>This is designed to be a maximally efficient compile-time constant. For * example, for the default goog.LOCALE, compiling * "if (goog.i18n.bidi.IS_RTL) alert('rtl') else {}" should produce no code. It * is this design consideration that limits the implementation to only * supporting a few major RTL locales, as opposed to the broader repertoire of * something like goog.i18n.bidi.isRtlLanguage. * * <p>Since this constant refers to the directionality of the locale, it is up * to the caller to determine if this constant should also be used for the * direction of the UI. * * {@see goog.LOCALE} * * @type {boolean} * * TODO(user): write a test that checks that this is a compile-time constant. */ goog.i18n.bidi.IS_RTL = goog.i18n.bidi.FORCE_RTL || ((goog.LOCALE.substring(0, 2).toLowerCase() == 'ar' || goog.LOCALE.substring(0, 2).toLowerCase() == 'fa' || goog.LOCALE.substring(0, 2).toLowerCase() == 'he' || goog.LOCALE.substring(0, 2).toLowerCase() == 'iw' || goog.LOCALE.substring(0, 2).toLowerCase() == 'ps' || goog.LOCALE.substring(0, 2).toLowerCase() == 'sd' || goog.LOCALE.substring(0, 2).toLowerCase() == 'ug' || goog.LOCALE.substring(0, 2).toLowerCase() == 'ur' || goog.LOCALE.substring(0, 2).toLowerCase() == 'yi') && (goog.LOCALE.length == 2 || goog.LOCALE.substring(2, 3) == '-' || goog.LOCALE.substring(2, 3) == '_')) || (goog.LOCALE.length >= 3 && goog.LOCALE.substring(0, 3).toLowerCase() == 'ckb' && (goog.LOCALE.length == 3 || goog.LOCALE.substring(3, 4) == '-' || goog.LOCALE.substring(3, 4) == '_')); /** * Unicode formatting characters and directionality string constants. * @enum {string} */ goog.i18n.bidi.Format = { /** Unicode "Left-To-Right Embedding" (LRE) character. */ LRE: '\u202A', /** Unicode "Right-To-Left Embedding" (RLE) character. */ RLE: '\u202B', /** Unicode "Pop Directional Formatting" (PDF) character. */ PDF: '\u202C', /** Unicode "Left-To-Right Mark" (LRM) character. */ LRM: '\u200E', /** Unicode "Right-To-Left Mark" (RLM) character. */ RLM: '\u200F' }; /** * Directionality enum. * @enum {number} */ goog.i18n.bidi.Dir = { /** * Left-to-right. */ LTR: 1, /** * Right-to-left. */ RTL: -1, /** * Neither left-to-right nor right-to-left. */ NEUTRAL: 0 }; /** * 'right' string constant. * @type {string} */ goog.i18n.bidi.RIGHT = 'right'; /** * 'left' string constant. * @type {string} */ goog.i18n.bidi.LEFT = 'left'; /** * 'left' if locale is RTL, 'right' if not. * @type {string} */ goog.i18n.bidi.I18N_RIGHT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.LEFT : goog.i18n.bidi.RIGHT; /** * 'right' if locale is RTL, 'left' if not. * @type {string} */ goog.i18n.bidi.I18N_LEFT = goog.i18n.bidi.IS_RTL ? goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT; /** * Convert a directionality given in various formats to a goog.i18n.bidi.Dir * constant. Useful for interaction with different standards of directionality * representation. * * @param {goog.i18n.bidi.Dir|number|boolean|null} givenDir Directionality given * in one of the following formats: * 1. A goog.i18n.bidi.Dir constant. * 2. A number (positive = LTR, negative = RTL, 0 = neutral). * 3. A boolean (true = RTL, false = LTR). * 4. A null for unknown directionality. * @param {boolean=} opt_noNeutral Whether a givenDir of zero or * goog.i18n.bidi.Dir.NEUTRAL should be treated as null, i.e. unknown, in * order to preserve legacy behavior. * @return {?goog.i18n.bidi.Dir} A goog.i18n.bidi.Dir constant matching the * given directionality. If given null, returns null (i.e. unknown). */ goog.i18n.bidi.toDir = function(givenDir, opt_noNeutral) { if (typeof givenDir == 'number') { // This includes the non-null goog.i18n.bidi.Dir case. return givenDir > 0 ? goog.i18n.bidi.Dir.LTR : givenDir < 0 ? goog.i18n.bidi.Dir.RTL : opt_noNeutral ? null : goog.i18n.bidi.Dir.NEUTRAL; } else if (givenDir == null) { return null; } else { // Must be typeof givenDir == 'boolean'. return givenDir ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR; } }; /** * A practical pattern to identify strong LTR characters. This pattern is not * theoretically correct according to the Unicode standard. It is simplified for * performance and small code size. * @type {string} * @private */ goog.i18n.bidi.ltrChars_ = 'A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02B8\u0300-\u0590\u0800-\u1FFF' + '\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF'; /** * A practical pattern to identify strong RTL character. This pattern is not * theoretically correct according to the Unicode standard. It is simplified * for performance and small code size. * @type {string} * @private */ goog.i18n.bidi.rtlChars_ = '\u0591-\u06EF\u06FA-\u07FF\u200F\uFB1D-\uFDFF\uFE70-\uFEFC'; /** * Simplified regular expression for an HTML tag (opening or closing) or an HTML * escape. We might want to skip over such expressions when estimating the text * directionality. * @type {RegExp} * @private */ goog.i18n.bidi.htmlSkipReg_ = /<[^>]*>|&[^;]+;/g; /** * Returns the input text with spaces instead of HTML tags or HTML escapes, if * opt_isStripNeeded is true. Else returns the input as is. * Useful for text directionality estimation. * Note: the function should not be used in other contexts; it is not 100% * correct, but rather a good-enough implementation for directionality * estimation purposes. * @param {string} str The given string. * @param {boolean=} opt_isStripNeeded Whether to perform the stripping. * Default: false (to retain consistency with calling functions). * @return {string} The given string cleaned of HTML tags / escapes. * @private */ goog.i18n.bidi.stripHtmlIfNeeded_ = function(str, opt_isStripNeeded) { return opt_isStripNeeded ? str.replace(goog.i18n.bidi.htmlSkipReg_, '') : str; }; /** * Regular expression to check for RTL characters. * @type {RegExp} * @private */ goog.i18n.bidi.rtlCharReg_ = new RegExp('[' + goog.i18n.bidi.rtlChars_ + ']'); /** * Regular expression to check for LTR characters. * @type {RegExp} * @private */ goog.i18n.bidi.ltrCharReg_ = new RegExp('[' + goog.i18n.bidi.ltrChars_ + ']'); /** * Test whether the given string has any RTL characters in it. * @param {string} str The given string that need to be tested. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether the string contains RTL characters. */ goog.i18n.bidi.hasAnyRtl = function(str, opt_isHtml) { return goog.i18n.bidi.rtlCharReg_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Test whether the given string has any RTL characters in it. * @param {string} str The given string that need to be tested. * @return {boolean} Whether the string contains RTL characters. * @deprecated Use hasAnyRtl. */ goog.i18n.bidi.hasRtlChar = goog.i18n.bidi.hasAnyRtl; /** * Test whether the given string has any LTR characters in it. * @param {string} str The given string that need to be tested. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether the string contains LTR characters. */ goog.i18n.bidi.hasAnyLtr = function(str, opt_isHtml) { return goog.i18n.bidi.ltrCharReg_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Regular expression pattern to check if the first character in the string * is LTR. * @type {RegExp} * @private */ goog.i18n.bidi.ltrRe_ = new RegExp('^[' + goog.i18n.bidi.ltrChars_ + ']'); /** * Regular expression pattern to check if the first character in the string * is RTL. * @type {RegExp} * @private */ goog.i18n.bidi.rtlRe_ = new RegExp('^[' + goog.i18n.bidi.rtlChars_ + ']'); /** * Check if the first character in the string is RTL or not. * @param {string} str The given string that need to be tested. * @return {boolean} Whether the first character in str is an RTL char. */ goog.i18n.bidi.isRtlChar = function(str) { return goog.i18n.bidi.rtlRe_.test(str); }; /** * Check if the first character in the string is LTR or not. * @param {string} str The given string that need to be tested. * @return {boolean} Whether the first character in str is an LTR char. */ goog.i18n.bidi.isLtrChar = function(str) { return goog.i18n.bidi.ltrRe_.test(str); }; /** * Check if the first character in the string is neutral or not. * @param {string} str The given string that need to be tested. * @return {boolean} Whether the first character in str is a neutral char. */ goog.i18n.bidi.isNeutralChar = function(str) { return !goog.i18n.bidi.isLtrChar(str) && !goog.i18n.bidi.isRtlChar(str); }; /** * Regular expressions to check if a piece of text is of LTR directionality * on first character with strong directionality. * @type {RegExp} * @private */ goog.i18n.bidi.ltrDirCheckRe_ = new RegExp( '^[^' + goog.i18n.bidi.rtlChars_ + ']*[' + goog.i18n.bidi.ltrChars_ + ']'); /** * Regular expressions to check if a piece of text is of RTL directionality * on first character with strong directionality. * @type {RegExp} * @private */ goog.i18n.bidi.rtlDirCheckRe_ = new RegExp( '^[^' + goog.i18n.bidi.ltrChars_ + ']*[' + goog.i18n.bidi.rtlChars_ + ']'); /** * Check whether the first strongly directional character (if any) is RTL. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether RTL directionality is detected using the first * strongly-directional character method. */ goog.i18n.bidi.startsWithRtl = function(str, opt_isHtml) { return goog.i18n.bidi.rtlDirCheckRe_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Check whether the first strongly directional character (if any) is RTL. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether RTL directionality is detected using the first * strongly-directional character method. * @deprecated Use startsWithRtl. */ goog.i18n.bidi.isRtlText = goog.i18n.bidi.startsWithRtl; /** * Check whether the first strongly directional character (if any) is LTR. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether LTR directionality is detected using the first * strongly-directional character method. */ goog.i18n.bidi.startsWithLtr = function(str, opt_isHtml) { return goog.i18n.bidi.ltrDirCheckRe_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Check whether the first strongly directional character (if any) is LTR. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether LTR directionality is detected using the first * strongly-directional character method. * @deprecated Use startsWithLtr. */ goog.i18n.bidi.isLtrText = goog.i18n.bidi.startsWithLtr; /** * Regular expression to check if a string looks like something that must * always be LTR even in RTL text, e.g. a URL. When estimating the * directionality of text containing these, we treat these as weakly LTR, * like numbers. * @type {RegExp} * @private */ goog.i18n.bidi.isRequiredLtrRe_ = /^http:\/\/.*/; /** * Check whether the input string either contains no strongly directional * characters or looks like a url. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether neutral directionality is detected. */ goog.i18n.bidi.isNeutralText = function(str, opt_isHtml) { str = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml); return goog.i18n.bidi.isRequiredLtrRe_.test(str) || !goog.i18n.bidi.hasAnyLtr(str) && !goog.i18n.bidi.hasAnyRtl(str); }; /** * Regular expressions to check if the last strongly-directional character in a * piece of text is LTR. * @type {RegExp} * @private */ goog.i18n.bidi.ltrExitDirCheckRe_ = new RegExp( '[' + goog.i18n.bidi.ltrChars_ + '][^' + goog.i18n.bidi.rtlChars_ + ']*$'); /** * Regular expressions to check if the last strongly-directional character in a * piece of text is RTL. * @type {RegExp} * @private */ goog.i18n.bidi.rtlExitDirCheckRe_ = new RegExp( '[' + goog.i18n.bidi.rtlChars_ + '][^' + goog.i18n.bidi.ltrChars_ + ']*$'); /** * Check if the exit directionality a piece of text is LTR, i.e. if the last * strongly-directional character in the string is LTR. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether LTR exit directionality was detected. */ goog.i18n.bidi.endsWithLtr = function(str, opt_isHtml) { return goog.i18n.bidi.ltrExitDirCheckRe_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Check if the exit directionality a piece of text is LTR, i.e. if the last * strongly-directional character in the string is LTR. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether LTR exit directionality was detected. * @deprecated Use endsWithLtr. */ goog.i18n.bidi.isLtrExitText = goog.i18n.bidi.endsWithLtr; /** * Check if the exit directionality a piece of text is RTL, i.e. if the last * strongly-directional character in the string is RTL. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether RTL exit directionality was detected. */ goog.i18n.bidi.endsWithRtl = function(str, opt_isHtml) { return goog.i18n.bidi.rtlExitDirCheckRe_.test( goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml)); }; /** * Check if the exit directionality a piece of text is RTL, i.e. if the last * strongly-directional character in the string is RTL. * @param {string} str String being checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether RTL exit directionality was detected. * @deprecated Use endsWithRtl. */ goog.i18n.bidi.isRtlExitText = goog.i18n.bidi.endsWithRtl; /** * A regular expression for matching right-to-left language codes. * See {@link #isRtlLanguage} for the design. * @type {RegExp} * @private */ goog.i18n.bidi.rtlLocalesRe_ = new RegExp( '^(ar|ckb|dv|he|iw|fa|nqo|ps|sd|ug|ur|yi|' + '.*[-_](Arab|Hebr|Thaa|Nkoo|Tfng))' + '(?!.*[-_](Latn|Cyrl)($|-|_))($|-|_)', 'i'); /** * Check if a BCP 47 / III language code indicates an RTL language, i.e. either: * - a language code explicitly specifying one of the right-to-left scripts, * e.g. "az-Arab", or<p> * - a language code specifying one of the languages normally written in a * right-to-left script, e.g. "fa" (Farsi), except ones explicitly specifying * Latin or Cyrillic script (which are the usual LTR alternatives).<p> * The list of right-to-left scripts appears in the 100-199 range in * http://www.unicode.org/iso15924/iso15924-num.html, of which Arabic and * Hebrew are by far the most widely used. We also recognize Thaana, N'Ko, and * Tifinagh, which also have significant modern usage. The rest (Syriac, * Samaritan, Mandaic, etc.) seem to have extremely limited or no modern usage * and are not recognized to save on code size. * The languages usually written in a right-to-left script are taken as those * with Suppress-Script: Hebr|Arab|Thaa|Nkoo|Tfng in * http://www.iana.org/assignments/language-subtag-registry, * as well as Central (or Sorani) Kurdish (ckb), Sindhi (sd) and Uyghur (ug). * Other subtags of the language code, e.g. regions like EG (Egypt), are * ignored. * @param {string} lang BCP 47 (a.k.a III) language code. * @return {boolean} Whether the language code is an RTL language. */ goog.i18n.bidi.isRtlLanguage = function(lang) { return goog.i18n.bidi.rtlLocalesRe_.test(lang); }; /** * Regular expression for bracket guard replacement in text. * @type {RegExp} * @private */ goog.i18n.bidi.bracketGuardTextRe_ = /(\(.*?\)+)|(\[.*?\]+)|(\{.*?\}+)|(<.*?>+)/g; /** * Apply bracket guard using LRM and RLM. This is to address the problem of * messy bracket display frequently happens in RTL layout. * This function works for plain text, not for HTML. In HTML, the opening * bracket might be in a different context than the closing bracket (such as * an attribute value). * @param {string} s The string that need to be processed. * @param {boolean=} opt_isRtlContext specifies default direction (usually * direction of the UI). * @return {string} The processed string, with all bracket guarded. */ goog.i18n.bidi.guardBracketInText = function(s, opt_isRtlContext) { var useRtl = opt_isRtlContext === undefined ? goog.i18n.bidi.hasAnyRtl(s) : opt_isRtlContext; var mark = useRtl ? goog.i18n.bidi.Format.RLM : goog.i18n.bidi.Format.LRM; return s.replace(goog.i18n.bidi.bracketGuardTextRe_, mark + '$&' + mark); }; /** * Enforce the html snippet in RTL directionality regardless overall context. * If the html piece was enclosed by tag, dir will be applied to existing * tag, otherwise a span tag will be added as wrapper. For this reason, if * html snippet start with with tag, this tag must enclose the whole piece. If * the tag already has a dir specified, this new one will override existing * one in behavior (tested on FF and IE). * @param {string} html The string that need to be processed. * @return {string} The processed string, with directionality enforced to RTL. */ goog.i18n.bidi.enforceRtlInHtml = function(html) { if (html.charAt(0) == '<') { return html.replace(/<\w+/, '$& dir=rtl'); } // '\n' is important for FF so that it won't incorrectly merge span groups return '\n<span dir=rtl>' + html + '</span>'; }; /** * Enforce RTL on both end of the given text piece using unicode BiDi formatting * characters RLE and PDF. * @param {string} text The piece of text that need to be wrapped. * @return {string} The wrapped string after process. */ goog.i18n.bidi.enforceRtlInText = function(text) { return goog.i18n.bidi.Format.RLE + text + goog.i18n.bidi.Format.PDF; }; /** * Enforce the html snippet in RTL directionality regardless overall context. * If the html piece was enclosed by tag, dir will be applied to existing * tag, otherwise a span tag will be added as wrapper. For this reason, if * html snippet start with with tag, this tag must enclose the whole piece. If * the tag already has a dir specified, this new one will override existing * one in behavior (tested on FF and IE). * @param {string} html The string that need to be processed. * @return {string} The processed string, with directionality enforced to RTL. */ goog.i18n.bidi.enforceLtrInHtml = function(html) { if (html.charAt(0) == '<') { return html.replace(/<\w+/, '$& dir=ltr'); } // '\n' is important for FF so that it won't incorrectly merge span groups return '\n<span dir=ltr>' + html + '</span>'; }; /** * Enforce LTR on both end of the given text piece using unicode BiDi formatting * characters LRE and PDF. * @param {string} text The piece of text that need to be wrapped. * @return {string} The wrapped string after process. */ goog.i18n.bidi.enforceLtrInText = function(text) { return goog.i18n.bidi.Format.LRE + text + goog.i18n.bidi.Format.PDF; }; /** * Regular expression to find dimensions such as "padding: .3 0.4ex 5px 6;" * @type {RegExp} * @private */ goog.i18n.bidi.dimensionsRe_ = /:\s*([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)\s+([.\d][.\w]*)/g; /** * Regular expression for left. * @type {RegExp} * @private */ goog.i18n.bidi.leftRe_ = /left/gi; /** * Regular expression for right. * @type {RegExp} * @private */ goog.i18n.bidi.rightRe_ = /right/gi; /** * Placeholder regular expression for swapping. * @type {RegExp} * @private */ goog.i18n.bidi.tempRe_ = /%%%%/g; /** * Swap location parameters and 'left'/'right' in CSS specification. The * processed string will be suited for RTL layout. Though this function can * cover most cases, there are always exceptions. It is suggested to put * those exceptions in separate group of CSS string. * @param {string} cssStr CSS spefication string. * @return {string} Processed CSS specification string. */ goog.i18n.bidi.mirrorCSS = function(cssStr) { return cssStr . // reverse dimensions replace(goog.i18n.bidi.dimensionsRe_, ':$1 $4 $3 $2') .replace(goog.i18n.bidi.leftRe_, '%%%%') . // swap left and right replace(goog.i18n.bidi.rightRe_, goog.i18n.bidi.LEFT) .replace(goog.i18n.bidi.tempRe_, goog.i18n.bidi.RIGHT); }; /** * Regular expression for hebrew double quote substitution, finding quote * directly after hebrew characters. * @type {RegExp} * @private */ goog.i18n.bidi.doubleQuoteSubstituteRe_ = /([\u0591-\u05f2])"/g; /** * Regular expression for hebrew single quote substitution, finding quote * directly after hebrew characters. * @type {RegExp} * @private */ goog.i18n.bidi.singleQuoteSubstituteRe_ = /([\u0591-\u05f2])'/g; /** * Replace the double and single quote directly after a Hebrew character with * GERESH and GERSHAYIM. In such case, most likely that's user intention. * @param {string} str String that need to be processed. * @return {string} Processed string with double/single quote replaced. */ goog.i18n.bidi.normalizeHebrewQuote = function(str) { return str.replace(goog.i18n.bidi.doubleQuoteSubstituteRe_, '$1\u05f4') .replace(goog.i18n.bidi.singleQuoteSubstituteRe_, '$1\u05f3'); }; /** * Regular expression to split a string into "words" for directionality * estimation based on relative word counts. * @type {RegExp} * @private */ goog.i18n.bidi.wordSeparatorRe_ = /\s+/; /** * Regular expression to check if a string contains any numerals. Used to * differentiate between completely neutral strings and those containing * numbers, which are weakly LTR. * * Native Arabic digits (\u0660 - \u0669) are not included because although they * do flow left-to-right inside a number, this is the case even if the overall * directionality is RTL, and a mathematical expression using these digits is * supposed to flow right-to-left overall, including unary plus and minus * appearing to the right of a number, and this does depend on the overall * directionality being RTL. The digits used in Farsi (\u06F0 - \u06F9), on the * other hand, are included, since Farsi math (including unary plus and minus) * does flow left-to-right. * * @type {RegExp} * @private */ goog.i18n.bidi.hasNumeralsRe_ = /[\d\u06f0-\u06f9]/; /** * This constant controls threshold of RTL directionality. * @type {number} * @private */ goog.i18n.bidi.rtlDetectionThreshold_ = 0.40; /** * Estimates the directionality of a string based on relative word counts. * If the number of RTL words is above a certain percentage of the total number * of strongly directional words, returns RTL. * Otherwise, if any words are strongly or weakly LTR, returns LTR. * Otherwise, returns UNKNOWN, which is used to mean "neutral". * Numbers are counted as weakly LTR. * @param {string} str The string to be checked. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {goog.i18n.bidi.Dir} Estimated overall directionality of `str`. */ goog.i18n.bidi.estimateDirection = function(str, opt_isHtml) { var rtlCount = 0; var totalCount = 0; var hasWeaklyLtr = false; var tokens = goog.i18n.bidi.stripHtmlIfNeeded_(str, opt_isHtml) .split(goog.i18n.bidi.wordSeparatorRe_); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (goog.i18n.bidi.startsWithRtl(token)) { rtlCount++; totalCount++; } else if (goog.i18n.bidi.isRequiredLtrRe_.test(token)) { hasWeaklyLtr = true; } else if (goog.i18n.bidi.hasAnyLtr(token)) { totalCount++; } else if (goog.i18n.bidi.hasNumeralsRe_.test(token)) { hasWeaklyLtr = true; } } return totalCount == 0 ? (hasWeaklyLtr ? goog.i18n.bidi.Dir.LTR : goog.i18n.bidi.Dir.NEUTRAL) : (rtlCount / totalCount > goog.i18n.bidi.rtlDetectionThreshold_ ? goog.i18n.bidi.Dir.RTL : goog.i18n.bidi.Dir.LTR); }; /** * Check the directionality of a piece of text, return true if the piece of * text should be laid out in RTL direction. * @param {string} str The piece of text that need to be detected. * @param {boolean=} opt_isHtml Whether str is HTML / HTML-escaped. * Default: false. * @return {boolean} Whether this piece of text should be laid out in RTL. */ goog.i18n.bidi.detectRtlDirectionality = function(str, opt_isHtml) { return goog.i18n.bidi.estimateDirection(str, opt_isHtml) == goog.i18n.bidi.Dir.RTL; }; /** * Sets text input element's directionality and text alignment based on a * given directionality. Does nothing if the given directionality is unknown or * neutral. * @param {Element} element Input field element to set directionality to. * @param {goog.i18n.bidi.Dir|number|boolean|null} dir Desired directionality, * given in one of the following formats: * 1. A goog.i18n.bidi.Dir constant. * 2. A number (positive = LRT, negative = RTL, 0 = neutral). * 3. A boolean (true = RTL, false = LTR). * 4. A null for unknown directionality. */ goog.i18n.bidi.setElementDirAndAlign = function(element, dir) { if (element) { var htmlElement = /** @type {!HTMLElement} */ (element); dir = goog.i18n.bidi.toDir(dir); if (dir) { htmlElement.style.textAlign = dir == goog.i18n.bidi.Dir.RTL ? goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT; htmlElement.dir = dir == goog.i18n.bidi.Dir.RTL ? 'rtl' : 'ltr'; } } }; /** * Sets element dir based on estimated directionality of the given text. * @param {!Element} element * @param {string} text */ goog.i18n.bidi.setElementDirByTextDirectionality = function(element, text) { var htmlElement = /** @type {!HTMLElement} */ (element); switch (goog.i18n.bidi.estimateDirection(text)) { case (goog.i18n.bidi.Dir.LTR): htmlElement.dir = 'ltr'; break; case (goog.i18n.bidi.Dir.RTL): htmlElement.dir = 'rtl'; break; default: // Default for no direction, inherit from document. htmlElement.removeAttribute('dir'); } }; /** * Strings that have an (optional) known direction. * * Implementations of this interface are string-like objects that carry an * attached direction, if known. * @interface */ goog.i18n.bidi.DirectionalString = function() {}; /** * Interface marker of the DirectionalString interface. * * This property can be used to determine at runtime whether or not an object * implements this interface. All implementations of this interface set this * property to `true`. * @type {boolean} */ goog.i18n.bidi.DirectionalString.prototype .implementsGoogI18nBidiDirectionalString; /** * Retrieves this object's known direction (if any). * @return {?goog.i18n.bidi.Dir} The known direction. Null if unknown. */ goog.i18n.bidi.DirectionalString.prototype.getDirection; //javascript/closure/html/trustedresourceurl.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The TrustedResourceUrl type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.TrustedResourceUrl'); goog.require('goog.asserts'); goog.require('goog.i18n.bidi.Dir'); goog.require('goog.i18n.bidi.DirectionalString'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A URL which is under application control and from which script, CSS, and * other resources that represent executable code, can be fetched. * * Given that the URL can only be constructed from strings under application * control and is used to load resources, bugs resulting in a malformed URL * should not have a security impact and are likely to be easily detectable * during testing. Given the wide number of non-RFC compliant URLs in use, * stricter validation could prevent some applications from being able to use * this type. * * Instances of this type must be created via the factory method, * (`fromConstant`, `fromConstants`, `format` or * `formatWithParams`), and not by invoking its constructor. The constructor * intentionally takes no parameters and the type is immutable; hence only a * default instance corresponding to the empty string can be obtained via * constructor invocation. * * @see goog.html.TrustedResourceUrl#fromConstant * @constructor * @final * @struct * @implements {goog.i18n.bidi.DirectionalString} * @implements {goog.string.TypedString} */ goog.html.TrustedResourceUrl = function() { /** * The contained value of this TrustedResourceUrl. The field has a purposely * ugly name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.TrustedResourceUrl#unwrap * @const {!Object} * @private */ this.TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; }; /** * @override * @const */ goog.html.TrustedResourceUrl.prototype.implementsGoogStringTypedString = true; /** * Returns this TrustedResourceUrl's value as a string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `TrustedResourceUrl`, use * `goog.html.TrustedResourceUrl.unwrap` instead of this method. If in * doubt, assume that it's security relevant. In particular, note that * goog.html functions which return a goog.html type do not guarantee that * the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof * // goog.html.SafeHtml. * </pre> * * @see goog.html.TrustedResourceUrl#unwrap * @override */ goog.html.TrustedResourceUrl.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; }; /** * @override * @const */ goog.html.TrustedResourceUrl.prototype.implementsGoogI18nBidiDirectionalString = true; /** * Returns this URLs directionality, which is always `LTR`. * @override */ goog.html.TrustedResourceUrl.prototype.getDirection = function() { return goog.i18n.bidi.Dir.LTR; }; /** * Creates a new TrustedResourceUrl with params added to URL. * @param {!Object<string, *>} params Parameters to add to URL. Parameters with * value `null` or `undefined` are skipped. Both keys and values * are encoded. If the value is an array then the same parameter is added * for every element in the array. Note that JavaScript doesn't guarantee * the order of values in an object which might result in non-deterministic * order of the parameters. However, browsers currently preserve the order. * @return {!goog.html.TrustedResourceUrl} New TrustedResourceUrl with params. */ goog.html.TrustedResourceUrl.prototype.cloneWithParams = function(params) { var url = goog.html.TrustedResourceUrl.unwrap(this); var separator = /\?/.test(url) ? '&' : '?'; for (var key in params) { var values = goog.isArray(params[key]) ? /** @type {!Array<*>} */ (params[key]) : [params[key]]; for (var i = 0; i < values.length; i++) { if (values[i] == null) { continue; } url += separator + encodeURIComponent(key) + '=' + encodeURIComponent(String(values[i])); separator = '&'; } } return goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url); }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a TrustedResourceUrl, use * `goog.html.TrustedResourceUrl.unwrap`. * * @see goog.html.TrustedResourceUrl#unwrap * @override */ goog.html.TrustedResourceUrl.prototype.toString = function() { return 'TrustedResourceUrl{' + this.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a * TrustedResourceUrl object, and returns its value. * * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl The object to * extract from. * @return {string} The trustedResourceUrl object's contained string, unless * the run-time type check fails. In that case, `unwrap` returns an * innocuous string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.TrustedResourceUrl.unwrap = function(trustedResourceUrl) { // Perform additional Run-time type-checking to ensure that // trustedResourceUrl is indeed an instance of the expected type. This // provides some additional protection against security bugs due to // application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (trustedResourceUrl instanceof goog.html.TrustedResourceUrl && trustedResourceUrl.constructor === goog.html.TrustedResourceUrl && trustedResourceUrl .TRUSTED_RESOURCE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.TrustedResourceUrl .TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return trustedResourceUrl .privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_; } else { goog.asserts.fail('expected object of type TrustedResourceUrl, got \'' + trustedResourceUrl + '\' of type ' + goog.typeOf(trustedResourceUrl)); return 'type_error:TrustedResourceUrl'; } }; /** * Creates a TrustedResourceUrl from a format string and arguments. * * The arguments for interpolation into the format string map labels to values. * Values of type `goog.string.Const` are interpolated without modifcation. * Values of other types are cast to string and encoded with * encodeURIComponent. * * `%{<label>}` markers are used in the format string to indicate locations * to be interpolated with the valued mapped to the given label. `<label>` * must contain only alphanumeric and `_` characters. * * The format string must start with one of the following: * - `https://<origin>/` * - `//<origin>/` * - `/<pathStart>` * - `about:blank#` * * `<origin>` must contain only alphanumeric or any of the following: `-.:[]`. * `<pathStart>` is any character except `/` and `\`. * * Example usage: * * var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from( * 'https://www.google.com/search?q=%{query}'), {'query': searchTerm}); * * var url = goog.html.TrustedResourceUrl.format(goog.string.Const.from( * '//www.youtube.com/v/%{videoId}?hl=en&fs=1%{autoplay}'), { * 'videoId': videoId, * 'autoplay': opt_autoplay ? * goog.string.Const.from('&autoplay=1') : goog.string.Const.EMPTY * }); * * While this function can be used to create a TrustedResourceUrl from only * constants, fromConstant() and fromConstants() are generally preferable for * that purpose. * * @param {!goog.string.Const} format The format string. * @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping * of labels to values to be interpolated into the format string. * goog.string.Const values are interpolated without encoding. * @return {!goog.html.TrustedResourceUrl} * @throws {!Error} On an invalid format string or if a label used in the * the format string is not present in args. */ goog.html.TrustedResourceUrl.format = function(format, args) { var formatStr = goog.string.Const.unwrap(format); if (!goog.html.TrustedResourceUrl.BASE_URL_.test(formatStr)) { throw new Error('Invalid TrustedResourceUrl format: ' + formatStr); } var result = formatStr.replace( goog.html.TrustedResourceUrl.FORMAT_MARKER_, function(match, id) { if (!Object.prototype.hasOwnProperty.call(args, id)) { throw new Error( 'Found marker, "' + id + '", in format string, "' + formatStr + '", but no valid label mapping found ' + 'in args: ' + JSON.stringify(args)); } var arg = args[id]; if (arg instanceof goog.string.Const) { return goog.string.Const.unwrap(arg); } else { return encodeURIComponent(String(arg)); } }); return goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(result); }; /** * @private @const {!RegExp} */ goog.html.TrustedResourceUrl.FORMAT_MARKER_ = /%{(\w+)}/g; /** * The URL must be absolute, scheme-relative or path-absolute. So it must * start with: * - https:// followed by allowed origin characters. * - // followed by allowed origin characters. * - / not followed by / or \. There will only be an absolute path. * * Based on * https://url.spec.whatwg.org/commit-snapshots/56b74ce7cca8883eab62e9a12666e2fac665d03d/#url-parsing * an initial / which is not followed by another / or \ will end up in the "path * state" and from there it can only go to "fragment state" and "query state". * * We don't enforce a well-formed domain name. So '.' or '1.2' are valid. * That's ok because the origin comes from a compile-time constant. * * A regular expression is used instead of goog.uri for several reasons: * - Strictness. E.g. we don't want any userinfo component and we don't * want '/./, nor \' in the first path component. * - Small trusted base. goog.uri is generic and might need to change, * reasoning about all the ways it can parse a URL now and in the future * is error-prone. * - Code size. We expect many calls to .format(), many of which might * not be using goog.uri. * - Simplicity. Using goog.uri would likely not result in simpler nor shorter * code. * @private @const {!RegExp} */ goog.html.TrustedResourceUrl.BASE_URL_ = /^(?:https:)?\/\/[0-9a-z.:[\]-]+\/|^\/[^\/\\]|^about:blank#/i; /** * Formats the URL same as TrustedResourceUrl.format and then adds extra URL * parameters. * * Example usage: * * // Creates '//www.youtube.com/v/abc?autoplay=1' for videoId='abc' and * // opt_autoplay=1. Creates '//www.youtube.com/v/abc' for videoId='abc' * // and opt_autoplay=undefined. * var url = goog.html.TrustedResourceUrl.formatWithParams( * goog.string.Const.from('//www.youtube.com/v/%{videoId}'), * {'videoId': videoId}, * {'autoplay': opt_autoplay}); * * @param {!goog.string.Const} format The format string. * @param {!Object<string, (string|number|!goog.string.Const)>} args Mapping * of labels to values to be interpolated into the format string. * goog.string.Const values are interpolated without encoding. * @param {!Object<string, *>} params Parameters to add to URL. Parameters with * value `null` or `undefined` are skipped. Both keys and values * are encoded. If the value is an array then the same parameter is added * for every element in the array. Note that JavaScript doesn't guarantee * the order of values in an object which might result in non-deterministic * order of the parameters. However, browsers currently preserve the order. * @return {!goog.html.TrustedResourceUrl} * @throws {!Error} On an invalid format string or if a label used in the * the format string is not present in args. */ goog.html.TrustedResourceUrl.formatWithParams = function(format, args, params) { var url = goog.html.TrustedResourceUrl.format(format, args); return url.cloneWithParams(params); }; /** * Creates a TrustedResourceUrl object from a compile-time constant string. * * Compile-time constant strings are inherently program-controlled and hence * trusted. * * @param {!goog.string.Const} url A compile-time-constant string from which to * create a TrustedResourceUrl. * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object * initialized to `url`. */ goog.html.TrustedResourceUrl.fromConstant = function(url) { return goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse( goog.string.Const.unwrap(url)); }; /** * Creates a TrustedResourceUrl object from a compile-time constant strings. * * Compile-time constant strings are inherently program-controlled and hence * trusted. * * @param {!Array<!goog.string.Const>} parts Compile-time-constant strings from * which to create a TrustedResourceUrl. * @return {!goog.html.TrustedResourceUrl} A TrustedResourceUrl object * initialized to concatenation of `parts`. */ goog.html.TrustedResourceUrl.fromConstants = function(parts) { var unwrapped = ''; for (var i = 0; i < parts.length; i++) { unwrapped += goog.string.Const.unwrap(parts[i]); } return goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(unwrapped); }; /** * Type marker for the TrustedResourceUrl type, used to implement additional * run-time type checking. * @const {!Object} * @private */ goog.html.TrustedResourceUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Package-internal utility method to create TrustedResourceUrl instances. * * @param {string} url The string to initialize the TrustedResourceUrl object * with. * @return {!goog.html.TrustedResourceUrl} The initialized TrustedResourceUrl * object. * @package */ goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse = function(url) { var trustedResourceUrl = new goog.html.TrustedResourceUrl(); trustedResourceUrl.privateDoNotAccessOrElseTrustedResourceUrlWrappedValue_ = url; return trustedResourceUrl; }; //javascript/closure/html/safeurl.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The SafeUrl type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.SafeUrl'); goog.require('goog.asserts'); goog.require('goog.fs.url'); goog.require('goog.html.TrustedResourceUrl'); goog.require('goog.i18n.bidi.Dir'); goog.require('goog.i18n.bidi.DirectionalString'); goog.require('goog.string'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A string that is safe to use in URL context in DOM APIs and HTML documents. * * A SafeUrl is a string-like object that carries the security type contract * that its value as a string will not cause untrusted script execution * when evaluated as a hyperlink URL in a browser. * * Values of this type are guaranteed to be safe to use in URL/hyperlink * contexts, such as assignment to URL-valued DOM properties, in the sense that * the use will not result in a Cross-Site-Scripting vulnerability. Similarly, * SafeUrls can be interpolated into the URL context of an HTML template (e.g., * inside a href attribute). However, appropriate HTML-escaping must still be * applied. * * Note that, as documented in `goog.html.SafeUrl.unwrap`, this type's * contract does not guarantee that instances are safe to interpolate into HTML * without appropriate escaping. * * Note also that this type's contract does not imply any guarantees regarding * the resource the URL refers to. In particular, SafeUrls are <b>not</b> * safe to use in a context where the referred-to resource is interpreted as * trusted code, e.g., as the src of a script tag. * * Instances of this type must be created via the factory methods * (`goog.html.SafeUrl.fromConstant`, `goog.html.SafeUrl.sanitize`), * etc and not by invoking its constructor. The constructor intentionally * takes no parameters and the type is immutable; hence only a default instance * corresponding to the empty string can be obtained via constructor invocation. * * @see goog.html.SafeUrl#fromConstant * @see goog.html.SafeUrl#from * @see goog.html.SafeUrl#sanitize * @constructor * @final * @struct * @implements {goog.i18n.bidi.DirectionalString} * @implements {goog.string.TypedString} */ goog.html.SafeUrl = function() { /** * The contained value of this SafeUrl. The field has a purposely ugly * name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.SafeUrl#unwrap * @const {!Object} * @private */ this.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; }; /** * The innocuous string generated by goog.html.SafeUrl.sanitize when passed * an unsafe URL. * * about:invalid is registered in * http://www.w3.org/TR/css3-values/#about-invalid. * http://tools.ietf.org/html/rfc6694#section-2.2.1 permits about URLs to * contain a fragment, which is not to be considered when determining if an * about URL is well-known. * * Using about:invalid seems preferable to using a fixed data URL, since * browsers might choose to not report CSP violations on it, as legitimate * CSS function calls to attr() can result in this URL being produced. It is * also a standard URL which matches exactly the semantics we need: * "The about:invalid URI references a non-existent document with a generic * error condition. It can be used when a URI is necessary, but the default * value shouldn't be resolveable as any type of document". * * @const {string} */ goog.html.SafeUrl.INNOCUOUS_STRING = 'about:invalid#zClosurez'; /** * @override * @const */ goog.html.SafeUrl.prototype.implementsGoogStringTypedString = true; /** * Returns this SafeUrl's value a string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `SafeUrl`, use `goog.html.SafeUrl.unwrap` instead of this * method. If in doubt, assume that it's security relevant. In particular, note * that goog.html functions which return a goog.html type do not guarantee that * the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml instanceof * // goog.html.SafeHtml. * </pre> * * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST * be appropriately escaped before embedding in a HTML document. Note that the * required escaping is context-sensitive (e.g. a different escaping is * required for embedding a URL in a style property within a style * attribute, as opposed to embedding in a href attribute). * * @see goog.html.SafeUrl#unwrap * @override */ goog.html.SafeUrl.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_; }; /** * @override * @const */ goog.html.SafeUrl.prototype.implementsGoogI18nBidiDirectionalString = true; /** * Returns this URLs directionality, which is always `LTR`. * @override */ goog.html.SafeUrl.prototype.getDirection = function() { return goog.i18n.bidi.Dir.LTR; }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a SafeUrl, use * `goog.html.SafeUrl.unwrap`. * * @see goog.html.SafeUrl#unwrap * @override */ goog.html.SafeUrl.prototype.toString = function() { return 'SafeUrl{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a SafeUrl * object, and returns its value. * * IMPORTANT: The guarantees of the SafeUrl type contract only extend to the * behavior of browsers when interpreting URLs. Values of SafeUrl objects MUST * be appropriately escaped before embedding in a HTML document. Note that the * required escaping is context-sensitive (e.g. a different escaping is * required for embedding a URL in a style property within a style * attribute, as opposed to embedding in a href attribute). * * @param {!goog.html.SafeUrl} safeUrl The object to extract from. * @return {string} The SafeUrl object's contained string, unless the run-time * type check fails. In that case, `unwrap` returns an innocuous * string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.SafeUrl.unwrap = function(safeUrl) { // Perform additional Run-time type-checking to ensure that safeUrl is indeed // an instance of the expected type. This provides some additional protection // against security bugs due to application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (safeUrl instanceof goog.html.SafeUrl && safeUrl.constructor === goog.html.SafeUrl && safeUrl.SAFE_URL_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_; } else { goog.asserts.fail('expected object of type SafeUrl, got \'' + safeUrl + '\' of type ' + goog.typeOf(safeUrl)); return 'type_error:SafeUrl'; } }; /** * Creates a SafeUrl object from a compile-time constant string. * * Compile-time constant strings are inherently program-controlled and hence * trusted. * * @param {!goog.string.Const} url A compile-time-constant string from which to * create a SafeUrl. * @return {!goog.html.SafeUrl} A SafeUrl object initialized to `url`. */ goog.html.SafeUrl.fromConstant = function(url) { return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( goog.string.Const.unwrap(url)); }; /** * A pattern that matches Blob or data types that can have SafeUrls created * from URL.createObjectURL(blob) or via a data: URI. * @const * @private */ goog.html.SAFE_MIME_TYPE_PATTERN_ = new RegExp( // Note: Due to content-sniffing concerns, only add MIME types for // media formats. '^(?:audio/(?:3gpp|3gpp2|aac|midi|mp4|mpeg|ogg|x-m4a|x-wav|webm)|' + 'image/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|' + // TODO(b/68188949): Due to content-sniffing concerns, text/csv should // be removed from the whitelist. 'text/csv|' + 'video/(?:mpeg|mp4|ogg|webm|quicktime))$', 'i'); /** * Creates a SafeUrl wrapping a blob URL for the given `blob`. * * The blob URL is created with `URL.createObjectURL`. If the MIME type * for `blob` is not of a known safe audio, image or video MIME type, * then the SafeUrl will wrap {@link #INNOCUOUS_STRING}. * * @see http://www.w3.org/TR/FileAPI/#url * @param {!Blob} blob * @return {!goog.html.SafeUrl} The blob URL, or an innocuous string wrapped * as a SafeUrl. */ goog.html.SafeUrl.fromBlob = function(blob) { var url = goog.html.SAFE_MIME_TYPE_PATTERN_.test(blob.type) ? goog.fs.url.createObjectUrl(blob) : goog.html.SafeUrl.INNOCUOUS_STRING; return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); }; /** * Matches a base-64 data URL, with the first match group being the MIME type. * @const * @private */ goog.html.DATA_URL_PATTERN_ = /^data:([^;,]*);base64,[a-z0-9+\/]+=*$/i; /** * Creates a SafeUrl wrapping a data: URL, after validating it matches a * known-safe audio, image or video MIME type. * * @param {string} dataUrl A valid base64 data URL with one of the whitelisted * audio, image or video MIME types. * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING} * wrapped as a SafeUrl if it does not pass. */ goog.html.SafeUrl.fromDataUrl = function(dataUrl) { // There's a slight risk here that a browser sniffs the content type if it // doesn't know the MIME type and executes HTML within the data: URL. For this // to cause XSS it would also have to execute the HTML in the same origin // of the page with the link. It seems unlikely that both of these will // happen, particularly in not really old IEs. var match = dataUrl.match(goog.html.DATA_URL_PATTERN_); var valid = match && goog.html.SAFE_MIME_TYPE_PATTERN_.test(match[1]); return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( valid ? dataUrl : goog.html.SafeUrl.INNOCUOUS_STRING); }; /** * Creates a SafeUrl wrapping a tel: URL. * * @param {string} telUrl A tel URL. * @return {!goog.html.SafeUrl} A matching safe URL, or {@link INNOCUOUS_STRING} * wrapped as a SafeUrl if it does not pass. */ goog.html.SafeUrl.fromTelUrl = function(telUrl) { // There's a risk that a tel: URL could immediately place a call once // clicked, without requiring user confirmation. For that reason it is // handled in this separate function. if (!goog.string.caseInsensitiveStartsWith(telUrl, 'tel:')) { telUrl = goog.html.SafeUrl.INNOCUOUS_STRING; } return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( telUrl); }; /** * Creates a SafeUrl from TrustedResourceUrl. This is safe because * TrustedResourceUrl is more tightly restricted than SafeUrl. * * @param {!goog.html.TrustedResourceUrl} trustedResourceUrl * @return {!goog.html.SafeUrl} */ goog.html.SafeUrl.fromTrustedResourceUrl = function(trustedResourceUrl) { return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( goog.html.TrustedResourceUrl.unwrap(trustedResourceUrl)); }; /** * A pattern that recognizes a commonly useful subset of URLs that satisfy * the SafeUrl contract. * * This regular expression matches a subset of URLs that will not cause script * execution if used in URL context within a HTML document. Specifically, this * regular expression matches if (comment from here on and regex copied from * Soy's EscapingConventions): * (1) Either a protocol in a whitelist (http, https, mailto or ftp). * (2) or no protocol. A protocol must be followed by a colon. The below * allows that by allowing colons only after one of the characters [/?#]. * A colon after a hash (#) must be in the fragment. * Otherwise, a colon after a (?) must be in a query. * Otherwise, a colon after a single solidus (/) must be in a path. * Otherwise, a colon after a double solidus (//) must be in the authority * (before port). * * @private * @const {!RegExp} */ goog.html.SAFE_URL_PATTERN_ = /^(?:(?:https?|mailto|ftp):|[^:/?#]*(?:[/?#]|$))/i; /** * Creates a SafeUrl object from `url`. If `url` is a * goog.html.SafeUrl then it is simply returned. Otherwise the input string is * validated to match a pattern of commonly used safe URLs. * * `url` may be a URL with the http, https, mailto or ftp scheme, * or a relative URL (i.e., a URL without a scheme; specifically, a * scheme-relative, absolute-path-relative, or path-relative URL). * * @see http://url.spec.whatwg.org/#concept-relative-url * @param {string|!goog.string.TypedString} url The URL to validate. * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl. */ goog.html.SafeUrl.sanitize = function(url) { if (url instanceof goog.html.SafeUrl) { return url; } else if (url.implementsGoogStringTypedString) { url = /** @type {!goog.string.TypedString} */ (url).getTypedStringValue(); } else { url = String(url); } if (!goog.html.SAFE_URL_PATTERN_.test(url)) { url = goog.html.SafeUrl.INNOCUOUS_STRING; } return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); }; /** * Creates a SafeUrl object from `url`. If `url` is a * goog.html.SafeUrl then it is simply returned. Otherwise the input string is * validated to match a pattern of commonly used safe URLs. * * `url` may be a URL with the http, https, mailto or ftp scheme, * or a relative URL (i.e., a URL without a scheme; specifically, a * scheme-relative, absolute-path-relative, or path-relative URL). * * This function asserts (using goog.asserts) that the URL matches this pattern. * If it does not, in addition to failing the assert, an innocous URL will be * returned. * * @see http://url.spec.whatwg.org/#concept-relative-url * @param {string|!goog.string.TypedString} url The URL to validate. * @return {!goog.html.SafeUrl} The validated URL, wrapped as a SafeUrl. */ goog.html.SafeUrl.sanitizeAssertUnchanged = function(url) { if (url instanceof goog.html.SafeUrl) { return url; } else if (url.implementsGoogStringTypedString) { url = /** @type {!goog.string.TypedString} */ (url).getTypedStringValue(); } else { url = String(url); } if (!goog.asserts.assert(goog.html.SAFE_URL_PATTERN_.test(url))) { url = goog.html.SafeUrl.INNOCUOUS_STRING; } return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); }; /** * Type marker for the SafeUrl type, used to implement additional run-time * type checking. * @const {!Object} * @private */ goog.html.SafeUrl.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Package-internal utility method to create SafeUrl instances. * * @param {string} url The string to initialize the SafeUrl object with. * @return {!goog.html.SafeUrl} The initialized SafeUrl object. * @package */ goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse = function( url) { var safeUrl = new goog.html.SafeUrl(); safeUrl.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = url; return safeUrl; }; /** * A SafeUrl corresponding to the special about:blank url. * @const {!goog.html.SafeUrl} */ goog.html.SafeUrl.ABOUT_BLANK = goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse( 'about:blank'); //javascript/closure/html/safestyle.js // Copyright 2014 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The SafeStyle type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.SafeStyle'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.html.SafeUrl'); goog.require('goog.string'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A string-like object which represents a sequence of CSS declarations * ({@code propertyName1: propertyvalue1; propertyName2: propertyValue2; ...}) * and that carries the security type contract that its value, as a string, * will not cause untrusted script execution (XSS) when evaluated as CSS in a * browser. * * Instances of this type must be created via the factory methods * (`goog.html.SafeStyle.create` or * `goog.html.SafeStyle.fromConstant`) and not by invoking its * constructor. The constructor intentionally takes no parameters and the type * is immutable; hence only a default instance corresponding to the empty string * can be obtained via constructor invocation. * * SafeStyle's string representation can safely be: * <ul> * <li>Interpolated as the content of a *quoted* HTML style attribute. * However, the SafeStyle string *must be HTML-attribute-escaped* before * interpolation. * <li>Interpolated as the content of a {}-wrapped block within a stylesheet. * '<' characters in the SafeStyle string *must be CSS-escaped* before * interpolation. The SafeStyle string is also guaranteed not to be able * to introduce new properties or elide existing ones. * <li>Interpolated as the content of a {}-wrapped block within an HTML * &lt;style&gt; element. '<' characters in the SafeStyle string * *must be CSS-escaped* before interpolation. * <li>Assigned to the style property of a DOM node. The SafeStyle string * should not be escaped before being assigned to the property. * </ul> * * A SafeStyle may never contain literal angle brackets. Otherwise, it could * be unsafe to place a SafeStyle into a &lt;style&gt; tag (where it can't * be HTML escaped). For example, if the SafeStyle containing * "{@code font: 'foo &lt;style/&gt;&lt;script&gt;evil&lt;/script&gt;'}" were * interpolated within a &lt;style&gt; tag, this would then break out of the * style context into HTML. * * A SafeStyle may contain literal single or double quotes, and as such the * entire style string must be escaped when used in a style attribute (if * this were not the case, the string could contain a matching quote that * would escape from the style attribute). * * Values of this type must be composable, i.e. for any two values * `style1` and `style2` of this type, * {@code goog.html.SafeStyle.unwrap(style1) + * goog.html.SafeStyle.unwrap(style2)} must itself be a value that satisfies * the SafeStyle type constraint. This requirement implies that for any value * `style` of this type, `goog.html.SafeStyle.unwrap(style)` must * not end in a "property value" or "property name" context. For example, * a value of {@code background:url("} or {@code font-} would not satisfy the * SafeStyle contract. This is because concatenating such strings with a * second value that itself does not contain unsafe CSS can result in an * overall string that does. For example, if {@code javascript:evil())"} is * appended to {@code background:url("}, the resulting string may result in * the execution of a malicious script. * * TODO(mlourenco): Consider whether we should implement UTF-8 interchange * validity checks and blacklisting of newlines (including Unicode ones) and * other whitespace characters (\t, \f). Document here if so and also update * SafeStyle.fromConstant(). * * The following example values comply with this type's contract: * <ul> * <li><pre>width: 1em;</pre> * <li><pre>height:1em;</pre> * <li><pre>width: 1em;height: 1em;</pre> * <li><pre>background:url('http://url');</pre> * </ul> * In addition, the empty string is safe for use in a CSS attribute. * * The following example values do NOT comply with this type's contract: * <ul> * <li><pre>background: red</pre> (missing a trailing semi-colon) * <li><pre>background:</pre> (missing a value and a trailing semi-colon) * <li><pre>1em</pre> (missing an attribute name, which provides context for * the value) * </ul> * * @see goog.html.SafeStyle#create * @see goog.html.SafeStyle#fromConstant * @see http://www.w3.org/TR/css3-syntax/ * @constructor * @final * @struct * @implements {goog.string.TypedString} */ goog.html.SafeStyle = function() { /** * The contained value of this SafeStyle. The field has a purposely * ugly name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.SafeStyle#unwrap * @const {!Object} * @private */ this.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; }; /** * @override * @const */ goog.html.SafeStyle.prototype.implementsGoogStringTypedString = true; /** * Type marker for the SafeStyle type, used to implement additional * run-time type checking. * @const {!Object} * @private */ goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Creates a SafeStyle object from a compile-time constant string. * * `style` should be in the format * {@code name: value; [name: value; ...]} and must not have any < or > * characters in it. This is so that SafeStyle's contract is preserved, * allowing the SafeStyle to correctly be interpreted as a sequence of CSS * declarations and without affecting the syntactic structure of any * surrounding CSS and HTML. * * This method performs basic sanity checks on the format of `style` * but does not constrain the format of `name` and `value`, except * for disallowing tag characters. * * @param {!goog.string.Const} style A compile-time-constant string from which * to create a SafeStyle. * @return {!goog.html.SafeStyle} A SafeStyle object initialized to * `style`. */ goog.html.SafeStyle.fromConstant = function(style) { var styleString = goog.string.Const.unwrap(style); if (styleString.length === 0) { return goog.html.SafeStyle.EMPTY; } goog.html.SafeStyle.checkStyle_(styleString); goog.asserts.assert( goog.string.endsWith(styleString, ';'), 'Last character of style string is not \';\': ' + styleString); goog.asserts.assert( goog.string.contains(styleString, ':'), 'Style string must contain at least one \':\', to ' + 'specify a "name: value" pair: ' + styleString); return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( styleString); }; /** * Checks if the style definition is valid. * @param {string} style * @private */ goog.html.SafeStyle.checkStyle_ = function(style) { goog.asserts.assert( !/[<>]/.test(style), 'Forbidden characters in style string: ' + style); }; /** * Returns this SafeStyle's value as a string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `SafeStyle`, use `goog.html.SafeStyle.unwrap` instead of * this method. If in doubt, assume that it's security relevant. In particular, * note that goog.html functions which return a goog.html type do not guarantee * the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml * // instanceof goog.html.SafeHtml. * </pre> * * @see goog.html.SafeStyle#unwrap * @override */ goog.html.SafeStyle.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseSafeStyleWrappedValue_; }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a SafeStyle, use * `goog.html.SafeStyle.unwrap`. * * @see goog.html.SafeStyle#unwrap * @override */ goog.html.SafeStyle.prototype.toString = function() { return 'SafeStyle{' + this.privateDoNotAccessOrElseSafeStyleWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a * SafeStyle object, and returns its value. * * @param {!goog.html.SafeStyle} safeStyle The object to extract from. * @return {string} The safeStyle object's contained string, unless * the run-time type check fails. In that case, `unwrap` returns an * innocuous string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.SafeStyle.unwrap = function(safeStyle) { // Perform additional Run-time type-checking to ensure that // safeStyle is indeed an instance of the expected type. This // provides some additional protection against security bugs due to // application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (safeStyle instanceof goog.html.SafeStyle && safeStyle.constructor === goog.html.SafeStyle && safeStyle.SAFE_STYLE_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeStyle.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return safeStyle.privateDoNotAccessOrElseSafeStyleWrappedValue_; } else { goog.asserts.fail('expected object of type SafeStyle, got \'' + safeStyle + '\' of type ' + goog.typeOf(safeStyle)); return 'type_error:SafeStyle'; } }; /** * Package-internal utility method to create SafeStyle instances. * * @param {string} style The string to initialize the SafeStyle object with. * @return {!goog.html.SafeStyle} The initialized SafeStyle object. * @package */ goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse = function( style) { return new goog.html.SafeStyle().initSecurityPrivateDoNotAccessOrElse_(style); }; /** * Called from createSafeStyleSecurityPrivateDoNotAccessOrElse(). This * method exists only so that the compiler can dead code eliminate static * fields (like EMPTY) when they're not accessed. * @param {string} style * @return {!goog.html.SafeStyle} * @private */ goog.html.SafeStyle.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( style) { this.privateDoNotAccessOrElseSafeStyleWrappedValue_ = style; return this; }; /** * A SafeStyle instance corresponding to the empty string. * @const {!goog.html.SafeStyle} */ goog.html.SafeStyle.EMPTY = goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse(''); /** * The innocuous string generated by goog.html.SafeStyle.create when passed * an unsafe value. * @const {string} */ goog.html.SafeStyle.INNOCUOUS_STRING = 'zClosurez'; /** * A single property value. * @typedef {string|!goog.string.Const|!goog.html.SafeUrl} */ goog.html.SafeStyle.PropertyValue; /** * Mapping of property names to their values. * We don't support numbers even though some values might be numbers (e.g. * line-height or 0 for any length). The reason is that most numeric values need * units (e.g. '1px') and allowing numbers could cause users forgetting about * them. * @typedef {!Object<string, ?goog.html.SafeStyle.PropertyValue| * ?Array<!goog.html.SafeStyle.PropertyValue>>} */ goog.html.SafeStyle.PropertyMap; /** * Creates a new SafeStyle object from the properties specified in the map. * @param {goog.html.SafeStyle.PropertyMap} map Mapping of property names to * their values, for example {'margin': '1px'}. Names must consist of * [-_a-zA-Z0-9]. Values might be strings consisting of * [-,.'"%_!# a-zA-Z0-9], where " and ' must be properly balanced. We also * allow simple functions like rgb() and url() which sanitizes its contents. * Other values must be wrapped in goog.string.Const. URLs might be passed * as goog.html.SafeUrl which will be wrapped into url(""). We also support * array whose elements are joined with ' '. Null value causes skipping the * property. * @return {!goog.html.SafeStyle} * @throws {Error} If invalid name is provided. * @throws {goog.asserts.AssertionError} If invalid value is provided. With * disabled assertions, invalid value is replaced by * goog.html.SafeStyle.INNOCUOUS_STRING. */ goog.html.SafeStyle.create = function(map) { var style = ''; for (var name in map) { if (!/^[-_a-zA-Z0-9]+$/.test(name)) { throw new Error('Name allows only [-_a-zA-Z0-9], got: ' + name); } var value = map[name]; if (value == null) { continue; } if (goog.isArray(value)) { value = goog.array.map(value, goog.html.SafeStyle.sanitizePropertyValue_) .join(' '); } else { value = goog.html.SafeStyle.sanitizePropertyValue_(value); } style += name + ':' + value + ';'; } if (!style) { return goog.html.SafeStyle.EMPTY; } goog.html.SafeStyle.checkStyle_(style); return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( style); }; /** * Checks and converts value to string. * @param {!goog.html.SafeStyle.PropertyValue} value * @return {string} * @private */ goog.html.SafeStyle.sanitizePropertyValue_ = function(value) { if (value instanceof goog.html.SafeUrl) { var url = goog.html.SafeUrl.unwrap(value); return 'url("' + url.replace(/</g, '%3c').replace(/[\\"]/g, '\\$&') + '")'; } var result = value instanceof goog.string.Const ? goog.string.Const.unwrap(value) : goog.html.SafeStyle.sanitizePropertyValueString_(String(value)); // These characters can be used to change context and we don't want that even // with const values. goog.asserts.assert(!/[{;}]/.test(result), 'Value does not allow [{;}].'); return result; }; /** * Checks string value. * @param {string} value * @return {string} * @private */ goog.html.SafeStyle.sanitizePropertyValueString_ = function(value) { var valueWithoutFunctions = value.replace(goog.html.SafeUrl.FUNCTIONS_RE_, '$1') .replace(goog.html.SafeUrl.URL_RE_, 'url'); if (!goog.html.SafeStyle.VALUE_RE_.test(valueWithoutFunctions)) { goog.asserts.fail( 'String value allows only ' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + ' and simple functions, got: ' + value); return goog.html.SafeStyle.INNOCUOUS_STRING; } else if (!goog.html.SafeStyle.hasBalancedQuotes_(value)) { goog.asserts.fail('String value requires balanced quotes, got: ' + value); return goog.html.SafeStyle.INNOCUOUS_STRING; } return goog.html.SafeStyle.sanitizeUrl_(value); }; /** * Checks that quotes (" and ') are properly balanced inside a string. Assumes * that neither escape (\) nor any other character that could result in * breaking out of a string parsing context are allowed; * see http://www.w3.org/TR/css3-syntax/#string-token-diagram. * @param {string} value Untrusted CSS property value. * @return {boolean} True if property value is safe with respect to quote * balancedness. * @private */ goog.html.SafeStyle.hasBalancedQuotes_ = function(value) { var outsideSingle = true; var outsideDouble = true; for (var i = 0; i < value.length; i++) { var c = value.charAt(i); if (c == "'" && outsideDouble) { outsideSingle = !outsideSingle; } else if (c == '"' && outsideSingle) { outsideDouble = !outsideDouble; } } return outsideSingle && outsideDouble; }; /** * Characters allowed in goog.html.SafeStyle.VALUE_RE_. * @private {string} */ goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ = '[-,."\'%_!# a-zA-Z0-9]'; /** * Regular expression for safe values. * * Quotes (" and ') are allowed, but a check must be done elsewhere to ensure * they're balanced. * * ',' allows multiple values to be assigned to the same property * (e.g. background-attachment or font-family) and hence could allow * multiple values to get injected, but that should pose no risk of XSS. * * The expression checks only for XSS safety, not for CSS validity. * @const {!RegExp} * @private */ goog.html.SafeStyle.VALUE_RE_ = new RegExp('^' + goog.html.SafeStyle.VALUE_ALLOWED_CHARS_ + '+$'); /** * Regular expression for url(). We support URLs allowed by * https://www.w3.org/TR/css-syntax-3/#url-token-diagram without using escape * sequences. Use percent-encoding if you need to use special characters like * backslash. * @private @const {!RegExp} */ goog.html.SafeUrl.URL_RE_ = new RegExp( '\\b(url\\([ \t\n]*)(' + '\'[ -&(-\\[\\]-~]*\'' + // Printable characters except ' and \. '|"[ !#-\\[\\]-~]*"' + // Printable characters except " and \. '|[!#-&*-\\[\\]-~]*' + // Printable characters except [ "'()\\]. ')([ \t\n]*\\))', 'g'); /** * Regular expression for simple functions. * @private @const {!RegExp} */ goog.html.SafeUrl.FUNCTIONS_RE_ = new RegExp( '\\b(hsl|hsla|rgb|rgba|(rotate|scale|translate)(X|Y|Z|3d)?)' + '\\([-0-9a-z.%, ]+\\)', 'g'); /** * Sanitize URLs inside url(). * * NOTE: We could also consider using CSS.escape once that's available in the * browsers. However, loosely matching URL e.g. with url\(.*\) and then escaping * the contents would result in a slightly different language than CSS leading * to confusion of users. E.g. url(")") is valid in CSS but it would be invalid * as seen by our parser. On the other hand, url(\) is invalid in CSS but our * parser would be fine with it. * * @param {string} value Untrusted CSS property value. * @return {string} * @private */ goog.html.SafeStyle.sanitizeUrl_ = function(value) { return value.replace( goog.html.SafeUrl.URL_RE_, function(match, before, url, after) { var quote = ''; url = url.replace(/^(['"])(.*)\1$/, function(match, start, inside) { quote = start; return inside; }); var sanitized = goog.html.SafeUrl.sanitize(url).getTypedStringValue(); return before + quote + sanitized + quote + after; }); }; /** * Creates a new SafeStyle object by concatenating the values. * @param {...(!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>)} var_args * SafeStyles to concatenate. * @return {!goog.html.SafeStyle} */ goog.html.SafeStyle.concat = function(var_args) { var style = ''; /** * @param {!goog.html.SafeStyle|!Array<!goog.html.SafeStyle>} argument */ var addArgument = function(argument) { if (goog.isArray(argument)) { goog.array.forEach(argument, addArgument); } else { style += goog.html.SafeStyle.unwrap(argument); } }; goog.array.forEach(arguments, addArgument); if (!style) { return goog.html.SafeStyle.EMPTY; } return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( style); }; //javascript/closure/html/safestylesheet.js // Copyright 2014 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The SafeStyleSheet type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.SafeStyleSheet'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.html.SafeStyle'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A string-like object which represents a CSS style sheet and that carries the * security type contract that its value, as a string, will not cause untrusted * script execution (XSS) when evaluated as CSS in a browser. * * Instances of this type must be created via the factory method * `goog.html.SafeStyleSheet.fromConstant` and not by invoking its * constructor. The constructor intentionally takes no parameters and the type * is immutable; hence only a default instance corresponding to the empty string * can be obtained via constructor invocation. * * A SafeStyleSheet's string representation can safely be interpolated as the * content of a style element within HTML. The SafeStyleSheet string should * not be escaped before interpolation. * * Values of this type must be composable, i.e. for any two values * `styleSheet1` and `styleSheet2` of this type, * {@code goog.html.SafeStyleSheet.unwrap(styleSheet1) + * goog.html.SafeStyleSheet.unwrap(styleSheet2)} must itself be a value that * satisfies the SafeStyleSheet type constraint. This requirement implies that * for any value `styleSheet` of this type, * `goog.html.SafeStyleSheet.unwrap(styleSheet1)` must end in * "beginning of rule" context. * A SafeStyleSheet can be constructed via security-reviewed unchecked * conversions. In this case producers of SafeStyleSheet must ensure themselves * that the SafeStyleSheet does not contain unsafe script. Note in particular * that {@code &lt;} is dangerous, even when inside CSS strings, and so should * always be forbidden or CSS-escaped in user controlled input. For example, if * {@code &lt;/style&gt;&lt;script&gt;evil&lt;/script&gt;"} were interpolated * inside a CSS string, it would break out of the context of the original * style element and `evil` would execute. Also note that within an HTML * style (raw text) element, HTML character references, such as * {@code &amp;lt;}, are not allowed. See * http://www.w3.org/TR/html5/scripting-1.html#restrictions-for-contents-of-script-elements * (similar considerations apply to the style element). * * @see goog.html.SafeStyleSheet#fromConstant * @constructor * @final * @struct * @implements {goog.string.TypedString} */ goog.html.SafeStyleSheet = function() { /** * The contained value of this SafeStyleSheet. The field has a purposely * ugly name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.SafeStyleSheet#unwrap * @const {!Object} * @private */ this.SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; }; /** * @override * @const */ goog.html.SafeStyleSheet.prototype.implementsGoogStringTypedString = true; /** * Type marker for the SafeStyleSheet type, used to implement additional * run-time type checking. * @const {!Object} * @private */ goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Creates a style sheet consisting of one selector and one style definition. * Use {@link goog.html.SafeStyleSheet.concat} to create longer style sheets. * This function doesn't support @import, @media and similar constructs. * @param {string} selector CSS selector, e.g. '#id' or 'tag .class, #id'. We * support CSS3 selectors: https://w3.org/TR/css3-selectors/#selectors. * @param {!goog.html.SafeStyle.PropertyMap|!goog.html.SafeStyle} style Style * definition associated with the selector. * @return {!goog.html.SafeStyleSheet} * @throws {Error} If invalid selector is provided. */ goog.html.SafeStyleSheet.createRule = function(selector, style) { if (goog.string.contains(selector, '<')) { throw new Error('Selector does not allow \'<\', got: ' + selector); } // Remove strings. var selectorToCheck = selector.replace(/('|")((?!\1)[^\r\n\f\\]|\\[\s\S])*\1/g, ''); // Check characters allowed in CSS3 selectors. if (!/^[-_a-zA-Z0-9#.:* ,>+~[\]()=^$|]+$/.test(selectorToCheck)) { throw new Error( 'Selector allows only [-_a-zA-Z0-9#.:* ,>+~[\\]()=^$|] and ' + 'strings, got: ' + selector); } // Check balanced () and []. if (!goog.html.SafeStyleSheet.hasBalancedBrackets_(selectorToCheck)) { throw new Error('() and [] in selector must be balanced, got: ' + selector); } if (!(style instanceof goog.html.SafeStyle)) { style = goog.html.SafeStyle.create(style); } var styleSheet = selector + '{' + goog.html.SafeStyle.unwrap(style) + '}'; return goog.html.SafeStyleSheet .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet); }; /** * Checks if a string has balanced () and [] brackets. * @param {string} s String to check. * @return {boolean} * @private */ goog.html.SafeStyleSheet.hasBalancedBrackets_ = function(s) { var brackets = {'(': ')', '[': ']'}; var expectedBrackets = []; for (var i = 0; i < s.length; i++) { var ch = s[i]; if (brackets[ch]) { expectedBrackets.push(brackets[ch]); } else if (goog.object.contains(brackets, ch)) { if (expectedBrackets.pop() != ch) { return false; } } } return expectedBrackets.length == 0; }; /** * Creates a new SafeStyleSheet object by concatenating values. * @param {...(!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>)} * var_args Values to concatenate. * @return {!goog.html.SafeStyleSheet} */ goog.html.SafeStyleSheet.concat = function(var_args) { var result = ''; /** * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>} * argument */ var addArgument = function(argument) { if (goog.isArray(argument)) { goog.array.forEach(argument, addArgument); } else { result += goog.html.SafeStyleSheet.unwrap(argument); } }; goog.array.forEach(arguments, addArgument); return goog.html.SafeStyleSheet .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(result); }; /** * Creates a SafeStyleSheet object from a compile-time constant string. * * `styleSheet` must not have any &lt; characters in it, so that * the syntactic structure of the surrounding HTML is not affected. * * @param {!goog.string.Const} styleSheet A compile-time-constant string from * which to create a SafeStyleSheet. * @return {!goog.html.SafeStyleSheet} A SafeStyleSheet object initialized to * `styleSheet`. */ goog.html.SafeStyleSheet.fromConstant = function(styleSheet) { var styleSheetString = goog.string.Const.unwrap(styleSheet); if (styleSheetString.length === 0) { return goog.html.SafeStyleSheet.EMPTY; } // > is a valid character in CSS selectors and there's no strict need to // block it if we already block <. goog.asserts.assert( !goog.string.contains(styleSheetString, '<'), "Forbidden '<' character in style sheet string: " + styleSheetString); return goog.html.SafeStyleSheet .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheetString); }; /** * Returns this SafeStyleSheet's value as a string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `SafeStyleSheet`, use `goog.html.SafeStyleSheet.unwrap` * instead of this method. If in doubt, assume that it's security relevant. In * particular, note that goog.html functions which return a goog.html type do * not guarantee the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml * // instanceof goog.html.SafeHtml. * </pre> * * @see goog.html.SafeStyleSheet#unwrap * @override */ goog.html.SafeStyleSheet.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_; }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a SafeStyleSheet, use * `goog.html.SafeStyleSheet.unwrap`. * * @see goog.html.SafeStyleSheet#unwrap * @override */ goog.html.SafeStyleSheet.prototype.toString = function() { return 'SafeStyleSheet{' + this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a * SafeStyleSheet object, and returns its value. * * @param {!goog.html.SafeStyleSheet} safeStyleSheet The object to extract from. * @return {string} The safeStyleSheet object's contained string, unless * the run-time type check fails. In that case, `unwrap` returns an * innocuous string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.SafeStyleSheet.unwrap = function(safeStyleSheet) { // Perform additional Run-time type-checking to ensure that // safeStyleSheet is indeed an instance of the expected type. This // provides some additional protection against security bugs due to // application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (safeStyleSheet instanceof goog.html.SafeStyleSheet && safeStyleSheet.constructor === goog.html.SafeStyleSheet && safeStyleSheet .SAFE_STYLE_SHEET_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeStyleSheet.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return safeStyleSheet.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_; } else { goog.asserts.fail('expected object of type SafeStyleSheet, got \'' + safeStyleSheet + '\' of type ' + goog.typeOf(safeStyleSheet)); return 'type_error:SafeStyleSheet'; } }; /** * Package-internal utility method to create SafeStyleSheet instances. * * @param {string} styleSheet The string to initialize the SafeStyleSheet * object with. * @return {!goog.html.SafeStyleSheet} The initialized SafeStyleSheet object. * @package */ goog.html.SafeStyleSheet.createSafeStyleSheetSecurityPrivateDoNotAccessOrElse = function(styleSheet) { return new goog.html.SafeStyleSheet().initSecurityPrivateDoNotAccessOrElse_( styleSheet); }; /** * Called from createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(). This * method exists only so that the compiler can dead code eliminate static * fields (like EMPTY) when they're not accessed. * @param {string} styleSheet * @return {!goog.html.SafeStyleSheet} * @private */ goog.html.SafeStyleSheet.prototype.initSecurityPrivateDoNotAccessOrElse_ = function(styleSheet) { this.privateDoNotAccessOrElseSafeStyleSheetWrappedValue_ = styleSheet; return this; }; /** * A SafeStyleSheet instance corresponding to the empty string. * @const {!goog.html.SafeStyleSheet} */ goog.html.SafeStyleSheet.EMPTY = goog.html.SafeStyleSheet .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(''); //javascript/closure/html/safehtml.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview The SafeHtml type and its builders. * * TODO(xtof): Link to document stating type contract. */ goog.provide('goog.html.SafeHtml'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.dom.TagName'); goog.require('goog.dom.tags'); goog.require('goog.html.SafeScript'); goog.require('goog.html.SafeStyle'); goog.require('goog.html.SafeStyleSheet'); goog.require('goog.html.SafeUrl'); goog.require('goog.html.TrustedResourceUrl'); goog.require('goog.i18n.bidi.Dir'); goog.require('goog.i18n.bidi.DirectionalString'); goog.require('goog.labs.userAgent.browser'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.string.Const'); goog.require('goog.string.TypedString'); /** * A string that is safe to use in HTML context in DOM APIs and HTML documents. * * A SafeHtml is a string-like object that carries the security type contract * that its value as a string will not cause untrusted script execution when * evaluated as HTML in a browser. * * Values of this type are guaranteed to be safe to use in HTML contexts, * such as, assignment to the innerHTML DOM property, or interpolation into * a HTML template in HTML PC_DATA context, in the sense that the use will not * result in a Cross-Site-Scripting vulnerability. * * Instances of this type must be created via the factory methods * (`goog.html.SafeHtml.create`, `goog.html.SafeHtml.htmlEscape`), * etc and not by invoking its constructor. The constructor intentionally * takes no parameters and the type is immutable; hence only a default instance * corresponding to the empty string can be obtained via constructor invocation. * * @see goog.html.SafeHtml#create * @see goog.html.SafeHtml#htmlEscape * @constructor * @final * @struct * @implements {goog.i18n.bidi.DirectionalString} * @implements {goog.string.TypedString} */ goog.html.SafeHtml = function() { /** * The contained value of this SafeHtml. The field has a purposely ugly * name to make (non-compiled) code that attempts to directly access this * field stand out. * @private {string} */ this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = ''; /** * A type marker used to implement additional run-time type checking. * @see goog.html.SafeHtml#unwrap * @const {!Object} * @private */ this.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_; /** * This SafeHtml's directionality, or null if unknown. * @private {?goog.i18n.bidi.Dir} */ this.dir_ = null; }; /** * @override * @const */ goog.html.SafeHtml.prototype.implementsGoogI18nBidiDirectionalString = true; /** @override */ goog.html.SafeHtml.prototype.getDirection = function() { return this.dir_; }; /** * @override * @const */ goog.html.SafeHtml.prototype.implementsGoogStringTypedString = true; /** * Returns this SafeHtml's value as string. * * IMPORTANT: In code where it is security relevant that an object's type is * indeed `SafeHtml`, use `goog.html.SafeHtml.unwrap` instead of * this method. If in doubt, assume that it's security relevant. In particular, * note that goog.html functions which return a goog.html type do not guarantee * that the returned instance is of the right type. For example: * * <pre> * var fakeSafeHtml = new String('fake'); * fakeSafeHtml.__proto__ = goog.html.SafeHtml.prototype; * var newSafeHtml = goog.html.SafeHtml.htmlEscape(fakeSafeHtml); * // newSafeHtml is just an alias for fakeSafeHtml, it's passed through by * // goog.html.SafeHtml.htmlEscape() as fakeSafeHtml * // instanceof goog.html.SafeHtml. * </pre> * * @see goog.html.SafeHtml#unwrap * @override */ goog.html.SafeHtml.prototype.getTypedStringValue = function() { return this.privateDoNotAccessOrElseSafeHtmlWrappedValue_; }; if (goog.DEBUG) { /** * Returns a debug string-representation of this value. * * To obtain the actual string value wrapped in a SafeHtml, use * `goog.html.SafeHtml.unwrap`. * * @see goog.html.SafeHtml#unwrap * @override */ goog.html.SafeHtml.prototype.toString = function() { return 'SafeHtml{' + this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ + '}'; }; } /** * Performs a runtime check that the provided object is indeed a SafeHtml * object, and returns its value. * @param {!goog.html.SafeHtml} safeHtml The object to extract from. * @return {string} The SafeHtml object's contained string, unless the run-time * type check fails. In that case, `unwrap` returns an innocuous * string, or, if assertions are enabled, throws * `goog.asserts.AssertionError`. */ goog.html.SafeHtml.unwrap = function(safeHtml) { // Perform additional run-time type-checking to ensure that safeHtml is indeed // an instance of the expected type. This provides some additional protection // against security bugs due to application code that disables type checks. // Specifically, the following checks are performed: // 1. The object is an instance of the expected type. // 2. The object is not an instance of a subclass. // 3. The object carries a type marker for the expected type. "Faking" an // object requires a reference to the type marker, which has names intended // to stand out in code reviews. if (safeHtml instanceof goog.html.SafeHtml && safeHtml.constructor === goog.html.SafeHtml && safeHtml.SAFE_HTML_TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ === goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_) { return safeHtml.privateDoNotAccessOrElseSafeHtmlWrappedValue_; } else { goog.asserts.fail('expected object of type SafeHtml, got \'' + safeHtml + '\' of type ' + goog.typeOf(safeHtml)); return 'type_error:SafeHtml'; } }; /** * Shorthand for union of types that can sensibly be converted to strings * or might already be SafeHtml (as SafeHtml is a goog.string.TypedString). * @private * @typedef {string|number|boolean|!goog.string.TypedString| * !goog.i18n.bidi.DirectionalString} */ goog.html.SafeHtml.TextOrHtml_; /** * Returns HTML-escaped text as a SafeHtml object. * * If text is of a type that implements * `goog.i18n.bidi.DirectionalString`, the directionality of the new * `SafeHtml` object is set to `text`'s directionality, if known. * Otherwise, the directionality of the resulting SafeHtml is unknown (i.e., * `null`). * * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If * the parameter is of type SafeHtml it is returned directly (no escaping * is done). * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. */ goog.html.SafeHtml.htmlEscape = function(textOrHtml) { if (textOrHtml instanceof goog.html.SafeHtml) { return textOrHtml; } var dir = null; if (textOrHtml.implementsGoogI18nBidiDirectionalString) { dir = /** @type {!goog.i18n.bidi.DirectionalString} */ (textOrHtml) .getDirection(); } var textAsString; if (textOrHtml.implementsGoogStringTypedString) { textAsString = /** @type {!goog.string.TypedString} */ (textOrHtml) .getTypedStringValue(); } else { textAsString = String(textOrHtml); } return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( goog.string.htmlEscape(textAsString), dir); }; /** * Returns HTML-escaped text as a SafeHtml object, with newlines changed to * &lt;br&gt;. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If * the parameter is of type SafeHtml it is returned directly (no escaping * is done). * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. */ goog.html.SafeHtml.htmlEscapePreservingNewlines = function(textOrHtml) { if (textOrHtml instanceof goog.html.SafeHtml) { return textOrHtml; } var html = goog.html.SafeHtml.htmlEscape(textOrHtml); return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( goog.string.newLineToBr(goog.html.SafeHtml.unwrap(html)), html.getDirection()); }; /** * Returns HTML-escaped text as a SafeHtml object, with newlines changed to * &lt;br&gt; and escaping whitespace to preserve spatial formatting. Character * entity #160 is used to make it safer for XML. * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text to escape. If * the parameter is of type SafeHtml it is returned directly (no escaping * is done). * @return {!goog.html.SafeHtml} The escaped text, wrapped as a SafeHtml. */ goog.html.SafeHtml.htmlEscapePreservingNewlinesAndSpaces = function( textOrHtml) { if (textOrHtml instanceof goog.html.SafeHtml) { return textOrHtml; } var html = goog.html.SafeHtml.htmlEscape(textOrHtml); return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( goog.string.whitespaceEscape(goog.html.SafeHtml.unwrap(html)), html.getDirection()); }; /** * Coerces an arbitrary object into a SafeHtml object. * * If `textOrHtml` is already of type `goog.html.SafeHtml`, the same * object is returned. Otherwise, `textOrHtml` is coerced to string, and * HTML-escaped. If `textOrHtml` is of a type that implements * `goog.i18n.bidi.DirectionalString`, its directionality, if known, is * preserved. * * @param {!goog.html.SafeHtml.TextOrHtml_} textOrHtml The text or SafeHtml to * coerce. * @return {!goog.html.SafeHtml} The resulting SafeHtml object. * @deprecated Use goog.html.SafeHtml.htmlEscape. */ goog.html.SafeHtml.from = goog.html.SafeHtml.htmlEscape; /** * @const * @private */ goog.html.SafeHtml.VALID_NAMES_IN_TAG_ = /^[a-zA-Z0-9-]+$/; /** * Set of attributes containing URL as defined at * http://www.w3.org/TR/html5/index.html#attributes-1. * @private @const {!Object<string,boolean>} */ goog.html.SafeHtml.URL_ATTRIBUTES_ = goog.object.createSet( 'action', 'cite', 'data', 'formaction', 'href', 'manifest', 'poster', 'src'); /** * Tags which are unsupported via create(). They might be supported via a * tag-specific create method. These are tags which might require a * TrustedResourceUrl in one of their attributes or a restricted type for * their content. * @private @const {!Object<string,boolean>} */ goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_ = goog.object.createSet( goog.dom.TagName.APPLET, goog.dom.TagName.BASE, goog.dom.TagName.EMBED, goog.dom.TagName.IFRAME, goog.dom.TagName.LINK, goog.dom.TagName.MATH, goog.dom.TagName.META, goog.dom.TagName.OBJECT, goog.dom.TagName.SCRIPT, goog.dom.TagName.STYLE, goog.dom.TagName.SVG, goog.dom.TagName.TEMPLATE); /** * @typedef {string|number|goog.string.TypedString| * goog.html.SafeStyle.PropertyMap|undefined} */ goog.html.SafeHtml.AttributeValue; /** * Creates a SafeHtml content consisting of a tag with optional attributes and * optional content. * * For convenience tag names and attribute names are accepted as regular * strings, instead of goog.string.Const. Nevertheless, you should not pass * user-controlled values to these parameters. Note that these parameters are * syntactically validated at runtime, and invalid values will result in * an exception. * * Example usage: * * goog.html.SafeHtml.create('br'); * goog.html.SafeHtml.create('div', {'class': 'a'}); * goog.html.SafeHtml.create('p', {}, 'a'); * goog.html.SafeHtml.create('p', {}, goog.html.SafeHtml.create('br')); * * goog.html.SafeHtml.create('span', { * 'style': {'margin': '0'} * }); * * To guarantee SafeHtml's type contract is upheld there are restrictions on * attribute values and tag names. * * - For attributes which contain script code (on*), a goog.string.Const is * required. * - For attributes which contain style (style), a goog.html.SafeStyle or a * goog.html.SafeStyle.PropertyMap is required. * - For attributes which are interpreted as URLs (e.g. src, href) a * goog.html.SafeUrl, goog.string.Const or string is required. If a string * is passed, it will be sanitized with SafeUrl.sanitize(). * - For tags which can load code or set security relevant page metadata, * more specific goog.html.SafeHtml.create*() functions must be used. Tags * which are not supported by this function are applet, base, embed, iframe, * link, math, object, script, style, svg, and template. * * @param {!goog.dom.TagName|string} tagName The name of the tag. Only tag names * consisting of [a-zA-Z0-9-] are allowed. Tag names documented above are * disallowed. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes * the attribute to be omitted. * @param {!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to * HTML-escape and put inside the tag. This must be empty for void tags * like <br>. Array elements are concatenated. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid tag name, attribute name, or attribute value is * provided. * @throws {goog.asserts.AssertionError} If content for void tag is provided. */ goog.html.SafeHtml.create = function(tagName, opt_attributes, opt_content) { goog.html.SafeHtml.verifyTagName(String(tagName)); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( String(tagName), opt_attributes, opt_content); }; /** * Verifies if the tag name is valid and if it doesn't change the context. * E.g. STRONG is fine but SCRIPT throws because it changes context. See * goog.html.SafeHtml.create for an explanation of allowed tags. * @param {string} tagName * @throws {Error} If invalid tag name is provided. * @package */ goog.html.SafeHtml.verifyTagName = function(tagName) { if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(tagName)) { throw new Error('Invalid tag name <' + tagName + '>.'); } if (tagName.toUpperCase() in goog.html.SafeHtml.NOT_ALLOWED_TAG_NAMES_) { throw new Error('Tag name <' + tagName + '> is not allowed for SafeHtml.'); } }; /** * Creates a SafeHtml representing an iframe tag. * * This by default restricts the iframe as much as possible by setting the * sandbox attribute to the empty string. If the iframe requires less * restrictions, set the sandbox attribute as tight as possible, but do not rely * on the sandbox as a security feature because it is not supported by older * browsers. If a sandbox is essential to security (e.g. for third-party * frames), use createSandboxIframe which checks for browser support. * * @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox * * @param {?goog.html.TrustedResourceUrl=} opt_src The value of the src * attribute. If null or undefined src will not be set. * @param {?goog.html.SafeHtml=} opt_srcdoc The value of the srcdoc attribute. * If null or undefined srcdoc will not be set. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes * the attribute to be omitted. * @param {!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to * HTML-escape and put inside the tag. Array elements are concatenated. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid tag name, attribute name, or attribute value is * provided. If opt_attributes contains the src or srcdoc attributes. */ goog.html.SafeHtml.createIframe = function( opt_src, opt_srcdoc, opt_attributes, opt_content) { if (opt_src) { // Check whether this is really TrustedResourceUrl. goog.html.TrustedResourceUrl.unwrap(opt_src); } var fixedAttributes = {}; fixedAttributes['src'] = opt_src || null; fixedAttributes['srcdoc'] = opt_srcdoc && goog.html.SafeHtml.unwrap(opt_srcdoc); var defaultAttributes = {'sandbox': ''}; var attributes = goog.html.SafeHtml.combineAttributes( fixedAttributes, defaultAttributes, opt_attributes); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'iframe', attributes, opt_content); }; /** * Creates a SafeHtml representing a sandboxed iframe tag. * * The sandbox attribute is enforced in its most restrictive mode, an empty * string. Consequently, the security requirements for the src and srcdoc * attributes are relaxed compared to SafeHtml.createIframe. This function * will throw on browsers that do not support the sandbox attribute, as * determined by SafeHtml.canUseSandboxIframe. * * The SafeHtml returned by this function can trigger downloads with no * user interaction on Chrome (though only a few, further attempts are blocked). * Firefox and IE will block all downloads from the sandbox. * * @see https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe#attr-sandbox * @see https://lists.w3.org/Archives/Public/public-whatwg-archive/2013Feb/0112.html * * @param {string|!goog.html.SafeUrl=} opt_src The value of the src * attribute. If null or undefined src will not be set. * @param {string=} opt_srcdoc The value of the srcdoc attribute. * If null or undefined srcdoc will not be set. Will not be sanitized. * @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes * the attribute to be omitted. * @param {!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content Content to * HTML-escape and put inside the tag. Array elements are concatenated. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid tag name, attribute name, or attribute value is * provided. If opt_attributes contains the src, srcdoc or sandbox * attributes. If browser does not support the sandbox attribute on iframe. */ goog.html.SafeHtml.createSandboxIframe = function( opt_src, opt_srcdoc, opt_attributes, opt_content) { if (!goog.html.SafeHtml.canUseSandboxIframe()) { throw new Error('The browser does not support sandboxed iframes.'); } var fixedAttributes = {}; if (opt_src) { // Note that sanitize is a no-op on SafeUrl. fixedAttributes['src'] = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(opt_src)); } else { fixedAttributes['src'] = null; } fixedAttributes['srcdoc'] = opt_srcdoc || null; fixedAttributes['sandbox'] = ''; var attributes = goog.html.SafeHtml.combineAttributes(fixedAttributes, {}, opt_attributes); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'iframe', attributes, opt_content); }; /** * Checks if the user agent supports sandboxed iframes. * @return {boolean} */ goog.html.SafeHtml.canUseSandboxIframe = function() { return goog.global['HTMLIFrameElement'] && ('sandbox' in goog.global['HTMLIFrameElement'].prototype); }; /** * Creates a SafeHtml representing a script tag with the src attribute. * @param {!goog.html.TrustedResourceUrl} src The value of the src * attribute. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} * opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined * causes the attribute to be omitted. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid attribute name or value is provided. If * opt_attributes contains the src attribute. */ goog.html.SafeHtml.createScriptSrc = function(src, opt_attributes) { // TODO(mlourenco): The charset attribute should probably be blocked. If // its value is attacker controlled, the script contains attacker controlled // sub-strings (even if properly escaped) and the server does not set charset // then XSS is likely possible. // https://html.spec.whatwg.org/multipage/scripting.html#dom-script-charset // Check whether this is really TrustedResourceUrl. goog.html.TrustedResourceUrl.unwrap(src); var fixedAttributes = {'src': src}; var defaultAttributes = {}; var attributes = goog.html.SafeHtml.combineAttributes( fixedAttributes, defaultAttributes, opt_attributes); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'script', attributes); }; /** * Creates a SafeHtml representing a script tag. Does not allow the language, * src, text or type attributes to be set. * @param {!goog.html.SafeScript|!Array<!goog.html.SafeScript>} * script Content to put inside the tag. Array elements are * concatenated. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes * the attribute to be omitted. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid attribute name or attribute value is provided. If * opt_attributes contains the language, src, text or type attribute. */ goog.html.SafeHtml.createScript = function(script, opt_attributes) { for (var attr in opt_attributes) { var attrLower = attr.toLowerCase(); if (attrLower == 'language' || attrLower == 'src' || attrLower == 'text' || attrLower == 'type') { throw new Error('Cannot set "' + attrLower + '" attribute'); } } var content = ''; script = goog.array.concat(script); for (var i = 0; i < script.length; i++) { content += goog.html.SafeScript.unwrap(script[i]); } // Convert to SafeHtml so that it's not HTML-escaped. This is safe because // as part of its contract, SafeScript should have no dangerous '<'. var htmlContent = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( content, goog.i18n.bidi.Dir.NEUTRAL); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'script', opt_attributes, htmlContent); }; /** * Creates a SafeHtml representing a style tag. The type attribute is set * to "text/css". * @param {!goog.html.SafeStyleSheet|!Array<!goog.html.SafeStyleSheet>} * styleSheet Content to put inside the tag. Array elements are * concatenated. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Mapping from attribute names to their values. Only attribute names * consisting of [a-zA-Z0-9-] are allowed. Value of null or undefined causes * the attribute to be omitted. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. * @throws {Error} If invalid attribute name or attribute value is provided. If * opt_attributes contains the type attribute. */ goog.html.SafeHtml.createStyle = function(styleSheet, opt_attributes) { var fixedAttributes = {'type': 'text/css'}; var defaultAttributes = {}; var attributes = goog.html.SafeHtml.combineAttributes( fixedAttributes, defaultAttributes, opt_attributes); var content = ''; styleSheet = goog.array.concat(styleSheet); for (var i = 0; i < styleSheet.length; i++) { content += goog.html.SafeStyleSheet.unwrap(styleSheet[i]); } // Convert to SafeHtml so that it's not HTML-escaped. This is safe because // as part of its contract, SafeStyleSheet should have no dangerous '<'. var htmlContent = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( content, goog.i18n.bidi.Dir.NEUTRAL); return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'style', attributes, htmlContent); }; /** * Creates a SafeHtml representing a meta refresh tag. * @param {!goog.html.SafeUrl|string} url Where to redirect. If a string is * passed, it will be sanitized with SafeUrl.sanitize(). * @param {number=} opt_secs Number of seconds until the page should be * reloaded. Will be set to 0 if unspecified. * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. */ goog.html.SafeHtml.createMetaRefresh = function(url, opt_secs) { // Note that sanitize is a no-op on SafeUrl. var unwrappedUrl = goog.html.SafeUrl.unwrap(goog.html.SafeUrl.sanitize(url)); if (goog.labs.userAgent.browser.isIE() || goog.labs.userAgent.browser.isEdge()) { // IE/EDGE can't parse the content attribute if the url contains a // semicolon. We can fix this by adding quotes around the url, but then we // can't parse quotes in the URL correctly. Also, it seems that IE/EDGE // did not unescape semicolons in these URLs at some point in the past. We // take a best-effort approach. // // If the URL has semicolons (which may happen in some cases, see // http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2 // for instance), wrap it in single quotes to protect the semicolons. // If the URL has semicolons and single quotes, url-encode the single quotes // as well. // // This is imperfect. Notice that both ' and ; are reserved characters in // URIs, so this could do the wrong thing, but at least it will do the wrong // thing in only rare cases. if (goog.string.contains(unwrappedUrl, ';')) { unwrappedUrl = "'" + unwrappedUrl.replace(/'/g, '%27') + "'"; } } var attributes = { 'http-equiv': 'refresh', 'content': (opt_secs || 0) + '; url=' + unwrappedUrl }; // This function will handle the HTML escaping for attributes. return goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse( 'meta', attributes); }; /** * @param {string} tagName The tag name. * @param {string} name The attribute name. * @param {!goog.html.SafeHtml.AttributeValue} value The attribute value. * @return {string} A "name=value" string. * @throws {Error} If attribute value is unsafe for the given tag and attribute. * @private */ goog.html.SafeHtml.getAttrNameAndValue_ = function(tagName, name, value) { // If it's goog.string.Const, allow any valid attribute name. if (value instanceof goog.string.Const) { value = goog.string.Const.unwrap(value); } else if (name.toLowerCase() == 'style') { value = goog.html.SafeHtml.getStyleValue_(value); } else if (/^on/i.test(name)) { // TODO(jakubvrana): Disallow more attributes with a special meaning. throw new Error( 'Attribute "' + name + '" requires goog.string.Const value, "' + value + '" given.'); // URL attributes handled differently according to tag. } else if (name.toLowerCase() in goog.html.SafeHtml.URL_ATTRIBUTES_) { if (value instanceof goog.html.TrustedResourceUrl) { value = goog.html.TrustedResourceUrl.unwrap(value); } else if (value instanceof goog.html.SafeUrl) { value = goog.html.SafeUrl.unwrap(value); } else if (goog.isString(value)) { value = goog.html.SafeUrl.sanitize(value).getTypedStringValue(); } else { throw new Error( 'Attribute "' + name + '" on tag "' + tagName + '" requires goog.html.SafeUrl, goog.string.Const, or string,' + ' value "' + value + '" given.'); } } // Accept SafeUrl, TrustedResourceUrl, etc. for attributes which only require // HTML-escaping. if (value.implementsGoogStringTypedString) { // Ok to call getTypedStringValue() since there's no reliance on the type // contract for security here. value = /** @type {!goog.string.TypedString} */ (value).getTypedStringValue(); } goog.asserts.assert( goog.isString(value) || goog.isNumber(value), 'String or number value expected, got ' + (typeof value) + ' with value: ' + value); return name + '="' + goog.string.htmlEscape(String(value)) + '"'; }; /** * Gets value allowed in "style" attribute. * @param {!goog.html.SafeHtml.AttributeValue} value It could be SafeStyle or a * map which will be passed to goog.html.SafeStyle.create. * @return {string} Unwrapped value. * @throws {Error} If string value is given. * @private */ goog.html.SafeHtml.getStyleValue_ = function(value) { if (!goog.isObject(value)) { throw new Error( 'The "style" attribute requires goog.html.SafeStyle or map ' + 'of style properties, ' + (typeof value) + ' given: ' + value); } if (!(value instanceof goog.html.SafeStyle)) { // Process the property bag into a style object. value = goog.html.SafeStyle.create(value); } return goog.html.SafeStyle.unwrap(value); }; /** * Creates a SafeHtml content with known directionality consisting of a tag with * optional attributes and optional content. * @param {!goog.i18n.bidi.Dir} dir Directionality. * @param {string} tagName * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * @param {!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>=} opt_content * @return {!goog.html.SafeHtml} The SafeHtml content with the tag. */ goog.html.SafeHtml.createWithDir = function( dir, tagName, opt_attributes, opt_content) { var html = goog.html.SafeHtml.create(tagName, opt_attributes, opt_content); html.dir_ = dir; return html; }; /** * Creates a new SafeHtml object by concatenating values. * @param {...(!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Values to concatenate. * @return {!goog.html.SafeHtml} */ goog.html.SafeHtml.concat = function(var_args) { var dir = goog.i18n.bidi.Dir.NEUTRAL; var content = ''; /** * @param {!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>} argument */ var addArgument = function(argument) { if (goog.isArray(argument)) { goog.array.forEach(argument, addArgument); } else { var html = goog.html.SafeHtml.htmlEscape(argument); content += goog.html.SafeHtml.unwrap(html); var htmlDir = html.getDirection(); if (dir == goog.i18n.bidi.Dir.NEUTRAL) { dir = htmlDir; } else if (htmlDir != goog.i18n.bidi.Dir.NEUTRAL && dir != htmlDir) { dir = null; } } }; goog.array.forEach(arguments, addArgument); return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( content, dir); }; /** * Creates a new SafeHtml object with known directionality by concatenating the * values. * @param {!goog.i18n.bidi.Dir} dir Directionality. * @param {...(!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>)} var_args Elements of array * arguments would be processed recursively. * @return {!goog.html.SafeHtml} */ goog.html.SafeHtml.concatWithDir = function(dir, var_args) { var html = goog.html.SafeHtml.concat(goog.array.slice(arguments, 1)); html.dir_ = dir; return html; }; /** * Type marker for the SafeHtml type, used to implement additional run-time * type checking. * @const {!Object} * @private */ goog.html.SafeHtml.TYPE_MARKER_GOOG_HTML_SECURITY_PRIVATE_ = {}; /** * Package-internal utility method to create SafeHtml instances. * * @param {string} html The string to initialize the SafeHtml object with. * @param {?goog.i18n.bidi.Dir} dir The directionality of the SafeHtml to be * constructed, or null if unknown. * @return {!goog.html.SafeHtml} The initialized SafeHtml object. * @package */ goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse = function( html, dir) { return new goog.html.SafeHtml().initSecurityPrivateDoNotAccessOrElse_( html, dir); }; /** * Called from createSafeHtmlSecurityPrivateDoNotAccessOrElse(). This * method exists only so that the compiler can dead code eliminate static * fields (like EMPTY) when they're not accessed. * @param {string} html * @param {?goog.i18n.bidi.Dir} dir * @return {!goog.html.SafeHtml} * @private */ goog.html.SafeHtml.prototype.initSecurityPrivateDoNotAccessOrElse_ = function( html, dir) { this.privateDoNotAccessOrElseSafeHtmlWrappedValue_ = html; this.dir_ = dir; return this; }; /** * Like create() but does not restrict which tags can be constructed. * * @param {string} tagName Tag name. Set or validated by caller. * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * @param {(!goog.html.SafeHtml.TextOrHtml_| * !Array<!goog.html.SafeHtml.TextOrHtml_>)=} opt_content * @return {!goog.html.SafeHtml} * @throws {Error} If invalid or unsafe attribute name or value is provided. * @throws {goog.asserts.AssertionError} If content for void tag is provided. * @package */ goog.html.SafeHtml.createSafeHtmlTagSecurityPrivateDoNotAccessOrElse = function( tagName, opt_attributes, opt_content) { var dir = null; var result = '<' + tagName; result += goog.html.SafeHtml.stringifyAttributes(tagName, opt_attributes); var content = opt_content; if (!goog.isDefAndNotNull(content)) { content = []; } else if (!goog.isArray(content)) { content = [content]; } if (goog.dom.tags.isVoidTag(tagName.toLowerCase())) { goog.asserts.assert( !content.length, 'Void tag <' + tagName + '> does not allow content.'); result += '>'; } else { var html = goog.html.SafeHtml.concat(content); result += '>' + goog.html.SafeHtml.unwrap(html) + '</' + tagName + '>'; dir = html.getDirection(); } var dirAttribute = opt_attributes && opt_attributes['dir']; if (dirAttribute) { if (/^(ltr|rtl|auto)$/i.test(dirAttribute)) { // If the tag has the "dir" attribute specified then its direction is // neutral because it can be safely used in any context. dir = goog.i18n.bidi.Dir.NEUTRAL; } else { dir = null; } } return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( result, dir); }; /** * Creates a string with attributes to insert after tagName. * @param {string} tagName * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * @return {string} Returns an empty string if there are no attributes, returns * a string starting with a space otherwise. * @throws {Error} If attribute value is unsafe for the given tag and attribute. * @package */ goog.html.SafeHtml.stringifyAttributes = function(tagName, opt_attributes) { var result = ''; if (opt_attributes) { for (var name in opt_attributes) { if (!goog.html.SafeHtml.VALID_NAMES_IN_TAG_.test(name)) { throw new Error('Invalid attribute name "' + name + '".'); } var value = opt_attributes[name]; if (!goog.isDefAndNotNull(value)) { continue; } result += ' ' + goog.html.SafeHtml.getAttrNameAndValue_(tagName, name, value); } } return result; }; /** * @param {!Object<string, ?goog.html.SafeHtml.AttributeValue>} fixedAttributes * @param {!Object<string, string>} defaultAttributes * @param {?Object<string, ?goog.html.SafeHtml.AttributeValue>=} opt_attributes * Optional attributes passed to create*(). * @return {!Object<string, ?goog.html.SafeHtml.AttributeValue>} * @throws {Error} If opt_attributes contains an attribute with the same name * as an attribute in fixedAttributes. * @package */ goog.html.SafeHtml.combineAttributes = function( fixedAttributes, defaultAttributes, opt_attributes) { var combinedAttributes = {}; var name; for (name in fixedAttributes) { goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); combinedAttributes[name] = fixedAttributes[name]; } for (name in defaultAttributes) { goog.asserts.assert(name.toLowerCase() == name, 'Must be lower case'); combinedAttributes[name] = defaultAttributes[name]; } for (name in opt_attributes) { var nameLower = name.toLowerCase(); if (nameLower in fixedAttributes) { throw new Error( 'Cannot override "' + nameLower + '" attribute, got "' + name + '" with value "' + opt_attributes[name] + '"'); } if (nameLower in defaultAttributes) { delete combinedAttributes[nameLower]; } combinedAttributes[name] = opt_attributes[name]; } return combinedAttributes; }; /** * A SafeHtml instance corresponding to the HTML doctype: "<!DOCTYPE html>". * @const {!goog.html.SafeHtml} */ goog.html.SafeHtml.DOCTYPE_HTML = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( '<!DOCTYPE html>', goog.i18n.bidi.Dir.NEUTRAL); /** * A SafeHtml instance corresponding to the empty string. * @const {!goog.html.SafeHtml} */ goog.html.SafeHtml.EMPTY = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( '', goog.i18n.bidi.Dir.NEUTRAL); /** * A SafeHtml instance corresponding to the <br> tag. * @const {!goog.html.SafeHtml} */ goog.html.SafeHtml.BR = goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( '<br>', goog.i18n.bidi.Dir.NEUTRAL); //javascript/closure/html/uncheckedconversions.js // Copyright 2013 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Unchecked conversions to create values of goog.html types from * plain strings. Use of these functions could potentially result in instances * of goog.html types that violate their type contracts, and hence result in * security vulnerabilties. * * Therefore, all uses of the methods herein must be carefully security * reviewed. Avoid use of the methods in this file whenever possible; instead * prefer to create instances of goog.html types using inherently safe builders * or template systems. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * MOE:begin_intracomment_strip * MAINTAINERS: Use of these functions is detected with a Tricorder analyzer. * If adding functions here also add them to analyzer's list at * j/c/g/devtools/staticanalysis/pipeline/analyzers/shared/SafeHtmlAnalyzers.java. * MOE:end_intracomment_strip * * @visibility {//javascript/closure/html:approved_for_unchecked_conversion} * @visibility {//javascript/closure/bin/sizetests:__pkg__} */ goog.provide('goog.html.uncheckedconversions'); goog.require('goog.asserts'); goog.require('goog.html.SafeHtml'); goog.require('goog.html.SafeScript'); goog.require('goog.html.SafeStyle'); goog.require('goog.html.SafeStyleSheet'); goog.require('goog.html.SafeUrl'); goog.require('goog.html.TrustedResourceUrl'); goog.require('goog.string'); goog.require('goog.string.Const'); /** * Performs an "unchecked conversion" to SafeHtml from a plain string that is * known to satisfy the SafeHtml type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `html` satisfies the SafeHtml type contract in all * possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} html A string that is claimed to adhere to the SafeHtml * contract. * @param {?goog.i18n.bidi.Dir=} opt_dir The optional directionality of the * SafeHtml to be constructed. A null or undefined value signifies an * unknown directionality. * @return {!goog.html.SafeHtml} The value of html, wrapped in a SafeHtml * object. */ goog.html.uncheckedconversions.safeHtmlFromStringKnownToSatisfyTypeContract = function(justification, html, opt_dir) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.SafeHtml.createSafeHtmlSecurityPrivateDoNotAccessOrElse( html, opt_dir || null); }; /** * Performs an "unchecked conversion" to SafeScript from a plain string that is * known to satisfy the SafeScript type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `script` satisfies the SafeScript type contract in * all possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} script The string to wrap as a SafeScript. * @return {!goog.html.SafeScript} The value of `script`, wrapped in a * SafeScript object. */ goog.html.uncheckedconversions.safeScriptFromStringKnownToSatisfyTypeContract = function(justification, script) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.SafeScript.createSafeScriptSecurityPrivateDoNotAccessOrElse( script); }; /** * Performs an "unchecked conversion" to SafeStyle from a plain string that is * known to satisfy the SafeStyle type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `style` satisfies the SafeStyle type contract in all * possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} style The string to wrap as a SafeStyle. * @return {!goog.html.SafeStyle} The value of `style`, wrapped in a * SafeStyle object. */ goog.html.uncheckedconversions.safeStyleFromStringKnownToSatisfyTypeContract = function(justification, style) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.SafeStyle.createSafeStyleSecurityPrivateDoNotAccessOrElse( style); }; /** * Performs an "unchecked conversion" to SafeStyleSheet from a plain string * that is known to satisfy the SafeStyleSheet type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `styleSheet` satisfies the SafeStyleSheet type * contract in all possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} styleSheet The string to wrap as a SafeStyleSheet. * @return {!goog.html.SafeStyleSheet} The value of `styleSheet`, wrapped * in a SafeStyleSheet object. */ goog.html.uncheckedconversions .safeStyleSheetFromStringKnownToSatisfyTypeContract = function( justification, styleSheet) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.SafeStyleSheet .createSafeStyleSheetSecurityPrivateDoNotAccessOrElse(styleSheet); }; /** * Performs an "unchecked conversion" to SafeUrl from a plain string that is * known to satisfy the SafeUrl type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `url` satisfies the SafeUrl type contract in all * possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} url The string to wrap as a SafeUrl. * @return {!goog.html.SafeUrl} The value of `url`, wrapped in a SafeUrl * object. */ goog.html.uncheckedconversions.safeUrlFromStringKnownToSatisfyTypeContract = function(justification, url) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.SafeUrl.createSafeUrlSecurityPrivateDoNotAccessOrElse(url); }; /** * Performs an "unchecked conversion" to TrustedResourceUrl from a plain string * that is known to satisfy the TrustedResourceUrl type contract. * * IMPORTANT: Uses of this method must be carefully security-reviewed to ensure * that the value of `url` satisfies the TrustedResourceUrl type contract * in all possible program states. * * MOE:begin_intracomment_strip * See http://go/safehtml-unchecked for guidelines on using these functions. * MOE:end_intracomment_strip * * @param {!goog.string.Const} justification A constant string explaining why * this use of this method is safe. May include a security review ticket * number. * @param {string} url The string to wrap as a TrustedResourceUrl. * @return {!goog.html.TrustedResourceUrl} The value of `url`, wrapped in * a TrustedResourceUrl object. */ goog.html.uncheckedconversions .trustedResourceUrlFromStringKnownToSatisfyTypeContract = function( justification, url) { // unwrap() called inside an assert so that justification can be optimized // away in production code. goog.asserts.assertString( goog.string.Const.unwrap(justification), 'must provide justification'); goog.asserts.assert( !goog.string.isEmptyOrWhitespace(goog.string.Const.unwrap(justification)), 'must provide non-empty justification'); return goog.html.TrustedResourceUrl .createTrustedResourceUrlSecurityPrivateDoNotAccessOrElse(url); }; //javascript/closure/i18n/bidiformatter.js // Copyright 2009 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Utility for formatting text for display in a potentially * opposite-directionality context without garbling. * Mostly a port of http://go/formatter.cc. * @author <EMAIL> (<NAME>) */ goog.provide('goog.i18n.BidiFormatter'); goog.require('goog.html.SafeHtml'); goog.require('goog.i18n.bidi'); goog.require('goog.i18n.bidi.Dir'); goog.require('goog.i18n.bidi.Format'); /** * Utility class for formatting text for display in a potentially * opposite-directionality context without garbling. Provides the following * functionality: * * 1. BiDi Wrapping * When text in one language is mixed into a document in another, opposite- * directionality language, e.g. when an English business name is embedded in a * Hebrew web page, both the inserted string and the text following it may be * displayed incorrectly unless the inserted string is explicitly separated * from the surrounding text in a "wrapper" that declares its directionality at * the start and then resets it back at the end. This wrapping can be done in * HTML mark-up (e.g. a 'span dir="rtl"' tag) or - only in contexts where * mark-up can not be used - in Unicode BiDi formatting codes (LRE|RLE and PDF). * Providing such wrapping services is the basic purpose of the BiDi formatter. * * 2. Directionality estimation * How does one know whether a string about to be inserted into surrounding * text has the same directionality? Well, in many cases, one knows that this * must be the case when writing the code doing the insertion, e.g. when a * localized message is inserted into a localized page. In such cases there is * no need to involve the BiDi formatter at all. In the remaining cases, e.g. * when the string is user-entered or comes from a database, the language of * the string (and thus its directionality) is not known a priori, and must be * estimated at run-time. The BiDi formatter does this automatically. * * 3. Escaping * When wrapping plain text - i.e. text that is not already HTML or HTML- * escaped - in HTML mark-up, the text must first be HTML-escaped to prevent XSS * attacks and other nasty business. This of course is always true, but the * escaping can not be done after the string has already been wrapped in * mark-up, so the BiDi formatter also serves as a last chance and includes * escaping services. * * Thus, in a single call, the formatter will escape the input string as * specified, determine its directionality, and wrap it as necessary. It is * then up to the caller to insert the return value in the output. * * See http://wiki/Main/TemplatesAndBiDi for more information. * * @param {goog.i18n.bidi.Dir|number|boolean|null} contextDir The context * directionality, in one of the following formats: * 1. A goog.i18n.bidi.Dir constant. NEUTRAL is treated the same as null, * i.e. unknown, for backward compatibility with legacy calls. * 2. A number (positive = LTR, negative = RTL, 0 = unknown). * 3. A boolean (true = RTL, false = LTR). * 4. A null for unknown directionality. * @param {boolean=} opt_alwaysSpan Whether {@link #spanWrap} should always * use a 'span' tag, even when the input directionality is neutral or * matches the context, so that the DOM structure of the output does not * depend on the combination of directionalities. Default: false. * @constructor * @final */ goog.i18n.BidiFormatter = function(contextDir, opt_alwaysSpan) { /** * The overall directionality of the context in which the formatter is being * used. * @type {?goog.i18n.bidi.Dir} * @private */ this.contextDir_ = goog.i18n.bidi.toDir(contextDir, true /* opt_noNeutral */); /** * Whether {@link #spanWrap} and similar methods should always use the same * span structure, regardless of the combination of directionalities, for a * stable DOM structure. * @type {boolean} * @private */ this.alwaysSpan_ = !!opt_alwaysSpan; }; /** * @return {?goog.i18n.bidi.Dir} The context directionality. */ goog.i18n.BidiFormatter.prototype.getContextDir = function() { return this.contextDir_; }; /** * @return {boolean} Whether alwaysSpan is set. */ goog.i18n.BidiFormatter.prototype.getAlwaysSpan = function() { return this.alwaysSpan_; }; /** * @param {goog.i18n.bidi.Dir|number|boolean|null} contextDir The context * directionality, in one of the following formats: * 1. A goog.i18n.bidi.Dir constant. NEUTRAL is treated the same as null, * i.e. unknown. * 2. A number (positive = LTR, negative = RTL, 0 = unknown). * 3. A boolean (true = RTL, false = LTR). * 4. A null for unknown directionality. */ goog.i18n.BidiFormatter.prototype.setContextDir = function(contextDir) { this.contextDir_ = goog.i18n.bidi.toDir(contextDir, true /* opt_noNeutral */); }; /** * @param {boolean} alwaysSpan Whether {@link #spanWrap} should always use a * 'span' tag, even when the input directionality is neutral or matches the * context, so that the DOM structure of the output does not depend on the * combination of directionalities. */ goog.i18n.BidiFormatter.prototype.setAlwaysSpan = function(alwaysSpan) { this.alwaysSpan_ = alwaysSpan; }; /** * Returns the directionality of input argument `str`. * Identical to {@link goog.i18n.bidi.estimateDirection}. * * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @return {goog.i18n.bidi.Dir} Estimated overall directionality of `str`. */ goog.i18n.BidiFormatter.prototype.estimateDirection = goog.i18n.bidi.estimateDirection; /** * Returns true if two given directionalities are opposite. * Note: the implementation is based on the numeric values of the Dir enum. * * @param {?goog.i18n.bidi.Dir} dir1 1st directionality. * @param {?goog.i18n.bidi.Dir} dir2 2nd directionality. * @return {boolean} Whether the directionalities are opposite. * @private */ goog.i18n.BidiFormatter.prototype.areDirectionalitiesOpposite_ = function( dir1, dir2) { return Number(dir1) * Number(dir2) < 0; }; /** * Returns a unicode BiDi mark matching the context directionality (LRM or * RLM) if `opt_dirReset`, and if either the directionality or the exit * directionality of `str` is opposite to the context directionality. * Otherwise returns the empty string. * * @param {string} str The input text. * @param {goog.i18n.bidi.Dir} dir `str`'s overall directionality. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @param {boolean=} opt_dirReset Whether to perform the reset. Default: false. * @return {string} A unicode BiDi mark or the empty string. * @private */ goog.i18n.BidiFormatter.prototype.dirResetIfNeeded_ = function( str, dir, opt_isHtml, opt_dirReset) { // endsWithRtl and endsWithLtr are called only if needed (short-circuit). if (opt_dirReset && (this.areDirectionalitiesOpposite_(dir, this.contextDir_) || (this.contextDir_ == goog.i18n.bidi.Dir.LTR && goog.i18n.bidi.endsWithRtl(str, opt_isHtml)) || (this.contextDir_ == goog.i18n.bidi.Dir.RTL && goog.i18n.bidi.endsWithLtr(str, opt_isHtml)))) { return this.contextDir_ == goog.i18n.bidi.Dir.LTR ? goog.i18n.bidi.Format.LRM : goog.i18n.bidi.Format.RLM; } else { return ''; } }; /** * Returns "rtl" if `str`'s estimated directionality is RTL, and "ltr" if * it is LTR. In case it's NEUTRAL, returns "rtl" if the context directionality * is RTL, and "ltr" otherwise. * Needed for GXP, which can't handle dirAttr. * Example use case: * &lt;td expr:dir='bidiFormatter.dirAttrValue(foo)'&gt; * &lt;gxp:eval expr='foo'&gt; * &lt;/td&gt; * * @param {string} str Text whose directionality is to be estimated. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @return {string} "rtl" or "ltr", according to the logic described above. */ goog.i18n.BidiFormatter.prototype.dirAttrValue = function(str, opt_isHtml) { return this.knownDirAttrValue(this.estimateDirection(str, opt_isHtml)); }; /** * Returns "rtl" if the given directionality is RTL, and "ltr" if it is LTR. In * case it's NEUTRAL, returns "rtl" if the context directionality is RTL, and * "ltr" otherwise. * * @param {goog.i18n.bidi.Dir} dir A directionality. * @return {string} "rtl" or "ltr", according to the logic described above. */ goog.i18n.BidiFormatter.prototype.knownDirAttrValue = function(dir) { var resolvedDir = dir == goog.i18n.bidi.Dir.NEUTRAL ? this.contextDir_ : dir; return resolvedDir == goog.i18n.bidi.Dir.RTL ? 'rtl' : 'ltr'; }; /** * Returns 'dir="ltr"' or 'dir="rtl"', depending on `str`'s estimated * directionality, if it is not the same as the context directionality. * Otherwise, returns the empty string. * * @param {string} str Text whose directionality is to be estimated. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @return {string} 'dir="rtl"' for RTL text in non-RTL context; 'dir="ltr"' for * LTR text in non-LTR context; else, the empty string. */ goog.i18n.BidiFormatter.prototype.dirAttr = function(str, opt_isHtml) { return this.knownDirAttr(this.estimateDirection(str, opt_isHtml)); }; /** * Returns 'dir="ltr"' or 'dir="rtl"', depending on the given directionality, if * it is not the same as the context directionality. Otherwise, returns the * empty string. * * @param {goog.i18n.bidi.Dir} dir A directionality. * @return {string} 'dir="rtl"' for RTL text in non-RTL context; 'dir="ltr"' for * LTR text in non-LTR context; else, the empty string. */ goog.i18n.BidiFormatter.prototype.knownDirAttr = function(dir) { if (dir != this.contextDir_) { return dir == goog.i18n.bidi.Dir.RTL ? 'dir="rtl"' : dir == goog.i18n.bidi.Dir.LTR ? 'dir="ltr"' : ''; } return ''; }; /** * Formats a string of unknown directionality for use in HTML output of the * context directionality, so an opposite-directionality string is neither * garbled nor garbles what follows it. * The algorithm: estimates the directionality of input argument `html`. * In case its directionality doesn't match the context directionality, wraps it * with a 'span' tag and adds a "dir" attribute (either 'dir="rtl"' or * 'dir="ltr"'). If setAlwaysSpan(true) was used, the input is always wrapped * with 'span', skipping just the dir attribute when it's not needed. * * If `opt_dirReset`, and if the overall directionality or the exit * directionality of `str` are opposite to the context directionality, a * trailing unicode BiDi mark matching the context directionality is appened * (LRM or RLM). * * @param {!goog.html.SafeHtml} html The input HTML. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `html`. Default: true. * @return {!goog.html.SafeHtml} Input text after applying the processing. */ goog.i18n.BidiFormatter.prototype.spanWrapSafeHtml = function( html, opt_dirReset) { return this.spanWrapSafeHtmlWithKnownDir(null, html, opt_dirReset); }; /** * Formats a string of given directionality for use in HTML output of the * context directionality, so an opposite-directionality string is neither * garbled nor garbles what follows it. * The algorithm: If `dir` doesn't match the context directionality, wraps * `html` with a 'span' tag and adds a "dir" attribute (either 'dir="rtl"' * or 'dir="ltr"'). If setAlwaysSpan(true) was used, the input is always wrapped * with 'span', skipping just the dir attribute when it's not needed. * * If `opt_dirReset`, and if `dir` or the exit directionality of * `html` are opposite to the context directionality, a trailing unicode * BiDi mark matching the context directionality is appened (LRM or RLM). * * @param {?goog.i18n.bidi.Dir} dir `html`'s overall directionality, or * null if unknown and needs to be estimated. * @param {!goog.html.SafeHtml} html The input HTML. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `html`. Default: true. * @return {!goog.html.SafeHtml} Input text after applying the processing. */ goog.i18n.BidiFormatter.prototype.spanWrapSafeHtmlWithKnownDir = function( dir, html, opt_dirReset) { if (dir == null) { dir = this.estimateDirection(goog.html.SafeHtml.unwrap(html), true); } return this.spanWrapWithKnownDir_(dir, html, opt_dirReset); }; /** * The internal implementation of spanWrapSafeHtmlWithKnownDir for non-null dir, * to help the compiler optimize. * * @param {goog.i18n.bidi.Dir} dir `str`'s overall directionality. * @param {!goog.html.SafeHtml} html The input HTML. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `str`. Default: true. * @return {!goog.html.SafeHtml} Input text after applying the above processing. * @private */ goog.i18n.BidiFormatter.prototype.spanWrapWithKnownDir_ = function( dir, html, opt_dirReset) { opt_dirReset = opt_dirReset || (opt_dirReset == undefined); var result; // Whether to add the "dir" attribute. var dirCondition = dir != goog.i18n.bidi.Dir.NEUTRAL && dir != this.contextDir_; if (this.alwaysSpan_ || dirCondition) { // Wrap is needed var dirAttribute; if (dirCondition) { dirAttribute = dir == goog.i18n.bidi.Dir.RTL ? 'rtl' : 'ltr'; } result = goog.html.SafeHtml.create('span', {'dir': dirAttribute}, html); } else { result = html; } var str = goog.html.SafeHtml.unwrap(html); result = goog.html.SafeHtml.concatWithDir( goog.i18n.bidi.Dir.NEUTRAL, result, this.dirResetIfNeeded_(str, dir, true, opt_dirReset)); return result; }; /** * Formats a string of unknown directionality for use in plain-text output of * the context directionality, so an opposite-directionality string is neither * garbled nor garbles what follows it. * As opposed to {@link #spanWrap}, this makes use of unicode BiDi formatting * characters. In HTML, its *only* valid use is inside of elements that do not * allow mark-up, e.g. an 'option' tag. * The algorithm: estimates the directionality of input argument `str`. * In case it doesn't match the context directionality, wraps it with Unicode * BiDi formatting characters: RLE`str`PDF for RTL text, and * LRE`str`PDF for LTR text. * * If `opt_dirReset`, and if the overall directionality or the exit * directionality of `str` are opposite to the context directionality, a * trailing unicode BiDi mark matching the context directionality is appended * (LRM or RLM). * * Does *not* do HTML-escaping regardless of the value of `opt_isHtml`. * The return value can be HTML-escaped as necessary. * * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `str`. Default: true. * @return {string} Input text after applying the above processing. */ goog.i18n.BidiFormatter.prototype.unicodeWrap = function( str, opt_isHtml, opt_dirReset) { return this.unicodeWrapWithKnownDir(null, str, opt_isHtml, opt_dirReset); }; /** * Formats a string of given directionality for use in plain-text output of the * context directionality, so an opposite-directionality string is neither * garbled nor garbles what follows it. * As opposed to {@link #spanWrapWithKnownDir}, makes use of unicode BiDi * formatting characters. In HTML, its *only* valid use is inside of elements * that do not allow mark-up, e.g. an 'option' tag. * The algorithm: If `dir` doesn't match the context directionality, wraps * `str` with Unicode BiDi formatting characters: RLE`str`PDF for * RTL text, and LRE`str`PDF for LTR text. * * If `opt_dirReset`, and if the overall directionality or the exit * directionality of `str` are opposite to the context directionality, a * trailing unicode BiDi mark matching the context directionality is appended * (LRM or RLM). * * Does *not* do HTML-escaping regardless of the value of `opt_isHtml`. * The return value can be HTML-escaped as necessary. * * @param {?goog.i18n.bidi.Dir} dir `str`'s overall directionality, or * null if unknown and needs to be estimated. * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `str`. Default: true. * @return {string} Input text after applying the above processing. */ goog.i18n.BidiFormatter.prototype.unicodeWrapWithKnownDir = function( dir, str, opt_isHtml, opt_dirReset) { if (dir == null) { dir = this.estimateDirection(str, opt_isHtml); } return this.unicodeWrapWithKnownDir_(dir, str, opt_isHtml, opt_dirReset); }; /** * The internal implementation of unicodeWrapWithKnownDir for non-null dir, to * help the compiler optimize. * * @param {goog.i18n.bidi.Dir} dir `str`'s overall directionality. * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @param {boolean=} opt_dirReset Whether to append a trailing unicode bidi mark * matching the context directionality, when needed, to prevent the possible * garbling of whatever may follow `str`. Default: true. * @return {string} Input text after applying the above processing. * @private */ goog.i18n.BidiFormatter.prototype.unicodeWrapWithKnownDir_ = function( dir, str, opt_isHtml, opt_dirReset) { opt_dirReset = opt_dirReset || (opt_dirReset == undefined); var result = []; if (dir != goog.i18n.bidi.Dir.NEUTRAL && dir != this.contextDir_) { result.push( dir == goog.i18n.bidi.Dir.RTL ? goog.i18n.bidi.Format.RLE : goog.i18n.bidi.Format.LRE); result.push(str); result.push(goog.i18n.bidi.Format.PDF); } else { result.push(str); } result.push(this.dirResetIfNeeded_(str, dir, opt_isHtml, opt_dirReset)); return result.join(''); }; /** * Returns a Unicode BiDi mark matching the context directionality (LRM or RLM) * if the directionality or the exit directionality of `str` are opposite * to the context directionality. Otherwise returns the empty string. * * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @return {string} A Unicode bidi mark matching the global directionality or * the empty string. */ goog.i18n.BidiFormatter.prototype.markAfter = function(str, opt_isHtml) { return this.markAfterKnownDir(null, str, opt_isHtml); }; /** * Returns a Unicode BiDi mark matching the context directionality (LRM or RLM) * if the given directionality or the exit directionality of `str` are * opposite to the context directionality. Otherwise returns the empty string. * * @param {?goog.i18n.bidi.Dir} dir `str`'s overall directionality, or * null if unknown and needs to be estimated. * @param {string} str The input text. * @param {boolean=} opt_isHtml Whether `str` is HTML / HTML-escaped. * Default: false. * @return {string} A Unicode bidi mark matching the global directionality or * the empty string. */ goog.i18n.BidiFormatter.prototype.markAfterKnownDir = function( dir, str, opt_isHtml) { if (dir == null) { dir = this.estimateDirection(str, opt_isHtml); } return this.dirResetIfNeeded_(str, dir, opt_isHtml, true); }; /** * Returns the Unicode BiDi mark matching the context directionality (LRM for * LTR context directionality, RLM for RTL context directionality), or the * empty string for neutral / unknown context directionality. * * @return {string} LRM for LTR context directionality and RLM for RTL context * directionality. */ goog.i18n.BidiFormatter.prototype.mark = function() { switch (this.contextDir_) { case (goog.i18n.bidi.Dir.LTR): return goog.i18n.bidi.Format.LRM; case (goog.i18n.bidi.Dir.RTL): return goog.i18n.bidi.Format.RLM; default: return ''; } }; /** * Returns 'right' for RTL context directionality. Otherwise (LTR or neutral / * unknown context directionality) returns 'left'. * * @return {string} 'right' for RTL context directionality and 'left' for other * context directionality. */ goog.i18n.BidiFormatter.prototype.startEdge = function() { return this.contextDir_ == goog.i18n.bidi.Dir.RTL ? goog.i18n.bidi.RIGHT : goog.i18n.bidi.LEFT; }; /** * Returns 'left' for RTL context directionality. Otherwise (LTR or neutral / * unknown context directionality) returns 'right'. * * @return {string} 'left' for RTL context directionality and 'right' for other * context directionality. */ goog.i18n.BidiFormatter.prototype.endEdge = function() { return this.contextDir_ == goog.i18n.bidi.Dir.RTL ? goog.i18n.bidi.LEFT : goog.i18n.bidi.RIGHT; }; //javascript/closure/math/math.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Additional mathematical functions. * @author <EMAIL> (<NAME>) */ goog.provide('goog.math'); goog.require('goog.array'); goog.require('goog.asserts'); /** * Returns a random integer greater than or equal to 0 and less than `a`. * @param {number} a The upper bound for the random integer (exclusive). * @return {number} A random integer N such that 0 <= N < a. */ goog.math.randomInt = function(a) { return Math.floor(Math.random() * a); }; /** * Returns a random number greater than or equal to `a` and less than * `b`. * @param {number} a The lower bound for the random number (inclusive). * @param {number} b The upper bound for the random number (exclusive). * @return {number} A random number N such that a <= N < b. */ goog.math.uniformRandom = function(a, b) { return a + Math.random() * (b - a); }; /** * Takes a number and clamps it to within the provided bounds. * @param {number} value The input number. * @param {number} min The minimum value to return. * @param {number} max The maximum value to return. * @return {number} The input number if it is within bounds, or the nearest * number within the bounds. */ goog.math.clamp = function(value, min, max) { return Math.min(Math.max(value, min), max); }; /** * The % operator in JavaScript returns the remainder of a / b, but differs from * some other languages in that the result will have the same sign as the * dividend. For example, -1 % 8 == -1, whereas in some other languages * (such as Python) the result would be 7. This function emulates the more * correct modulo behavior, which is useful for certain applications such as * calculating an offset index in a circular list. * * @param {number} a The dividend. * @param {number} b The divisor. * @return {number} a % b where the result is between 0 and b (either 0 <= x < b * or b < x <= 0, depending on the sign of b). */ goog.math.modulo = function(a, b) { var r = a % b; // If r and b differ in sign, add b to wrap the result to the correct sign. return (r * b < 0) ? r + b : r; }; /** * Performs linear interpolation between values a and b. Returns the value * between a and b proportional to x (when x is between 0 and 1. When x is * outside this range, the return value is a linear extrapolation). * @param {number} a A number. * @param {number} b A number. * @param {number} x The proportion between a and b. * @return {number} The interpolated value between a and b. */ goog.math.lerp = function(a, b, x) { return a + x * (b - a); }; /** * Tests whether the two values are equal to each other, within a certain * tolerance to adjust for floating point errors. * @param {number} a A number. * @param {number} b A number. * @param {number=} opt_tolerance Optional tolerance range. Defaults * to 0.000001. If specified, should be greater than 0. * @return {boolean} Whether `a` and `b` are nearly equal. */ goog.math.nearlyEquals = function(a, b, opt_tolerance) { return Math.abs(a - b) <= (opt_tolerance || 0.000001); }; // TODO(jrajeshwar): Rename to normalizeAngle, retaining old name as deprecated // alias. /** * Normalizes an angle to be in range [0-360). Angles outside this range will * be normalized to be the equivalent angle with that range. * @param {number} angle Angle in degrees. * @return {number} Standardized angle. */ goog.math.standardAngle = function(angle) { return goog.math.modulo(angle, 360); }; /** * Normalizes an angle to be in range [0-2*PI). Angles outside this range will * be normalized to be the equivalent angle with that range. * @param {number} angle Angle in radians. * @return {number} Standardized angle. */ goog.math.standardAngleInRadians = function(angle) { return goog.math.modulo(angle, 2 * Math.PI); }; /** * Converts degrees to radians. * @param {number} angleDegrees Angle in degrees. * @return {number} Angle in radians. */ goog.math.toRadians = function(angleDegrees) { return angleDegrees * Math.PI / 180; }; /** * Converts radians to degrees. * @param {number} angleRadians Angle in radians. * @return {number} Angle in degrees. */ goog.math.toDegrees = function(angleRadians) { return angleRadians * 180 / Math.PI; }; /** * For a given angle and radius, finds the X portion of the offset. * @param {number} degrees Angle in degrees (zero points in +X direction). * @param {number} radius Radius. * @return {number} The x-distance for the angle and radius. */ goog.math.angleDx = function(degrees, radius) { return radius * Math.cos(goog.math.toRadians(degrees)); }; /** * For a given angle and radius, finds the Y portion of the offset. * @param {number} degrees Angle in degrees (zero points in +X direction). * @param {number} radius Radius. * @return {number} The y-distance for the angle and radius. */ goog.math.angleDy = function(degrees, radius) { return radius * Math.sin(goog.math.toRadians(degrees)); }; /** * Computes the angle between two points (x1,y1) and (x2,y2). * Angle zero points in the +X direction, 90 degrees points in the +Y * direction (down) and from there we grow clockwise towards 360 degrees. * @param {number} x1 x of first point. * @param {number} y1 y of first point. * @param {number} x2 x of second point. * @param {number} y2 y of second point. * @return {number} Standardized angle in degrees of the vector from * x1,y1 to x2,y2. */ goog.math.angle = function(x1, y1, x2, y2) { return goog.math.standardAngle( goog.math.toDegrees(Math.atan2(y2 - y1, x2 - x1))); }; /** * Computes the difference between startAngle and endAngle (angles in degrees). * @param {number} startAngle Start angle in degrees. * @param {number} endAngle End angle in degrees. * @return {number} The number of degrees that when added to * startAngle will result in endAngle. Positive numbers mean that the * direction is clockwise. Negative numbers indicate a counter-clockwise * direction. * The shortest route (clockwise vs counter-clockwise) between the angles * is used. * When the difference is 180 degrees, the function returns 180 (not -180) * angleDifference(30, 40) is 10, and angleDifference(40, 30) is -10. * angleDifference(350, 10) is 20, and angleDifference(10, 350) is -20. */ goog.math.angleDifference = function(startAngle, endAngle) { var d = goog.math.standardAngle(endAngle) - goog.math.standardAngle(startAngle); if (d > 180) { d = d - 360; } else if (d <= -180) { d = 360 + d; } return d; }; /** * Returns the sign of a number as per the "sign" or "signum" function. * @param {number} x The number to take the sign of. * @return {number} -1 when negative, 1 when positive, 0 when 0. Preserves * signed zeros and NaN. */ goog.math.sign = function(x) { if (x > 0) { return 1; } if (x < 0) { return -1; } return x; // Preserves signed zeros and NaN. }; /** * JavaScript implementation of Longest Common Subsequence problem. * http://en.wikipedia.org/wiki/Longest_common_subsequence * * Returns the longest possible array that is subarray of both of given arrays. * * @param {IArrayLike<S>} array1 First array of objects. * @param {IArrayLike<T>} array2 Second array of objects. * @param {Function=} opt_compareFn Function that acts as a custom comparator * for the array ojects. Function should return true if objects are equal, * otherwise false. * @param {Function=} opt_collectorFn Function used to decide what to return * as a result subsequence. It accepts 2 arguments: index of common element * in the first array and index in the second. The default function returns * element from the first array. * @return {!Array<S|T>} A list of objects that are common to both arrays * such that there is no common subsequence with size greater than the * length of the list. * @template S,T */ goog.math.longestCommonSubsequence = function( array1, array2, opt_compareFn, opt_collectorFn) { var compare = opt_compareFn || function(a, b) { return a == b; }; var collect = opt_collectorFn || function(i1, i2) { return array1[i1]; }; var length1 = array1.length; var length2 = array2.length; var arr = []; for (var i = 0; i < length1 + 1; i++) { arr[i] = []; arr[i][0] = 0; } for (var j = 0; j < length2 + 1; j++) { arr[0][j] = 0; } for (i = 1; i <= length1; i++) { for (j = 1; j <= length2; j++) { if (compare(array1[i - 1], array2[j - 1])) { arr[i][j] = arr[i - 1][j - 1] + 1; } else { arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]); } } } // Backtracking var result = []; var i = length1, j = length2; while (i > 0 && j > 0) { if (compare(array1[i - 1], array2[j - 1])) { result.unshift(collect(i - 1, j - 1)); i--; j--; } else { if (arr[i - 1][j] > arr[i][j - 1]) { i--; } else { j--; } } } return result; }; /** * Returns the sum of the arguments. * @param {...number} var_args Numbers to add. * @return {number} The sum of the arguments (0 if no arguments were provided, * `NaN` if any of the arguments is not a valid number). */ goog.math.sum = function(var_args) { return /** @type {number} */ ( goog.array.reduce( arguments, function(sum, value) { return sum + value; }, 0)); }; /** * Returns the arithmetic mean of the arguments. * @param {...number} var_args Numbers to average. * @return {number} The average of the arguments (`NaN` if no arguments * were provided or any of the arguments is not a valid number). */ goog.math.average = function(var_args) { return goog.math.sum.apply(null, arguments) / arguments.length; }; /** * Returns the unbiased sample variance of the arguments. For a definition, * see e.g. http://en.wikipedia.org/wiki/Variance * @param {...number} var_args Number samples to analyze. * @return {number} The unbiased sample variance of the arguments (0 if fewer * than two samples were provided, or `NaN` if any of the samples is * not a valid number). */ goog.math.sampleVariance = function(var_args) { var sampleSize = arguments.length; if (sampleSize < 2) { return 0; } var mean = goog.math.average.apply(null, arguments); var variance = goog.math.sum.apply(null, goog.array.map(arguments, function(val) { return Math.pow(val - mean, 2); })) / (sampleSize - 1); return variance; }; /** * Returns the sample standard deviation of the arguments. For a definition of * sample standard deviation, see e.g. * http://en.wikipedia.org/wiki/Standard_deviation * @param {...number} var_args Number samples to analyze. * @return {number} The sample standard deviation of the arguments (0 if fewer * than two samples were provided, or `NaN` if any of the samples is * not a valid number). */ goog.math.standardDeviation = function(var_args) { return Math.sqrt(goog.math.sampleVariance.apply(null, arguments)); }; /** * Returns whether the supplied number represents an integer, i.e. that is has * no fractional component. No range-checking is performed on the number. * @param {number} num The number to test. * @return {boolean} Whether `num` is an integer. */ goog.math.isInt = function(num) { return isFinite(num) && num % 1 == 0; }; /** * Returns whether the supplied number is finite and not NaN. * @param {number} num The number to test. * @return {boolean} Whether `num` is a finite number. * @deprecated Use {@link isFinite} instead. */ goog.math.isFiniteNumber = function(num) { return isFinite(num); }; /** * @param {number} num The number to test. * @return {boolean} Whether it is negative zero. */ goog.math.isNegativeZero = function(num) { return num == 0 && 1 / num < 0; }; /** * Returns the precise value of floor(log10(num)). * Simpler implementations didn't work because of floating point rounding * errors. For example * <ul> * <li>Math.floor(Math.log(num) / Math.LN10) is off by one for num == 1e+3. * <li>Math.floor(Math.log(num) * Math.LOG10E) is off by one for num == 1e+15. * <li>Math.floor(Math.log10(num)) is off by one for num == 1e+15 - 1. * </ul> * @param {number} num A floating point number. * @return {number} Its logarithm to base 10 rounded down to the nearest * integer if num > 0. -Infinity if num == 0. NaN if num < 0. */ goog.math.log10Floor = function(num) { if (num > 0) { var x = Math.round(Math.log(num) * Math.LOG10E); return x - (parseFloat('1e' + x) > num ? 1 : 0); } return num == 0 ? -Infinity : NaN; }; /** * A tweaked variant of `Math.floor` which tolerates if the passed number * is infinitesimally smaller than the closest integer. It often happens with * the results of floating point calculations because of the finite precision * of the intermediate results. For example {@code Math.floor(Math.log(1000) / * Math.LN10) == 2}, not 3 as one would expect. * @param {number} num A number. * @param {number=} opt_epsilon An infinitesimally small positive number, the * rounding error to tolerate. * @return {number} The largest integer less than or equal to `num`. */ goog.math.safeFloor = function(num, opt_epsilon) { goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0); return Math.floor(num + (opt_epsilon || 2e-15)); }; /** * A tweaked variant of `Math.ceil`. See `goog.math.safeFloor` for * details. * @param {number} num A number. * @param {number=} opt_epsilon An infinitesimally small positive number, the * rounding error to tolerate. * @return {number} The smallest integer greater than or equal to `num`. */ goog.math.safeCeil = function(num, opt_epsilon) { goog.asserts.assert(!goog.isDef(opt_epsilon) || opt_epsilon > 0); return Math.ceil(num - (opt_epsilon || 2e-15)); }; //javascript/closure/iter/iter.js // Copyright 2007 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Python style iteration utilities. * @author <EMAIL> (<NAME>) */ goog.provide('goog.iter'); goog.provide('goog.iter.Iterable'); goog.provide('goog.iter.Iterator'); goog.provide('goog.iter.StopIteration'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.functions'); goog.require('goog.math'); /** * @typedef {goog.iter.Iterator|{length:number}|{__iterator__}} */ goog.iter.Iterable; /** * Singleton Error object that is used to terminate iterations. * @const {!Error} */ goog.iter.StopIteration = ('StopIteration' in goog.global) ? // For script engines that support legacy iterators. goog.global['StopIteration'] : {message: 'StopIteration', stack: ''}; /** * Class/interface for iterators. An iterator needs to implement a `next` * method and it needs to throw a `goog.iter.StopIteration` when the * iteration passes beyond the end. Iterators have no `hasNext` method. * It is recommended to always use the helper functions to iterate over the * iterator or in case you are only targeting JavaScript 1.7 for in loops. * @constructor * @template VALUE */ goog.iter.Iterator = function() {}; /** * Returns the next value of the iteration. This will throw the object * {@see goog.iter#StopIteration} when the iteration passes the end. * @return {VALUE} Any object or value. */ goog.iter.Iterator.prototype.next = function() { throw goog.iter.StopIteration; }; /** * Returns the `Iterator` object itself. This is used to implement * the iterator protocol in JavaScript 1.7 * @param {boolean=} opt_keys Whether to return the keys or values. Default is * to only return the values. This is being used by the for-in loop (true) * and the for-each-in loop (false). Even though the param gives a hint * about what the iterator will return there is no guarantee that it will * return the keys when true is passed. * @return {!goog.iter.Iterator<VALUE>} The object itself. */ goog.iter.Iterator.prototype.__iterator__ = function(opt_keys) { return this; }; /** * Returns an iterator that knows how to iterate over the values in the object. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable If the * object is an iterator it will be returned as is. If the object has an * `__iterator__` method that will be called to get the value * iterator. If the object is an array-like object we create an iterator * for that. * @return {!goog.iter.Iterator<VALUE>} An iterator that knows how to iterate * over the values in `iterable`. * @template VALUE */ goog.iter.toIterator = function(iterable) { if (iterable instanceof goog.iter.Iterator) { return iterable; } if (typeof iterable.__iterator__ == 'function') { return /** @type {{__iterator__:function(this:?, boolean=)}} */ (iterable) .__iterator__(false); } if (goog.isArrayLike(iterable)) { var like = /** @type {!IArrayLike<number|string>} */ (iterable); var i = 0; var newIter = new goog.iter.Iterator; newIter.next = function() { while (true) { if (i >= like.length) { throw goog.iter.StopIteration; } // Don't include deleted elements. if (!(i in like)) { i++; continue; } return like[i++]; } }; return newIter; } // TODO(arv): Should we fall back on goog.structs.getValues()? throw new Error('Not implemented'); }; /** * Calls a function for each element in the iterator with the element of the * iterator passed as argument. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to iterate over. If the iterable is an object `toIterator` will be * called on it. * @param {function(this:THIS,VALUE,?,!goog.iter.Iterator<VALUE>)} f * The function to call for every element. This function takes 3 arguments * (the element, undefined, and the iterator) and the return value is * irrelevant. The reason for passing undefined as the second argument is * so that the same function can be used in {@see goog.array#forEach} as * well as others. The third parameter is of type "number" for * arraylike objects, undefined, otherwise. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @template THIS, VALUE */ goog.iter.forEach = function(iterable, f, opt_obj) { if (goog.isArrayLike(iterable)) { try { // NOTES: this passes the index number to the second parameter // of the callback contrary to the documentation above. goog.array.forEach( /** @type {IArrayLike<?>} */ (iterable), f, opt_obj); } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } } else { iterable = goog.iter.toIterator(iterable); try { while (true) { f.call(opt_obj, iterable.next(), undefined, iterable); } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } } }; /** * Calls a function for every element in the iterator, and if the function * returns true adds the element to a new iterator. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to iterate over. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every element. This function takes 3 arguments * (the element, undefined, and the iterator) and should return a boolean. * If the return value is true the element will be included in the returned * iterator. If it is false the element is not included. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements * that passed the test are present. * @template THIS, VALUE */ goog.iter.filter = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; newIter.next = function() { while (true) { var val = iterator.next(); if (f.call(opt_obj, val, undefined, iterator)) { return val; } } }; return newIter; }; /** * Calls a function for every element in the iterator, and if the function * returns false adds the element to a new iterator. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to iterate over. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every element. This function takes 3 arguments * (the element, undefined, and the iterator) and should return a boolean. * If the return value is false the element will be included in the returned * iterator. If it is true the element is not included. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {!goog.iter.Iterator<VALUE>} A new iterator in which only elements * that did not pass the test are present. * @template THIS, VALUE */ goog.iter.filterFalse = function(iterable, f, opt_obj) { return goog.iter.filter(iterable, goog.functions.not(f), opt_obj); }; /** * Creates a new iterator that returns the values in a range. This function * can take 1, 2 or 3 arguments: * <pre> * range(5) same as range(0, 5, 1) * range(2, 5) same as range(2, 5, 1) * </pre> * * @param {number} startOrStop The stop value if only one argument is provided. * The start value if 2 or more arguments are provided. If only one * argument is used the start value is 0. * @param {number=} opt_stop The stop value. If left out then the first * argument is used as the stop value. * @param {number=} opt_step The number to increment with between each call to * next. This can be negative. * @return {!goog.iter.Iterator<number>} A new iterator that returns the values * in the range. */ goog.iter.range = function(startOrStop, opt_stop, opt_step) { var start = 0; var stop = startOrStop; var step = opt_step || 1; if (arguments.length > 1) { start = startOrStop; stop = +opt_stop; } if (step == 0) { throw new Error('Range step argument must not be zero'); } var newIter = new goog.iter.Iterator; newIter.next = function() { if (step > 0 && start >= stop || step < 0 && start <= stop) { throw goog.iter.StopIteration; } var rv = start; start += step; return rv; }; return newIter; }; /** * Joins the values in a iterator with a delimiter. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to get the values from. * @param {string} deliminator The text to put between the values. * @return {string} The joined value string. * @template VALUE */ goog.iter.join = function(iterable, deliminator) { return goog.iter.toArray(iterable).join(deliminator); }; /** * For every element in the iterator call a function and return a new iterator * with that value. * * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterator to iterate over. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):RESULT} f * The function to call for every element. This function takes 3 arguments * (the element, undefined, and the iterator) and should return a new value. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the * results of applying the function to each element in the original * iterator. * @template THIS, VALUE, RESULT */ goog.iter.map = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; newIter.next = function() { var val = iterator.next(); return f.call(opt_obj, val, undefined, iterator); }; return newIter; }; /** * Passes every element of an iterator into a function and accumulates the * result. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to iterate over. * @param {function(this:THIS,VALUE,VALUE):VALUE} f The function to call for * every element. This function takes 2 arguments (the function's previous * result or the initial value, and the value of the current element). * function(previousValue, currentElement) : newValue. * @param {VALUE} val The initial value to pass into the function on the first * call. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * f. * @return {VALUE} Result of evaluating f repeatedly across the values of * the iterator. * @template THIS, VALUE */ goog.iter.reduce = function(iterable, f, val, opt_obj) { var rval = val; goog.iter.forEach( iterable, function(val) { rval = f.call(opt_obj, rval, val); }); return rval; }; /** * Goes through the values in the iterator. Calls f for each of these, and if * any of them returns true, this returns true (without checking the rest). If * all return false this will return false. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * object. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every value. This function takes 3 arguments * (the value, undefined, and the iterator) and should return a boolean. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {boolean} true if any value passes the test. * @template THIS, VALUE */ goog.iter.some = function(iterable, f, opt_obj) { iterable = goog.iter.toIterator(iterable); try { while (true) { if (f.call(opt_obj, iterable.next(), undefined, iterable)) { return true; } } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } return false; }; /** * Goes through the values in the iterator. Calls f for each of these and if any * of them returns false this returns false (without checking the rest). If all * return true this will return true. * * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * object. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every value. This function takes 3 arguments * (the value, undefined, and the iterator) and should return a boolean. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {boolean} true if every value passes the test. * @template THIS, VALUE */ goog.iter.every = function(iterable, f, opt_obj) { iterable = goog.iter.toIterator(iterable); try { while (true) { if (!f.call(opt_obj, iterable.next(), undefined, iterable)) { return false; } } } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } } return true; }; /** * Takes zero or more iterables and returns one iterator that will iterate over * them in the order chained. * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any * number of iterable objects. * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will * iterate over all the given iterables' contents. * @template VALUE */ goog.iter.chain = function(var_args) { return goog.iter.chainFromIterable(arguments); }; /** * Takes a single iterable containing zero or more iterables and returns one * iterator that will iterate over each one in the order given. * @see https://goo.gl/5NRp5d * @param {goog.iter.Iterable} iterable The iterable of iterables to chain. * @return {!goog.iter.Iterator<VALUE>} Returns a new iterator that will * iterate over all the contents of the iterables contained within * `iterable`. * @template VALUE */ goog.iter.chainFromIterable = function(iterable) { var iterator = goog.iter.toIterator(iterable); var iter = new goog.iter.Iterator(); var current = null; iter.next = function() { while (true) { if (current == null) { var it = iterator.next(); current = goog.iter.toIterator(it); } try { return current.next(); } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } current = null; } } }; return iter; }; /** * Builds a new iterator that iterates over the original, but skips elements as * long as a supplied function returns true. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * object. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every value. This function takes 3 arguments * (the value, undefined, and the iterator) and should return a boolean. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {!goog.iter.Iterator<VALUE>} A new iterator that drops elements from * the original iterator as long as `f` is true. * @template THIS, VALUE */ goog.iter.dropWhile = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var newIter = new goog.iter.Iterator; var dropping = true; newIter.next = function() { while (true) { var val = iterator.next(); if (dropping && f.call(opt_obj, val, undefined, iterator)) { continue; } else { dropping = false; } return val; } }; return newIter; }; /** * Builds a new iterator that iterates over the original, but only as long as a * supplied function returns true. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * object. * @param { * function(this:THIS,VALUE,undefined,!goog.iter.Iterator<VALUE>):boolean} f * The function to call for every value. This function takes 3 arguments * (the value, undefined, and the iterator) and should return a boolean. * @param {THIS=} opt_obj This is used as the 'this' object in f when called. * @return {!goog.iter.Iterator<VALUE>} A new iterator that keeps elements in * the original iterator as long as the function is true. * @template THIS, VALUE */ goog.iter.takeWhile = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var iter = new goog.iter.Iterator(); iter.next = function() { var val = iterator.next(); if (f.call(opt_obj, val, undefined, iterator)) { return val; } throw goog.iter.StopIteration; }; return iter; }; /** * Converts the iterator to an array * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterator * to convert to an array. * @return {!Array<VALUE>} An array of the elements the iterator iterates over. * @template VALUE */ goog.iter.toArray = function(iterable) { // Fast path for array-like. if (goog.isArrayLike(iterable)) { return goog.array.toArray(/** @type {!IArrayLike<?>} */ (iterable)); } iterable = goog.iter.toIterator(iterable); var array = []; goog.iter.forEach(iterable, function(val) { array.push(val); }); return array; }; /** * Iterates over two iterables and returns true if they contain the same * sequence of elements and have the same length. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable1 The first * iterable object. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable2 The second * iterable object. * @param {function(VALUE,VALUE):boolean=} opt_equalsFn Optional comparison * function. * Should take two arguments to compare, and return true if the arguments * are equal. Defaults to {@link goog.array.defaultCompareEquality} which * compares the elements using the built-in '===' operator. * @return {boolean} true if the iterables contain the same sequence of elements * and have the same length. * @template VALUE */ goog.iter.equals = function(iterable1, iterable2, opt_equalsFn) { var fillValue = {}; var pairs = goog.iter.zipLongest(fillValue, iterable1, iterable2); var equalsFn = opt_equalsFn || goog.array.defaultCompareEquality; return goog.iter.every( pairs, function(pair) { return equalsFn(pair[0], pair[1]); }); }; /** * Advances the iterator to the next position, returning the given default value * instead of throwing an exception if the iterator has no more entries. * @param {goog.iter.Iterator<VALUE>|goog.iter.Iterable} iterable The iterable * object. * @param {VALUE} defaultValue The value to return if the iterator is empty. * @return {VALUE} The next item in the iteration, or defaultValue if the * iterator was empty. * @template VALUE */ goog.iter.nextOrValue = function(iterable, defaultValue) { try { return goog.iter.toIterator(iterable).next(); } catch (e) { if (e != goog.iter.StopIteration) { throw e; } return defaultValue; } }; /** * Cartesian product of zero or more sets. Gives an iterator that gives every * combination of one element chosen from each set. For example, * ([1, 2], [3, 4]) gives ([1, 3], [1, 4], [2, 3], [2, 4]). * @see http://docs.python.org/library/itertools.html#itertools.product * @param {...!IArrayLike<VALUE>} var_args Zero or more sets, as * arrays. * @return {!goog.iter.Iterator<!Array<VALUE>>} An iterator that gives each * n-tuple (as an array). * @template VALUE */ goog.iter.product = function(var_args) { var someArrayEmpty = goog.array.some(arguments, function(arr) { return !arr.length; }); // An empty set in a cartesian product gives an empty set. if (someArrayEmpty || !arguments.length) { return new goog.iter.Iterator(); } var iter = new goog.iter.Iterator(); var arrays = arguments; // The first indices are [0, 0, ...] /** @type {?Array<number>} */ var indicies = goog.array.repeat(0, arrays.length); iter.next = function() { if (indicies) { var retVal = goog.array.map(indicies, function(valueIndex, arrayIndex) { return arrays[arrayIndex][valueIndex]; }); // Generate the next-largest indices for the next call. // Increase the rightmost index. If it goes over, increase the next // rightmost (like carry-over addition). for (var i = indicies.length - 1; i >= 0; i--) { // Assertion prevents compiler warning below. goog.asserts.assert(indicies); if (indicies[i] < arrays[i].length - 1) { indicies[i]++; break; } // We're at the last indices (the last element of every array), so // the iteration is over on the next call. if (i == 0) { indicies = null; break; } // Reset the index in this column and loop back to increment the // next one. indicies[i] = 0; } return retVal; } throw goog.iter.StopIteration; }; return iter; }; /** * Create an iterator to cycle over the iterable's elements indefinitely. * For example, ([1, 2, 3]) would return : 1, 2, 3, 1, 2, 3, ... * @see: http://docs.python.org/library/itertools.html#itertools.cycle. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable object. * @return {!goog.iter.Iterator<VALUE>} An iterator that iterates indefinitely * over the values in `iterable`. * @template VALUE */ goog.iter.cycle = function(iterable) { var baseIterator = goog.iter.toIterator(iterable); // We maintain a cache to store the iterable elements as we iterate // over them. The cache is used to return elements once we have // iterated over the iterable once. var cache = []; var cacheIndex = 0; var iter = new goog.iter.Iterator(); // This flag is set after the iterable is iterated over once var useCache = false; iter.next = function() { var returnElement = null; // Pull elements off the original iterator if not using cache if (!useCache) { try { // Return the element from the iterable returnElement = baseIterator.next(); cache.push(returnElement); return returnElement; } catch (e) { // If an exception other than StopIteration is thrown // or if there are no elements to iterate over (the iterable was empty) // throw an exception if (e != goog.iter.StopIteration || goog.array.isEmpty(cache)) { throw e; } // set useCache to true after we know that a 'StopIteration' exception // was thrown and the cache is not empty (to handle the 'empty iterable' // use case) useCache = true; } } returnElement = cache[cacheIndex]; cacheIndex = (cacheIndex + 1) % cache.length; return returnElement; }; return iter; }; /** * Creates an iterator that counts indefinitely from a starting value. * @see http://docs.python.org/2/library/itertools.html#itertools.count * @param {number=} opt_start The starting value. Default is 0. * @param {number=} opt_step The number to increment with between each call to * next. Negative and floating point numbers are allowed. Default is 1. * @return {!goog.iter.Iterator<number>} A new iterator that returns the values * in the series. */ goog.iter.count = function(opt_start, opt_step) { var counter = opt_start || 0; var step = goog.isDef(opt_step) ? opt_step : 1; var iter = new goog.iter.Iterator(); iter.next = function() { var returnValue = counter; counter += step; return returnValue; }; return iter; }; /** * Creates an iterator that returns the same object or value repeatedly. * @param {VALUE} value Any object or value to repeat. * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the * repeated value. * @template VALUE */ goog.iter.repeat = function(value) { var iter = new goog.iter.Iterator(); iter.next = goog.functions.constant(value); return iter; }; /** * Creates an iterator that returns running totals from the numbers in * `iterable`. For example, the array {@code [1, 2, 3, 4, 5]} yields * {@code 1 -> 3 -> 6 -> 10 -> 15}. * @see http://docs.python.org/3.2/library/itertools.html#itertools.accumulate * @param {!goog.iter.Iterable} iterable The iterable of numbers to * accumulate. * @return {!goog.iter.Iterator<number>} A new iterator that returns the * numbers in the series. */ goog.iter.accumulate = function(iterable) { var iterator = goog.iter.toIterator(iterable); var total = 0; var iter = new goog.iter.Iterator(); iter.next = function() { total += iterator.next(); return total; }; return iter; }; /** * Creates an iterator that returns arrays containing the ith elements from the * provided iterables. The returned arrays will be the same size as the number * of iterables given in `var_args`. Once the shortest iterable is * exhausted, subsequent calls to `next()` will throw * `goog.iter.StopIteration`. * @see http://docs.python.org/2/library/itertools.html#itertools.izip * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any * number of iterable objects. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns * arrays of elements from the provided iterables. * @template VALUE */ goog.iter.zip = function(var_args) { var args = arguments; var iter = new goog.iter.Iterator(); if (args.length > 0) { var iterators = goog.array.map(args, goog.iter.toIterator); iter.next = function() { var arr = goog.array.map(iterators, function(it) { return it.next(); }); return arr; }; } return iter; }; /** * Creates an iterator that returns arrays containing the ith elements from the * provided iterables. The returned arrays will be the same size as the number * of iterables given in `var_args`. Shorter iterables will be extended * with `fillValue`. Once the longest iterable is exhausted, subsequent * calls to `next()` will throw `goog.iter.StopIteration`. * @see http://docs.python.org/2/library/itertools.html#itertools.izip_longest * @param {VALUE} fillValue The object or value used to fill shorter iterables. * @param {...!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} var_args Any * number of iterable objects. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator that returns * arrays of elements from the provided iterables. * @template VALUE */ goog.iter.zipLongest = function(fillValue, var_args) { var args = goog.array.slice(arguments, 1); var iter = new goog.iter.Iterator(); if (args.length > 0) { var iterators = goog.array.map(args, goog.iter.toIterator); iter.next = function() { var iteratorsHaveValues = false; // false when all iterators are empty. var arr = goog.array.map(iterators, function(it) { var returnValue; try { returnValue = it.next(); // Iterator had a value, so we've not exhausted the iterators. // Set flag accordingly. iteratorsHaveValues = true; } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } returnValue = fillValue; } return returnValue; }); if (!iteratorsHaveValues) { throw goog.iter.StopIteration; } return arr; }; } return iter; }; /** * Creates an iterator that filters `iterable` based on a series of * `selectors`. On each call to `next()`, one item is taken from * both the `iterable` and `selectors` iterators. If the item from * `selectors` evaluates to true, the item from `iterable` is given. * Otherwise, it is skipped. Once either `iterable` or `selectors` * is exhausted, subsequent calls to `next()` will throw * `goog.iter.StopIteration`. * @see http://docs.python.org/2/library/itertools.html#itertools.compress * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to filter. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} selectors An * iterable of items to be evaluated in a boolean context to determine if * the corresponding element in `iterable` should be included in the * result. * @return {!goog.iter.Iterator<VALUE>} A new iterator that returns the * filtered values. * @template VALUE */ goog.iter.compress = function(iterable, selectors) { var selectorIterator = goog.iter.toIterator(selectors); return goog.iter.filter( iterable, function() { return !!selectorIterator.next(); }); }; /** * Implements the `goog.iter.groupBy` iterator. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to group. * @param {function(VALUE): KEY=} opt_keyFunc Optional function for * determining the key value for each group in the `iterable`. Default * is the identity function. * @constructor * @extends {goog.iter.Iterator<!Array<?>>} * @template KEY, VALUE * @private */ goog.iter.GroupByIterator_ = function(iterable, opt_keyFunc) { /** * The iterable to group, coerced to an iterator. * @type {!goog.iter.Iterator} */ this.iterator = goog.iter.toIterator(iterable); /** * A function for determining the key value for each element in the iterable. * If no function is provided, the identity function is used and returns the * element unchanged. * @type {function(VALUE): KEY} */ this.keyFunc = opt_keyFunc || goog.functions.identity; /** * The target key for determining the start of a group. * @type {KEY} */ this.targetKey; /** * The current key visited during iteration. * @type {KEY} */ this.currentKey; /** * The current value being added to the group. * @type {VALUE} */ this.currentValue; }; goog.inherits(goog.iter.GroupByIterator_, goog.iter.Iterator); /** @override */ goog.iter.GroupByIterator_.prototype.next = function() { while (this.currentKey == this.targetKey) { this.currentValue = this.iterator.next(); // Exits on StopIteration this.currentKey = this.keyFunc(this.currentValue); } this.targetKey = this.currentKey; return [this.currentKey, this.groupItems_(this.targetKey)]; }; /** * Performs the grouping of objects using the given key. * @param {KEY} targetKey The target key object for the group. * @return {!Array<VALUE>} An array of grouped objects. * @private */ goog.iter.GroupByIterator_.prototype.groupItems_ = function(targetKey) { var arr = []; while (this.currentKey == targetKey) { arr.push(this.currentValue); try { this.currentValue = this.iterator.next(); } catch (ex) { if (ex !== goog.iter.StopIteration) { throw ex; } break; } this.currentKey = this.keyFunc(this.currentValue); } return arr; }; /** * Creates an iterator that returns arrays containing elements from the * `iterable` grouped by a key value. For iterables with repeated * elements (i.e. sorted according to a particular key function), this function * has a `uniq`-like effect. For example, grouping the array: * {@code [A, B, B, C, C, A]} produces * {@code [A, [A]], [B, [B, B]], [C, [C, C]], [A, [A]]}. * @see http://docs.python.org/2/library/itertools.html#itertools.groupby * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to group. * @param {function(VALUE): KEY=} opt_keyFunc Optional function for * determining the key value for each group in the `iterable`. Default * is the identity function. * @return {!goog.iter.Iterator<!Array<?>>} A new iterator that returns * arrays of consecutive key and groups. * @template KEY, VALUE */ goog.iter.groupBy = function(iterable, opt_keyFunc) { return new goog.iter.GroupByIterator_(iterable, opt_keyFunc); }; /** * Gives an iterator that gives the result of calling the given function * <code>f</code> with the arguments taken from the next element from * <code>iterable</code> (the elements are expected to also be iterables). * * Similar to {@see goog.iter#map} but allows the function to accept multiple * arguments from the iterable. * * @param {!goog.iter.Iterable} iterable The iterable of * iterables to iterate over. * @param {function(this:THIS,...*):RESULT} f The function to call for every * element. This function takes N+2 arguments, where N represents the * number of items from the next element of the iterable. The two * additional arguments passed to the function are undefined and the * iterator itself. The function should return a new value. * @param {THIS=} opt_obj The object to be used as the value of 'this' within * `f`. * @return {!goog.iter.Iterator<RESULT>} A new iterator that returns the * results of applying the function to each element in the original * iterator. * @template THIS, RESULT */ goog.iter.starMap = function(iterable, f, opt_obj) { var iterator = goog.iter.toIterator(iterable); var iter = new goog.iter.Iterator(); iter.next = function() { var args = goog.iter.toArray(iterator.next()); return f.apply(opt_obj, goog.array.concat(args, undefined, iterator)); }; return iter; }; /** * Returns an array of iterators each of which can iterate over the values in * `iterable` without advancing the others. * @see http://docs.python.org/2/library/itertools.html#itertools.tee * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to tee. * @param {number=} opt_num The number of iterators to create. Default is 2. * @return {!Array<goog.iter.Iterator<VALUE>>} An array of iterators. * @template VALUE */ goog.iter.tee = function(iterable, opt_num) { var iterator = goog.iter.toIterator(iterable); var num = goog.isNumber(opt_num) ? opt_num : 2; var buffers = goog.array.map(goog.array.range(num), function() { return []; }); var addNextIteratorValueToBuffers = function() { var val = iterator.next(); goog.array.forEach(buffers, function(buffer) { buffer.push(val); }); }; var createIterator = function(buffer) { // Each tee'd iterator has an associated buffer (initially empty). When a // tee'd iterator's buffer is empty, it calls // addNextIteratorValueToBuffers(), adding the next value to all tee'd // iterators' buffers, and then returns that value. This allows each // iterator to be advanced independently. var iter = new goog.iter.Iterator(); iter.next = function() { if (goog.array.isEmpty(buffer)) { addNextIteratorValueToBuffers(); } goog.asserts.assert(!goog.array.isEmpty(buffer)); return buffer.shift(); }; return iter; }; return goog.array.map(buffers, createIterator); }; /** * Creates an iterator that returns arrays containing a count and an element * obtained from the given `iterable`. * @see http://docs.python.org/2/library/functions.html#enumerate * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to enumerate. * @param {number=} opt_start Optional starting value. Default is 0. * @return {!goog.iter.Iterator<!Array<?>>} A new iterator containing * count/item pairs. * @template VALUE */ goog.iter.enumerate = function(iterable, opt_start) { return goog.iter.zip(goog.iter.count(opt_start), iterable); }; /** * Creates an iterator that returns the first `limitSize` elements from an * iterable. If this number is greater than the number of elements in the * iterable, all the elements are returned. * @see http://goo.gl/V0sihp Inspired by the limit iterator in Guava. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to limit. * @param {number} limitSize The maximum number of elements to return. * @return {!goog.iter.Iterator<VALUE>} A new iterator containing * `limitSize` elements. * @template VALUE */ goog.iter.limit = function(iterable, limitSize) { goog.asserts.assert(goog.math.isInt(limitSize) && limitSize >= 0); var iterator = goog.iter.toIterator(iterable); var iter = new goog.iter.Iterator(); var remaining = limitSize; iter.next = function() { if (remaining-- > 0) { return iterator.next(); } throw goog.iter.StopIteration; }; return iter; }; /** * Creates an iterator that is advanced `count` steps ahead. Consumed * values are silently discarded. If `count` is greater than the number * of elements in `iterable`, an empty iterator is returned. Subsequent * calls to `next()` will throw `goog.iter.StopIteration`. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to consume. * @param {number} count The number of elements to consume from the iterator. * @return {!goog.iter.Iterator<VALUE>} An iterator advanced zero or more steps * ahead. * @template VALUE */ goog.iter.consume = function(iterable, count) { goog.asserts.assert(goog.math.isInt(count) && count >= 0); var iterator = goog.iter.toIterator(iterable); while (count-- > 0) { goog.iter.nextOrValue(iterator, null); } return iterator; }; /** * Creates an iterator that returns a range of elements from an iterable. * Similar to {@see goog.array#slice} but does not support negative indexes. * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to slice. * @param {number} start The index of the first element to return. * @param {number=} opt_end The index after the last element to return. If * defined, must be greater than or equal to `start`. * @return {!goog.iter.Iterator<VALUE>} A new iterator containing a slice of * the original. * @template VALUE */ goog.iter.slice = function(iterable, start, opt_end) { goog.asserts.assert(goog.math.isInt(start) && start >= 0); var iterator = goog.iter.consume(iterable, start); if (goog.isNumber(opt_end)) { goog.asserts.assert(goog.math.isInt(opt_end) && opt_end >= start); iterator = goog.iter.limit(iterator, opt_end - start /* limitSize */); } return iterator; }; /** * Checks an array for duplicate elements. * @param {?IArrayLike<VALUE>} arr The array to check for * duplicates. * @return {boolean} True, if the array contains duplicates, false otherwise. * @private * @template VALUE */ // TODO(dlindquist): Consider moving this into goog.array as a public function. goog.iter.hasDuplicates_ = function(arr) { var deduped = []; goog.array.removeDuplicates(arr, deduped); return arr.length != deduped.length; }; /** * Creates an iterator that returns permutations of elements in * `iterable`. * * Permutations are obtained by taking the Cartesian product of * `opt_length` iterables and filtering out those with repeated * elements. For example, the permutations of {@code [1,2,3]} are * {@code [[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]}. * @see http://docs.python.org/2/library/itertools.html#itertools.permutations * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable from which to generate permutations. * @param {number=} opt_length Length of each permutation. If omitted, defaults * to the length of `iterable`. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing the * permutations of `iterable`. * @template VALUE */ goog.iter.permutations = function(iterable, opt_length) { var elements = goog.iter.toArray(iterable); var length = goog.isNumber(opt_length) ? opt_length : elements.length; var sets = goog.array.repeat(elements, length); var product = goog.iter.product.apply(undefined, sets); return goog.iter.filter( product, function(arr) { return !goog.iter.hasDuplicates_(arr); }); }; /** * Creates an iterator that returns combinations of elements from * `iterable`. * * Combinations are obtained by taking the {@see goog.iter#permutations} of * `iterable` and filtering those whose elements appear in the order they * are encountered in `iterable`. For example, the 3-length combinations * of {@code [0,1,2,3]} are {@code [[0,1,2], [0,1,3], [0,2,3], [1,2,3]]}. * @see http://docs.python.org/2/library/itertools.html#itertools.combinations * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable from which to generate combinations. * @param {number} length The length of each combination. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing * combinations from the `iterable`. * @template VALUE */ goog.iter.combinations = function(iterable, length) { var elements = goog.iter.toArray(iterable); var indexes = goog.iter.range(elements.length); var indexIterator = goog.iter.permutations(indexes, length); // sortedIndexIterator will now give arrays of with the given length that // indicate what indexes into "elements" should be returned on each iteration. var sortedIndexIterator = goog.iter.filter( indexIterator, function(arr) { return goog.array.isSorted(arr); }); var iter = new goog.iter.Iterator(); function getIndexFromElements(index) { return elements[index]; } iter.next = function() { return goog.array.map(sortedIndexIterator.next(), getIndexFromElements); }; return iter; }; /** * Creates an iterator that returns combinations of elements from * `iterable`, with repeated elements possible. * * Combinations are obtained by taking the Cartesian product of `length` * iterables and filtering those whose elements appear in the order they are * encountered in `iterable`. For example, the 2-length combinations of * {@code [1,2,3]} are {@code [[1,1], [1,2], [1,3], [2,2], [2,3], [3,3]]}. * @see https://goo.gl/C0yXe4 * @see https://goo.gl/djOCsk * @param {!goog.iter.Iterator<VALUE>|!goog.iter.Iterable} iterable The * iterable to combine. * @param {number} length The length of each combination. * @return {!goog.iter.Iterator<!Array<VALUE>>} A new iterator containing * combinations from the `iterable`. * @template VALUE */ goog.iter.combinationsWithReplacement = function(iterable, length) { var elements = goog.iter.toArray(iterable); var indexes = goog.array.range(elements.length); var sets = goog.array.repeat(indexes, length); var indexIterator = goog.iter.product.apply(undefined, sets); // sortedIndexIterator will now give arrays of with the given length that // indicate what indexes into "elements" should be returned on each iteration. var sortedIndexIterator = goog.iter.filter( indexIterator, function(arr) { return goog.array.isSorted(arr); }); var iter = new goog.iter.Iterator(); function getIndexFromElements(index) { return elements[index]; } iter.next = function() { return goog.array.map( /** @type {!Array<number>} */ (sortedIndexIterator.next()), getIndexFromElements); }; return iter; }; //javascript/closure/structs/map.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Datastructure: Hash Map. * * @author <EMAIL> (<NAME>) * @author <EMAIL> (<NAME>) Optimized for IE6 * * This file contains an implementation of a Map structure. It implements a lot * of the methods used in goog.structs so those functions work on hashes. This * is best suited for complex key types. For simple keys such as numbers and * strings consider using the lighter-weight utilities in goog.object. * MOE:begin_intracomment_strip * * NOTE(flan): Internally, key types are NOT actually cast to * strings. Some people actually rely on this behavior even though it * is incorrect. For more information, see http://b/5622311. * * NOTE(flan): <NAME> (erikcorry) from the V8 team went over this * class with me to help look for simplifications and * optimizations. In the end, he didn't come up with very much. Erik * explained that "for (k in o)" is not optimized in Crankshaft * because it needs to look up properties in the whole prototype * chain. It also needs to return the keys in order. Thus keeping an * array of keys is actually much more efficient. * * Likewise, one option to iterate safely with "for (k in o)" is to * prefix the keys with some character, like ':'. This can create a * lot of strings that didn't exist before. In Closure Labs, * goog.labs.structs.Map uses extra arrays to store non-safe keys and * values. * * Thus, there are not a lot of reasonable simplifications that can be * done here without impacting performance. * * TODO(chrishenry): Create some performance benchmarks for common * operations. * MOE:end_intracomment_strip */ goog.provide('goog.structs.Map'); goog.require('goog.iter.Iterator'); goog.require('goog.iter.StopIteration'); /** * Class for Hash Map datastructure. * @param {*=} opt_map Map or Object to initialize the map with. * @param {...*} var_args If 2 or more arguments are present then they * will be used as key-value pairs. * @constructor * @template K, V * @deprecated This type is misleading: use ES6 Map instead. */ goog.structs.Map = function(opt_map, var_args) { /** * Underlying JS object used to implement the map. * @private {!Object} */ this.map_ = {}; /** * An array of keys. This is necessary for two reasons: * 1. Iterating the keys using for (var key in this.map_) allocates an * object for every key in IE which is really bad for IE6 GC perf. * 2. Without a side data structure, we would need to escape all the keys * as that would be the only way we could tell during iteration if the * key was an internal key or a property of the object. * * This array can contain deleted keys so it's necessary to check the map * as well to see if the key is still in the map (this doesn't require a * memory allocation in IE). * @private {!Array<string>} */ this.keys_ = []; /** * The number of key value pairs in the map. * @private {number} */ this.count_ = 0; /** * Version used to detect changes while iterating. * @private {number} */ this.version_ = 0; var argLength = arguments.length; if (argLength > 1) { if (argLength % 2) { throw new Error('Uneven number of arguments'); } for (var i = 0; i < argLength; i += 2) { this.set(arguments[i], arguments[i + 1]); } } else if (opt_map) { this.addAll(/** @type {!Object} */ (opt_map)); } }; /** * @return {number} The number of key-value pairs in the map. */ goog.structs.Map.prototype.getCount = function() { return this.count_; }; /** * Returns the values of the map. * @return {!Array<V>} The values in the map. */ goog.structs.Map.prototype.getValues = function() { this.cleanupKeysArray_(); var rv = []; for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; rv.push(this.map_[key]); } return rv; }; /** * Returns the keys of the map. * @return {!Array<string>} Array of string values. */ goog.structs.Map.prototype.getKeys = function() { this.cleanupKeysArray_(); return /** @type {!Array<string>} */ (this.keys_.concat()); }; /** * Whether the map contains the given key. * @param {*} key The key to check for. * @return {boolean} Whether the map contains the key. */ goog.structs.Map.prototype.containsKey = function(key) { return goog.structs.Map.hasKey_(this.map_, key); }; /** * Whether the map contains the given value. This is O(n). * @param {V} val The value to check for. * @return {boolean} Whether the map contains the value. */ goog.structs.Map.prototype.containsValue = function(val) { for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; if (goog.structs.Map.hasKey_(this.map_, key) && this.map_[key] == val) { return true; } } return false; }; /** * Whether this map is equal to the argument map. * @param {goog.structs.Map} otherMap The map against which to test equality. * @param {function(V, V): boolean=} opt_equalityFn Optional equality function * to test equality of values. If not specified, this will test whether * the values contained in each map are identical objects. * @return {boolean} Whether the maps are equal. */ goog.structs.Map.prototype.equals = function(otherMap, opt_equalityFn) { if (this === otherMap) { return true; } if (this.count_ != otherMap.getCount()) { return false; } var equalityFn = opt_equalityFn || goog.structs.Map.defaultEquals; this.cleanupKeysArray_(); for (var key, i = 0; key = this.keys_[i]; i++) { if (!equalityFn(this.get(key), otherMap.get(key))) { return false; } } return true; }; /** * Default equality test for values. * @param {*} a The first value. * @param {*} b The second value. * @return {boolean} Whether a and b reference the same object. */ goog.structs.Map.defaultEquals = function(a, b) { return a === b; }; /** * @return {boolean} Whether the map is empty. */ goog.structs.Map.prototype.isEmpty = function() { return this.count_ == 0; }; /** * Removes all key-value pairs from the map. */ goog.structs.Map.prototype.clear = function() { this.map_ = {}; this.keys_.length = 0; this.count_ = 0; this.version_ = 0; }; /** * Removes a key-value pair based on the key. This is O(logN) amortized due to * updating the keys array whenever the count becomes half the size of the keys * in the keys array. * @param {*} key The key to remove. * @return {boolean} Whether object was removed. */ goog.structs.Map.prototype.remove = function(key) { if (goog.structs.Map.hasKey_(this.map_, key)) { delete this.map_[key]; this.count_--; this.version_++; // clean up the keys array if the threshold is hit if (this.keys_.length > 2 * this.count_) { this.cleanupKeysArray_(); } return true; } return false; }; /** * Cleans up the temp keys array by removing entries that are no longer in the * map. * @private */ goog.structs.Map.prototype.cleanupKeysArray_ = function() { if (this.count_ != this.keys_.length) { // First remove keys that are no longer in the map. var srcIndex = 0; var destIndex = 0; while (srcIndex < this.keys_.length) { var key = this.keys_[srcIndex]; if (goog.structs.Map.hasKey_(this.map_, key)) { this.keys_[destIndex++] = key; } srcIndex++; } this.keys_.length = destIndex; } if (this.count_ != this.keys_.length) { // If the count still isn't correct, that means we have duplicates. This can // happen when the same key is added and removed multiple times. Now we have // to allocate one extra Object to remove the duplicates. This could have // been done in the first pass, but in the common case, we can avoid // allocating an extra object by only doing this when necessary. var seen = {}; var srcIndex = 0; var destIndex = 0; while (srcIndex < this.keys_.length) { var key = this.keys_[srcIndex]; if (!(goog.structs.Map.hasKey_(seen, key))) { this.keys_[destIndex++] = key; seen[key] = 1; } srcIndex++; } this.keys_.length = destIndex; } }; /** * Returns the value for the given key. If the key is not found and the default * value is not given this will return `undefined`. * @param {*} key The key to get the value for. * @param {DEFAULT=} opt_val The value to return if no item is found for the * given key, defaults to undefined. * @return {V|DEFAULT} The value for the given key. * @template DEFAULT */ goog.structs.Map.prototype.get = function(key, opt_val) { if (goog.structs.Map.hasKey_(this.map_, key)) { return this.map_[key]; } return opt_val; }; /** * Adds a key-value pair to the map. * @param {*} key The key. * @param {V} value The value to add. * @return {*} Some subclasses return a value. */ goog.structs.Map.prototype.set = function(key, value) { if (!(goog.structs.Map.hasKey_(this.map_, key))) { this.count_++; // TODO(johnlenz): This class lies, it claims to return an array of string // keys, but instead returns the original object used. this.keys_.push(/** @type {?} */ (key)); // Only change the version if we add a new key. this.version_++; } this.map_[key] = value; }; /** * Adds multiple key-value pairs from another goog.structs.Map or Object. * @param {?Object} map Object containing the data to add. */ goog.structs.Map.prototype.addAll = function(map) { if (map instanceof goog.structs.Map) { var keys = map.getKeys(); for (var i = 0; i < keys.length; i++) { this.set(keys[i], map.get(keys[i])); } } else { for (var key in map) { this.set(key, map[key]); } } }; /** * Calls the given function on each entry in the map. * @param {function(this:T, V, K, goog.structs.Map<K,V>)} f * @param {T=} opt_obj The value of "this" inside f. * @template T */ goog.structs.Map.prototype.forEach = function(f, opt_obj) { var keys = this.getKeys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = this.get(key); f.call(opt_obj, value, key, this); } }; /** * Clones a map and returns a new map. * @return {!goog.structs.Map} A new map with the same key-value pairs. */ goog.structs.Map.prototype.clone = function() { return new goog.structs.Map(this); }; /** * Returns a new map in which all the keys and values are interchanged * (keys become values and values become keys). If multiple keys map to the * same value, the chosen transposed value is implementation-dependent. * * It acts very similarly to {goog.object.transpose(Object)}. * * @return {!goog.structs.Map} The transposed map. */ goog.structs.Map.prototype.transpose = function() { var transposed = new goog.structs.Map(); for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; var value = this.map_[key]; transposed.set(value, key); } return transposed; }; /** * @return {!Object} Object representation of the map. */ goog.structs.Map.prototype.toObject = function() { this.cleanupKeysArray_(); var obj = {}; for (var i = 0; i < this.keys_.length; i++) { var key = this.keys_[i]; obj[key] = this.map_[key]; } return obj; }; /** * Returns an iterator that iterates over the keys in the map. Removal of keys * while iterating might have undesired side effects. * @return {!goog.iter.Iterator} An iterator over the keys in the map. */ goog.structs.Map.prototype.getKeyIterator = function() { return this.__iterator__(true); }; /** * Returns an iterator that iterates over the values in the map. Removal of * keys while iterating might have undesired side effects. * @return {!goog.iter.Iterator} An iterator over the values in the map. */ goog.structs.Map.prototype.getValueIterator = function() { return this.__iterator__(false); }; /** * Returns an iterator that iterates over the values or the keys in the map. * This throws an exception if the map was mutated since the iterator was * created. * @param {boolean=} opt_keys True to iterate over the keys. False to iterate * over the values. The default value is false. * @return {!goog.iter.Iterator} An iterator over the values or keys in the map. */ goog.structs.Map.prototype.__iterator__ = function(opt_keys) { // Clean up keys to minimize the risk of iterating over dead keys. this.cleanupKeysArray_(); var i = 0; var version = this.version_; var selfObj = this; var newIter = new goog.iter.Iterator; newIter.next = function() { if (version != selfObj.version_) { throw new Error('The map has changed since the iterator was created'); } if (i >= selfObj.keys_.length) { throw goog.iter.StopIteration; } var key = selfObj.keys_[i++]; return opt_keys ? key : selfObj.map_[key]; }; return newIter; }; /** * Safe way to test for hasOwnProperty. It even allows testing for * 'hasOwnProperty'. * @param {!Object} obj The object to test for presence of the given key. * @param {*} key The key to check for. * @return {boolean} Whether the object has the key. * @private */ goog.structs.Map.hasKey_ = function(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); }; //javascript/closure/structs/structs.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Generics method for collection-like classes and objects. * * @author <EMAIL> (<NAME>) * * This file contains functions to work with collections. It supports using * Map, Set, Array and Object and other classes that implement collection-like * methods. * @suppress {strictMissingProperties} */ goog.provide('goog.structs'); goog.require('goog.array'); goog.require('goog.object'); // We treat an object as a dictionary if it has getKeys or it is an object that // isn't arrayLike. /** * Returns the number of values in the collection-like object. * @param {Object} col The collection-like object. * @return {number} The number of values in the collection-like object. */ goog.structs.getCount = function(col) { if (col.getCount && typeof col.getCount == 'function') { return col.getCount(); } if (goog.isArrayLike(col) || goog.isString(col)) { return col.length; } return goog.object.getCount(col); }; /** * Returns the values of the collection-like object. * @param {Object} col The collection-like object. * @return {!Array<?>} The values in the collection-like object. */ goog.structs.getValues = function(col) { if (col.getValues && typeof col.getValues == 'function') { return col.getValues(); } if (goog.isString(col)) { return col.split(''); } if (goog.isArrayLike(col)) { var rv = []; var l = col.length; for (var i = 0; i < l; i++) { rv.push(col[i]); } return rv; } return goog.object.getValues(col); }; /** * Returns the keys of the collection. Some collections have no notion of * keys/indexes and this function will return undefined in those cases. * @param {Object} col The collection-like object. * @return {!Array|undefined} The keys in the collection. */ goog.structs.getKeys = function(col) { if (col.getKeys && typeof col.getKeys == 'function') { return col.getKeys(); } // if we have getValues but no getKeys we know this is a key-less collection if (col.getValues && typeof col.getValues == 'function') { return undefined; } if (goog.isArrayLike(col) || goog.isString(col)) { var rv = []; var l = col.length; for (var i = 0; i < l; i++) { rv.push(i); } return rv; } return goog.object.getKeys(col); }; /** * Whether the collection contains the given value. This is O(n) and uses * equals (==) to test the existence. * @param {Object} col The collection-like object. * @param {*} val The value to check for. * @return {boolean} True if the map contains the value. */ goog.structs.contains = function(col, val) { if (col.contains && typeof col.contains == 'function') { return col.contains(val); } if (col.containsValue && typeof col.containsValue == 'function') { return col.containsValue(val); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.contains(/** @type {!Array<?>} */ (col), val); } return goog.object.containsValue(col, val); }; /** * Whether the collection is empty. * @param {Object} col The collection-like object. * @return {boolean} True if empty. */ goog.structs.isEmpty = function(col) { if (col.isEmpty && typeof col.isEmpty == 'function') { return col.isEmpty(); } // We do not use goog.string.isEmptyOrWhitespace because here we treat the // string as // collection and as such even whitespace matters if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.isEmpty(/** @type {!Array<?>} */ (col)); } return goog.object.isEmpty(col); }; /** * Removes all the elements from the collection. * @param {Object} col The collection-like object. */ goog.structs.clear = function(col) { // NOTE(arv): This should not contain strings because strings are immutable if (col.clear && typeof col.clear == 'function') { col.clear(); } else if (goog.isArrayLike(col)) { goog.array.clear(/** @type {IArrayLike<?>} */ (col)); } else { goog.object.clear(col); } }; /** * Calls a function for each value in a collection. The function takes * three arguments; the value, the key and the collection. * * @param {S} col The collection-like object. * @param {function(this:T,?,?,S):?} f The function to call for every value. * This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and the return value is irrelevant. * @param {T=} opt_obj The object to be used as the value of 'this' * within `f`. * @template T,S * @deprecated Use a more specific method, e.g. goog.array.forEach, * goog.object.forEach, or for-of. */ goog.structs.forEach = function(col, f, opt_obj) { if (col.forEach && typeof col.forEach == 'function') { col.forEach(f, opt_obj); } else if (goog.isArrayLike(col) || goog.isString(col)) { goog.array.forEach(/** @type {!Array<?>} */ (col), f, opt_obj); } else { var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col); } } }; /** * Calls a function for every value in the collection. When a call returns true, * adds the value to a new collection (Array is returned by default). * * @param {S} col The collection-like object. * @param {function(this:T,?,?,S):boolean} f The function to call for every * value. This function takes * 3 arguments (the value, the key or undefined if the collection has no * notion of keys, and the collection) and should return a Boolean. If the * return value is true the value is added to the result collection. If it * is false the value is not included. * @param {T=} opt_obj The object to be used as the value of 'this' * within `f`. * @return {!Object|!Array<?>} A new collection where the passed values are * present. If col is a key-less collection an array is returned. If col * has keys and values a plain old JS object is returned. * @template T,S */ goog.structs.filter = function(col, f, opt_obj) { if (typeof col.filter == 'function') { return col.filter(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.filter(/** @type {!Array<?>} */ (col), f, opt_obj); } var rv; var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; if (keys) { rv = {}; for (var i = 0; i < l; i++) { if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) { rv[keys[i]] = values[i]; } } } else { // We should not use goog.array.filter here since we want to make sure that // the index is undefined as well as make sure that col is passed to the // function. rv = []; for (var i = 0; i < l; i++) { if (f.call(opt_obj, values[i], undefined, col)) { rv.push(values[i]); } } } return rv; }; /** * Calls a function for every value in the collection and adds the result into a * new collection (defaults to creating a new Array). * * @param {S} col The collection-like object. * @param {function(this:T,?,?,S):V} f The function to call for every value. * This function takes 3 arguments (the value, the key or undefined if the * collection has no notion of keys, and the collection) and should return * something. The result will be used as the value in the new collection. * @param {T=} opt_obj The object to be used as the value of 'this' * within `f`. * @return {!Object<V>|!Array<V>} A new collection with the new values. If * col is a key-less collection an array is returned. If col has keys and * values a plain old JS object is returned. * @template T,S,V */ goog.structs.map = function(col, f, opt_obj) { if (typeof col.map == 'function') { return col.map(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.map(/** @type {!Array<?>} */ (col), f, opt_obj); } var rv; var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; if (keys) { rv = {}; for (var i = 0; i < l; i++) { rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col); } } else { // We should not use goog.array.map here since we want to make sure that // the index is undefined as well as make sure that col is passed to the // function. rv = []; for (var i = 0; i < l; i++) { rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col); } } return rv; }; /** * Calls f for each value in a collection. If any call returns true this returns * true (without checking the rest). If all returns false this returns false. * * @param {S} col The collection-like object. * @param {function(this:T,?,?,S):boolean} f The function to call for every * value. This function takes 3 arguments (the value, the key or undefined * if the collection has no notion of keys, and the collection) and should * return a boolean. * @param {T=} opt_obj The object to be used as the value of 'this' * within `f`. * @return {boolean} True if any value passes the test. * @template T,S */ goog.structs.some = function(col, f, opt_obj) { if (typeof col.some == 'function') { return col.some(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.some(/** @type {!Array<?>} */ (col), f, opt_obj); } var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) { return true; } } return false; }; /** * Calls f for each value in a collection. If all calls return true this return * true this returns true. If any returns false this returns false at this point * and does not continue to check the remaining values. * * @param {S} col The collection-like object. * @param {function(this:T,?,?,S):boolean} f The function to call for every * value. This function takes 3 arguments (the value, the key or * undefined if the collection has no notion of keys, and the collection) * and should return a boolean. * @param {T=} opt_obj The object to be used as the value of 'this' * within `f`. * @return {boolean} True if all key-value pairs pass the test. * @template T,S */ goog.structs.every = function(col, f, opt_obj) { if (typeof col.every == 'function') { return col.every(f, opt_obj); } if (goog.isArrayLike(col) || goog.isString(col)) { return goog.array.every(/** @type {!Array<?>} */ (col), f, opt_obj); } var keys = goog.structs.getKeys(col); var values = goog.structs.getValues(col); var l = values.length; for (var i = 0; i < l; i++) { if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) { return false; } } return true; }; //javascript/closure/uri/utils.js // Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Simple utilities for dealing with URI strings. * * This is intended to be a lightweight alternative to constructing goog.Uri * objects. Whereas goog.Uri adds several kilobytes to the binary regardless * of how much of its functionality you use, this is designed to be a set of * mostly-independent utilities so that the compiler includes only what is * necessary for the task. Estimated savings of porting is 5k pre-gzip and * 1.5k post-gzip. To ensure the savings remain, future developers should * avoid adding new functionality to existing functions, but instead create * new ones and factor out shared code. * * Many of these utilities have limited functionality, tailored to common * cases. The query parameter utilities assume that the parameter keys are * already encoded, since most keys are compile-time alphanumeric strings. The * query parameter mutation utilities also do not tolerate fragment identifiers. * * By design, these functions can be slower than goog.Uri equivalents. * Repeated calls to some of functions may be quadratic in behavior for IE, * although the effect is somewhat limited given the 2kb limit. * * One advantage of the limited functionality here is that this approach is * less sensitive to differences in URI encodings than goog.Uri, since these * functions operate on strings directly, rather than decoding them and * then re-encoding. * * Uses features of RFC 3986 for parsing/formatting URIs: * http://www.ietf.org/rfc/rfc3986.txt * * @author <EMAIL> (<NAME>) - The "lightened" design. * @author <EMAIL> (<NAME>) - Domain knowledge and regexes. */ goog.provide('goog.uri.utils'); goog.provide('goog.uri.utils.ComponentIndex'); goog.provide('goog.uri.utils.QueryArray'); goog.provide('goog.uri.utils.QueryValue'); goog.provide('goog.uri.utils.StandardQueryParam'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.string'); /** * Character codes inlined to avoid object allocations due to charCode. * @enum {number} * @private */ goog.uri.utils.CharCode_ = { AMPERSAND: 38, EQUAL: 61, HASH: 35, QUESTION: 63 }; /** * Builds a URI string from already-encoded parts. * * No encoding is performed. Any component may be omitted as either null or * undefined. * * @param {?string=} opt_scheme The scheme such as 'http'. * @param {?string=} opt_userInfo The user name before the '@'. * @param {?string=} opt_domain The domain such as 'www.google.com', already * URI-encoded. * @param {(string|number|null)=} opt_port The port number. * @param {?string=} opt_path The path, already URI-encoded. If it is not * empty, it must begin with a slash. * @param {?string=} opt_queryData The URI-encoded query data. * @param {?string=} opt_fragment The URI-encoded fragment identifier. * @return {string} The fully combined URI. */ goog.uri.utils.buildFromEncodedParts = function( opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) { var out = ''; if (opt_scheme) { out += opt_scheme + ':'; } if (opt_domain) { out += '//'; if (opt_userInfo) { out += opt_userInfo + '@'; } out += opt_domain; if (opt_port) { out += ':' + opt_port; } } if (opt_path) { out += opt_path; } if (opt_queryData) { out += '?' + opt_queryData; } if (opt_fragment) { out += '#' + opt_fragment; } return out; }; /** * A regular expression for breaking a URI into its component parts. * * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B * As the "first-match-wins" algorithm is identical to the "greedy" * disambiguation method used by POSIX regular expressions, it is natural and * commonplace to use a regular expression for parsing the potential five * components of a URI reference. * * The following line is the regular expression for breaking-down a * well-formed URI reference into its components. * * <pre> * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))? * 12 3 4 5 6 7 8 9 * </pre> * * The numbers in the second line above are only to assist readability; they * indicate the reference points for each subexpression (i.e., each paired * parenthesis). We refer to the value matched for subexpression <n> as $<n>. * For example, matching the above expression to * <pre> * http://www.ics.uci.edu/pub/ietf/uri/#Related * </pre> * results in the following subexpression matches: * <pre> * $1 = http: * $2 = http * $3 = //www.ics.uci.edu * $4 = www.ics.uci.edu * $5 = /pub/ietf/uri/ * $6 = <undefined> * $7 = <undefined> * $8 = #Related * $9 = Related * </pre> * where <undefined> indicates that the component is not present, as is the * case for the query component in the above example. Therefore, we can * determine the value of the five components as * <pre> * scheme = $2 * authority = $4 * path = $5 * query = $7 * fragment = $9 * </pre> * * The regular expression has been modified slightly to expose the * userInfo, domain, and port separately from the authority. * The modified version yields * <pre> * $1 = http scheme * $2 = <undefined> userInfo -\ * $3 = www.ics.uci.edu domain | authority * $4 = <undefined> port -/ * $5 = /pub/ietf/uri/ path * $6 = <undefined> query without ? * $7 = Related fragment without # * </pre> * @type {!RegExp} * @private */ goog.uri.utils.splitRe_ = new RegExp( '^' + '(?:' + '([^:/?#.]+)' + // scheme - ignore special characters // used by other URL parts such as :, // ?, /, #, and . ':)?' + '(?://' + '(?:([^/?#]*)@)?' + // userInfo '([^/#?]*?)' + // domain '(?::([0-9]+))?' + // port '(?=[/#?]|$)' + // authority-terminating character ')?' + '([^?#]+)?' + // path '(?:\\?([^#]*))?' + // query '(?:#([\\s\\S]*))?' + // fragment '$'); /** * The index of each URI component in the return value of goog.uri.utils.split. * @enum {number} */ goog.uri.utils.ComponentIndex = { SCHEME: 1, USER_INFO: 2, DOMAIN: 3, PORT: 4, PATH: 5, QUERY_DATA: 6, FRAGMENT: 7 }; /** * Splits a URI into its component parts. * * Each component can be accessed via the component indices; for example: * <pre> * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA]; * </pre> * * @param {string} uri The URI string to examine. * @return {!Array<string|undefined>} Each component still URI-encoded. * Each component that is present will contain the encoded value, whereas * components that are not present will be undefined or empty, depending * on the browser's regular expression implementation. Never null, since * arbitrary strings may still look like path names. */ goog.uri.utils.split = function(uri) { // See @return comment -- never null. return /** @type {!Array<string|undefined>} */ ( uri.match(goog.uri.utils.splitRe_)); }; /** * @param {?string} uri A possibly null string. * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986 * reserved characters will not be removed. * @return {?string} The string URI-decoded, or null if uri is null. * @private */ goog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) { if (!uri) { return uri; } return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri); }; /** * Gets a URI component by index. * * It is preferred to use the getPathEncoded() variety of functions ahead, * since they are more readable. * * @param {goog.uri.utils.ComponentIndex} componentIndex The component index. * @param {string} uri The URI to examine. * @return {?string} The still-encoded component, or null if the component * is not present. * @private */ goog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) { // Convert undefined, null, and empty string into null. return goog.uri.utils.split(uri)[componentIndex] || null; }; /** * @param {string} uri The URI to examine. * @return {?string} The protocol or scheme, or null if none. Does not * include trailing colons or slashes. */ goog.uri.utils.getScheme = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.SCHEME, uri); }; /** * Gets the effective scheme for the URL. If the URL is relative then the * scheme is derived from the page's location. * @param {string} uri The URI to examine. * @return {string} The protocol or scheme, always lower case. */ goog.uri.utils.getEffectiveScheme = function(uri) { var scheme = goog.uri.utils.getScheme(uri); if (!scheme && goog.global.self && goog.global.self.location) { var protocol = goog.global.self.location.protocol; scheme = protocol.substr(0, protocol.length - 1); } // NOTE: When called from a web worker in Firefox 3.5, location maybe null. // All other browsers with web workers support self.location from the worker. return scheme ? scheme.toLowerCase() : ''; }; /** * @param {string} uri The URI to examine. * @return {?string} The user name still encoded, or null if none. */ goog.uri.utils.getUserInfoEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.USER_INFO, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded user info, or null if none. */ goog.uri.utils.getUserInfo = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getUserInfoEncoded(uri)); }; /** * @param {string} uri The URI to examine. * @return {?string} The domain name still encoded, or null if none. */ goog.uri.utils.getDomainEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.DOMAIN, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded domain, or null if none. */ goog.uri.utils.getDomain = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */); }; /** * @param {string} uri The URI to examine. * @return {?number} The port number, or null if none. */ goog.uri.utils.getPort = function(uri) { // Coerce to a number. If the result of getComponentByIndex_ is null or // non-numeric, the number coersion yields NaN. This will then return // null for all non-numeric cases (though also zero, which isn't a relevant // port number). return Number( goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.PORT, uri)) || null; }; /** * @param {string} uri The URI to examine. * @return {?string} The path still encoded, or null if none. Includes the * leading slash, if any. */ goog.uri.utils.getPathEncoded = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.PATH, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded path, or null if none. Includes the leading * slash, if any. */ goog.uri.utils.getPath = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */); }; /** * @param {string} uri The URI to examine. * @return {?string} The query data still encoded, or null if none. Does not * include the question mark itself. */ goog.uri.utils.getQueryData = function(uri) { return goog.uri.utils.getComponentByIndex_( goog.uri.utils.ComponentIndex.QUERY_DATA, uri); }; /** * @param {string} uri The URI to examine. * @return {?string} The fragment identifier, or null if none. Does not * include the hash mark itself. */ goog.uri.utils.getFragmentEncoded = function(uri) { // The hash mark may not appear in any other part of the URL. var hashIndex = uri.indexOf('#'); return hashIndex < 0 ? null : uri.substr(hashIndex + 1); }; /** * @param {string} uri The URI to examine. * @param {?string} fragment The encoded fragment identifier, or null if none. * Does not include the hash mark itself. * @return {string} The URI with the fragment set. */ goog.uri.utils.setFragmentEncoded = function(uri, fragment) { return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : ''); }; /** * @param {string} uri The URI to examine. * @return {?string} The decoded fragment identifier, or null if none. Does * not include the hash mark. */ goog.uri.utils.getFragment = function(uri) { return goog.uri.utils.decodeIfPossible_( goog.uri.utils.getFragmentEncoded(uri)); }; /** * Extracts everything up to the port of the URI. * @param {string} uri The URI string. * @return {string} Everything up to and including the port. */ goog.uri.utils.getHost = function(uri) { var pieces = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts( pieces[goog.uri.utils.ComponentIndex.SCHEME], pieces[goog.uri.utils.ComponentIndex.USER_INFO], pieces[goog.uri.utils.ComponentIndex.DOMAIN], pieces[goog.uri.utils.ComponentIndex.PORT]); }; /** * Returns the origin for a given URL. * @param {string} uri The URI string. * @return {string} Everything up to and including the port. */ goog.uri.utils.getOrigin = function(uri) { var pieces = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts( pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */, pieces[goog.uri.utils.ComponentIndex.DOMAIN], pieces[goog.uri.utils.ComponentIndex.PORT]); }; /** * Extracts the path of the URL and everything after. * @param {string} uri The URI string. * @return {string} The URI, starting at the path and including the query * parameters and fragment identifier. */ goog.uri.utils.getPathAndAfter = function(uri) { var pieces = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts( null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH], pieces[goog.uri.utils.ComponentIndex.QUERY_DATA], pieces[goog.uri.utils.ComponentIndex.FRAGMENT]); }; /** * Gets the URI with the fragment identifier removed. * @param {string} uri The URI to examine. * @return {string} Everything preceding the hash mark. */ goog.uri.utils.removeFragment = function(uri) { // The hash mark may not appear in any other part of the URL. var hashIndex = uri.indexOf('#'); return hashIndex < 0 ? uri : uri.substr(0, hashIndex); }; /** * Ensures that two URI's have the exact same domain, scheme, and port. * * Unlike the version in goog.Uri, this checks protocol, and therefore is * suitable for checking against the browser's same-origin policy. * * @param {string} uri1 The first URI. * @param {string} uri2 The second URI. * @return {boolean} Whether they have the same scheme, domain and port. */ goog.uri.utils.haveSameDomain = function(uri1, uri2) { var pieces1 = goog.uri.utils.split(uri1); var pieces2 = goog.uri.utils.split(uri2); return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && pieces1[goog.uri.utils.ComponentIndex.SCHEME] == pieces2[goog.uri.utils.ComponentIndex.SCHEME] && pieces1[goog.uri.utils.ComponentIndex.PORT] == pieces2[goog.uri.utils.ComponentIndex.PORT]; }; /** * Asserts that there are no fragment or query identifiers, only in uncompiled * mode. * @param {string} uri The URI to examine. * @private */ goog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) { goog.asserts.assert( uri.indexOf('#') < 0 && uri.indexOf('?') < 0, 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]', uri); }; /** * Supported query parameter values by the parameter serializing utilities. * * If a value is null or undefined, the key-value pair is skipped, as an easy * way to omit parameters conditionally. Non-array parameters are converted * to a string and URI encoded. Array values are expanded into multiple * &key=value pairs, with each element stringized and URI-encoded. * * @typedef {*} */ goog.uri.utils.QueryValue; /** * An array representing a set of query parameters with alternating keys * and values. * * Keys are assumed to be URI encoded already and live at even indices. See * goog.uri.utils.QueryValue for details on how parameter values are encoded. * * Example: * <pre> * var data = [ * // Simple param: ?name=BobBarker * 'name', 'BobBarker', * // Conditional param -- may be omitted entirely. * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null, * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null * 'house', ['LosAngeles', 'NewYork', null] * ]; * </pre> * * @typedef {!Array<string|goog.uri.utils.QueryValue>} */ goog.uri.utils.QueryArray; /** * Parses encoded query parameters and calls callback function for every * parameter found in the string. * * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means * that “…&=&…” and “…&&…” will result in an empty key and value. * * @param {string} encodedQuery Encoded query string excluding question mark at * the beginning. * @param {function(string, string)} callback Function called for every * parameter found in query string. The first argument (name) will not be * urldecoded (so the function is consistent with buildQueryData), but the * second will. If the parameter has no value (i.e. “=” was not present) * the second argument (value) will be an empty string. */ goog.uri.utils.parseQueryData = function(encodedQuery, callback) { if (!encodedQuery) { return; } var pairs = encodedQuery.split('&'); for (var i = 0; i < pairs.length; i++) { var indexOfEquals = pairs[i].indexOf('='); var name = null; var value = null; if (indexOfEquals >= 0) { name = pairs[i].substring(0, indexOfEquals); value = pairs[i].substring(indexOfEquals + 1); } else { name = pairs[i]; } callback(name, value ? goog.string.urlDecode(value) : ''); } }; /** * Split the URI into 3 parts where the [1] is the queryData without a leading * '?'. For example, the URI http://foo.com/bar?a=b#abc returns * ['http://foo.com/bar','a=b','#abc']. * @param {string} uri The URI to parse. * @return {!Array<string>} An array representation of uri of length 3 where the * middle value is the queryData without a leading '?'. * @private */ goog.uri.utils.splitQueryData_ = function(uri) { // Find the query data and and hash. var hashIndex = uri.indexOf('#'); if (hashIndex < 0) { hashIndex = uri.length; } var questionIndex = uri.indexOf('?'); var queryData; if (questionIndex < 0 || questionIndex > hashIndex) { questionIndex = hashIndex; queryData = ''; } else { queryData = uri.substring(questionIndex + 1, hashIndex); } return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)]; }; /** * Join an array created by splitQueryData_ back into a URI. * @param {!Array<string>} parts A URI in the form generated by splitQueryData_. * @return {string} The joined URI. * @private */ goog.uri.utils.joinQueryData_ = function(parts) { return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2]; }; /** * @param {string} queryData * @param {string} newData * @return {string} * @private */ goog.uri.utils.appendQueryData_ = function(queryData, newData) { if (!newData) { return queryData; } return queryData ? queryData + '&' + newData : newData; }; /** * @param {string} uri * @param {string} queryData * @return {string} * @private */ goog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) { if (!queryData) { return uri; } var parts = goog.uri.utils.splitQueryData_(uri); parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData); return goog.uri.utils.joinQueryData_(parts); }; /** * Appends key=value pairs to an array, supporting multi-valued objects. * @param {*} key The key prefix. * @param {goog.uri.utils.QueryValue} value The value to serialize. * @param {!Array<string>} pairs The array to which the 'key=value' strings * should be appended. * @private */ goog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) { goog.asserts.assertString(key); if (goog.isArray(value)) { // Convince the compiler it's an array. goog.asserts.assertArray(value); for (var j = 0; j < value.length; j++) { // Convert to string explicitly, to short circuit the null and array // logic in this function -- this ensures that null and undefined get // written as literal 'null' and 'undefined', and arrays don't get // expanded out but instead encoded in the default way. goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs); } } else if (value != null) { // Skip a top-level null or undefined entirely. pairs.push( key + // Check for empty string. Zero gets encoded into the url as literal // strings. For empty string, skip the equal sign, to be consistent // with UriBuilder.java. (value === '' ? '' : '=' + goog.string.urlEncode(value))); } }; /** * Builds a query data string from a sequence of alternating keys and values. * Currently generates "&key&" for empty args. * * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues * Alternating keys and values. See the QueryArray typedef. * @param {number=} opt_startIndex A start offset into the arary, defaults to 0. * @return {string} The encoded query string, in the form 'a=1&b=2'. */ goog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) { goog.asserts.assert( Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0, 'goog.uri.utils: Key/value lists must be even in length.'); var params = []; for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) { var key = /** @type {string} */ (keysAndValues[i]); goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params); } return params.join('&'); }; /** * Builds a query data string from a map. * Currently generates "&key&" for empty args. * * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys * are URI-encoded parameter keys, and the values are arbitrary types * or arrays. Keys with a null value are dropped. * @return {string} The encoded query string, in the form 'a=1&b=2'. */ goog.uri.utils.buildQueryDataFromMap = function(map) { var params = []; for (var key in map) { goog.uri.utils.appendKeyValuePairs_(key, map[key], params); } return params.join('&'); }; /** * Appends URI parameters to an existing URI. * * The variable arguments may contain alternating keys and values. Keys are * assumed to be already URI encoded. The values should not be URI-encoded, * and will instead be encoded by this function. * <pre> * appendParams('http://www.foo.com?existing=true', * 'key1', 'value1', * 'key2', 'value?willBeEncoded', * 'key3', ['valueA', 'valueB', 'valueC'], * 'key4', null); * result: 'http://www.foo.com?existing=true&' + * 'key1=value1&' + * 'key2=value%3FwillBeEncoded&' + * 'key3=valueA&key3=valueB&key3=valueC' * </pre> * * A single call to this function will not exhibit quadratic behavior in IE, * whereas multiple repeated calls may, although the effect is limited by * fact that URL's generally can't exceed 2kb. * * @param {string} uri The original URI, which may already have query data. * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)} * var_args * An array or argument list conforming to goog.uri.utils.QueryArray. * @return {string} The URI with all query parameters added. */ goog.uri.utils.appendParams = function(uri, var_args) { var queryData = arguments.length == 2 ? goog.uri.utils.buildQueryData(arguments[1], 0) : goog.uri.utils.buildQueryData(arguments, 1); return goog.uri.utils.appendQueryDataToUri_(uri, queryData); }; /** * Appends query parameters from a map. * * @param {string} uri The original URI, which may already have query data. * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are * URI-encoded parameter keys, and the values are arbitrary types or arrays. * Keys with a null value are dropped. * @return {string} The new parameters. */ goog.uri.utils.appendParamsFromMap = function(uri, map) { var queryData = goog.uri.utils.buildQueryDataFromMap(map); return goog.uri.utils.appendQueryDataToUri_(uri, queryData); }; /** * Appends a single URI parameter. * * Repeated calls to this can exhibit quadratic behavior in IE6 due to the * way string append works, though it should be limited given the 2kb limit. * * @param {string} uri The original URI, which may already have query data. * @param {string} key The key, which must already be URI encoded. * @param {*=} opt_value The value, which will be stringized and encoded * (assumed not already to be encoded). If omitted, undefined, or null, the * key will be added as a valueless parameter. * @return {string} The URI with the query parameter added. */ goog.uri.utils.appendParam = function(uri, key, opt_value) { var value = goog.isDefAndNotNull(opt_value) ? '=' + goog.string.urlEncode(opt_value) : ''; return goog.uri.utils.appendQueryDataToUri_(uri, key + value); }; /** * Finds the next instance of a query parameter with the specified name. * * Does not instantiate any objects. * * @param {string} uri The URI to search. May contain a fragment identifier * if opt_hashIndex is specified. * @param {number} startIndex The index to begin searching for the key at. A * match may be found even if this is one character after the ampersand. * @param {string} keyEncoded The URI-encoded key. * @param {number} hashOrEndIndex Index to stop looking at. If a hash * mark is present, it should be its index, otherwise it should be the * length of the string. * @return {number} The position of the first character in the key's name, * immediately after either a question mark or a dot. * @private */ goog.uri.utils.findParam_ = function( uri, startIndex, keyEncoded, hashOrEndIndex) { var index = startIndex; var keyLength = keyEncoded.length; // Search for the key itself and post-filter for surronuding punctuation, // rather than expensively building a regexp. while ((index = uri.indexOf(keyEncoded, index)) >= 0 && index < hashOrEndIndex) { var precedingChar = uri.charCodeAt(index - 1); // Ensure that the preceding character is '&' or '?'. if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND || precedingChar == goog.uri.utils.CharCode_.QUESTION) { // Ensure the following character is '&', '=', '#', or NaN // (end of string). var followingChar = uri.charCodeAt(index + keyLength); if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL || followingChar == goog.uri.utils.CharCode_.AMPERSAND || followingChar == goog.uri.utils.CharCode_.HASH) { return index; } } index += keyLength + 1; } return -1; }; /** * Regular expression for finding a hash mark or end of string. * @type {RegExp} * @private */ goog.uri.utils.hashOrEndRe_ = /#|$/; /** * Determines if the URI contains a specific key. * * Performs no object instantiations. * * @param {string} uri The URI to process. May contain a fragment * identifier. * @param {string} keyEncoded The URI-encoded key. Case-sensitive. * @return {boolean} Whether the key is present. */ goog.uri.utils.hasParam = function(uri, keyEncoded) { return goog.uri.utils.findParam_( uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0; }; /** * Gets the first value of a query parameter. * @param {string} uri The URI to process. May contain a fragment. * @param {string} keyEncoded The URI-encoded key. Case-sensitive. * @return {?string} The first value of the parameter (URI-decoded), or null * if the parameter is not found. */ goog.uri.utils.getParamValue = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var foundIndex = goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex); if (foundIndex < 0) { return null; } else { var endPosition = uri.indexOf('&', foundIndex); if (endPosition < 0 || endPosition > hashOrEndIndex) { endPosition = hashOrEndIndex; } // Progress forth to the end of the "key=" or "key&" substring. foundIndex += keyEncoded.length + 1; // Use substr, because it (unlike substring) will return empty string // if foundIndex > endPosition. return goog.string.urlDecode( uri.substr(foundIndex, endPosition - foundIndex)); } }; /** * Gets all values of a query parameter. * @param {string} uri The URI to process. May contain a fragment. * @param {string} keyEncoded The URI-encoded key. Case-sensitive. * @return {!Array<string>} All URI-decoded values with the given key. * If the key is not found, this will have length 0, but never be null. */ goog.uri.utils.getParamValues = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var position = 0; var foundIndex; var result = []; while ((foundIndex = goog.uri.utils.findParam_( uri, position, keyEncoded, hashOrEndIndex)) >= 0) { // Find where this parameter ends, either the '&' or the end of the // query parameters. position = uri.indexOf('&', foundIndex); if (position < 0 || position > hashOrEndIndex) { position = hashOrEndIndex; } // Progress forth to the end of the "key=" or "key&" substring. foundIndex += keyEncoded.length + 1; // Use substr, because it (unlike substring) will return empty string // if foundIndex > position. result.push( goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex))); } return result; }; /** * Regexp to find trailing question marks and ampersands. * @type {RegExp} * @private */ goog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/; /** * Removes all instances of a query parameter. * @param {string} uri The URI to process. Must not contain a fragment. * @param {string} keyEncoded The URI-encoded key. * @return {string} The URI with all instances of the parameter removed. */ goog.uri.utils.removeParam = function(uri, keyEncoded) { var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_); var position = 0; var foundIndex; var buffer = []; // Look for a query parameter. while ((foundIndex = goog.uri.utils.findParam_( uri, position, keyEncoded, hashOrEndIndex)) >= 0) { // Get the portion of the query string up to, but not including, the ? // or & starting the parameter. buffer.push(uri.substring(position, foundIndex)); // Progress to immediately after the '&'. If not found, go to the end. // Avoid including the hash mark. position = Math.min( (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex); } // Append everything that is remaining. buffer.push(uri.substr(position)); // Join the buffer, and remove trailing punctuation that remains. return buffer.join('').replace( goog.uri.utils.trailingQueryPunctuationRe_, '$1'); }; /** * Replaces all existing definitions of a parameter with a single definition. * * Repeated calls to this can exhibit quadratic behavior due to the need to * find existing instances and reconstruct the string, though it should be * limited given the 2kb limit. Consider using appendParams or setParamsFromMap * to update multiple parameters in bulk. * * @param {string} uri The original URI, which may already have query data. * @param {string} keyEncoded The key, which must already be URI encoded. * @param {*} value The value, which will be stringized and encoded (assumed * not already to be encoded). * @return {string} The URI with the query parameter added. */ goog.uri.utils.setParam = function(uri, keyEncoded, value) { return goog.uri.utils.appendParam( goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value); }; /** * Effeciently set or remove multiple query parameters in a URI. Order of * unchanged parameters will not be modified, all updated parameters will be * appended to the end of the query. Params with values of null or undefined are * removed. * * @param {string} uri The URI to process. * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of * parameters to update. If null or undefined, the param will be removed. * @return {string} An updated URI where the query data has been updated with * the params. */ goog.uri.utils.setParamsFromMap = function(uri, params) { var parts = goog.uri.utils.splitQueryData_(uri); var queryData = parts[1]; var buffer = []; if (queryData) { goog.array.forEach(queryData.split('&'), function(pair) { var indexOfEquals = pair.indexOf('='); var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair; if (!params.hasOwnProperty(name)) { buffer.push(pair); } }); } parts[1] = goog.uri.utils.appendQueryData_( buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params)); return goog.uri.utils.joinQueryData_(parts); }; /** * Generates a URI path using a given URI and a path with checks to * prevent consecutive "//". The baseUri passed in must not contain * query or fragment identifiers. The path to append may not contain query or * fragment identifiers. * * @param {string} baseUri URI to use as the base. * @param {string} path Path to append. * @return {string} Updated URI. */ goog.uri.utils.appendPath = function(baseUri, path) { goog.uri.utils.assertNoFragmentsOrQueries_(baseUri); // Remove any trailing '/' if (goog.string.endsWith(baseUri, '/')) { baseUri = baseUri.substr(0, baseUri.length - 1); } // Remove any leading '/' if (goog.string.startsWith(path, '/')) { path = path.substr(1); } return goog.string.buildString(baseUri, '/', path); }; /** * Replaces the path. * @param {string} uri URI to use as the base. * @param {string} path New path. * @return {string} Updated URI. */ goog.uri.utils.setPath = function(uri, path) { // Add any missing '/'. if (!goog.string.startsWith(path, '/')) { path = '/' + path; } var parts = goog.uri.utils.split(uri); return goog.uri.utils.buildFromEncodedParts( parts[goog.uri.utils.ComponentIndex.SCHEME], parts[goog.uri.utils.ComponentIndex.USER_INFO], parts[goog.uri.utils.ComponentIndex.DOMAIN], parts[goog.uri.utils.ComponentIndex.PORT], path, parts[goog.uri.utils.ComponentIndex.QUERY_DATA], parts[goog.uri.utils.ComponentIndex.FRAGMENT]); }; /** * Standard supported query parameters. * @enum {string} */ goog.uri.utils.StandardQueryParam = { /** Unused parameter for unique-ifying. */ RANDOM: 'zx' }; /** * Sets the zx parameter of a URI to a random value. * @param {string} uri Any URI. * @return {string} That URI with the "zx" parameter added or replaced to * contain a random string. */ goog.uri.utils.makeUnique = function(uri) { return goog.uri.utils.setParam( uri, goog.uri.utils.StandardQueryParam.RANDOM, goog.string.getRandomString()); }; //javascript/closure/uri/uri.js // Copyright 2006 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Class for parsing and formatting URIs. * * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to * create a new instance of the goog.Uri object from Uri parts. * * e.g: <code>var myUri = new goog.Uri(window.location);</code> * * Implements RFC 3986 for parsing/formatting URIs. * http://www.ietf.org/rfc/rfc3986.txt * * Some changes have been made to the interface (more like .NETs), though the * internal representation is now of un-encoded parts, this will change the * behavior slightly. * * @author <EMAIL> (<NAME>) * @author <EMAIL> (<NAME>) - Ported to Closure * @author <EMAIL> (<NAME>) - Optimized for IE6 * @author <EMAIL> (<NAME>-Los) - Dot segments removal */ goog.provide('goog.Uri'); goog.provide('goog.Uri.QueryData'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.string'); goog.require('goog.structs'); goog.require('goog.structs.Map'); goog.require('goog.uri.utils'); goog.require('goog.uri.utils.ComponentIndex'); goog.require('goog.uri.utils.StandardQueryParam'); /** * This class contains setters and getters for the parts of the URI. * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the * decoded path, <code>/foo bar</code>. * * Reserved characters (see RFC 3986 section 2.2) can be present in * their percent-encoded form in scheme, domain, and path URI components and * will not be auto-decoded. For example: * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will * return <code>relative/path%2fto/resource</code>. * * The constructor accepts an optional unparsed, raw URI string. The parser * is relaxed, so special characters that aren't escaped but don't cause * ambiguities will not cause parse failures. * * All setters return <code>this</code> and so may be chained, a la * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>. * * @param {*=} opt_uri Optional string URI to parse * (use goog.Uri.create() to create a URI from parts), or if * a goog.Uri is passed, a clone is created. * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore * the case of the parameter name. * * @throws URIError If opt_uri is provided and URI is malformed (that is, * if decodeURIComponent fails on any of the URI components). * @constructor * @struct */ goog.Uri = function(opt_uri, opt_ignoreCase) { /** * Scheme such as "http". * @private {string} */ this.scheme_ = ''; /** * User credentials in the form "username:password". * @private {string} */ this.userInfo_ = ''; /** * Domain part, e.g. "www.google.com". * @private {string} */ this.domain_ = ''; /** * Port, e.g. 8080. * @private {?number} */ this.port_ = null; /** * Path, e.g. "/tests/img.png". * @private {string} */ this.path_ = ''; /** * The fragment without the #. * @private {string} */ this.fragment_ = ''; /** * Whether or not this Uri should be treated as Read Only. * @private {boolean} */ this.isReadOnly_ = false; /** * Whether or not to ignore case when comparing query params. * @private {boolean} */ this.ignoreCase_ = false; /** * Object representing query data. * @private {!goog.Uri.QueryData} */ this.queryData_; // Parse in the uri string var m; if (opt_uri instanceof goog.Uri) { this.ignoreCase_ = goog.isDef(opt_ignoreCase) ? opt_ignoreCase : opt_uri.getIgnoreCase(); this.setScheme(opt_uri.getScheme()); this.setUserInfo(opt_uri.getUserInfo()); this.setDomain(opt_uri.getDomain()); this.setPort(opt_uri.getPort()); this.setPath(opt_uri.getPath()); this.setQueryData(opt_uri.getQueryData().clone()); this.setFragment(opt_uri.getFragment()); } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) { this.ignoreCase_ = !!opt_ignoreCase; // Set the parts -- decoding as we do so. // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings, // whereas in other browsers they will be undefined. this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true); this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true); this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true); this.setPort(m[goog.uri.utils.ComponentIndex.PORT]); this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true); this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true); this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true); } else { this.ignoreCase_ = !!opt_ignoreCase; this.queryData_ = new goog.Uri.QueryData(null, null, this.ignoreCase_); } }; /** * If true, we preserve the type of query parameters set programmatically. * * This means that if you set a parameter to a boolean, and then call * getParameterValue, you will get a boolean back. * * If false, we will coerce parameters to strings, just as they would * appear in real URIs. * * TODO(nicksantos): Remove this once people have time to fix all tests. * * @type {boolean} */ goog.Uri.preserveParameterTypesCompatibilityFlag = false; /** * Parameter name added to stop caching. * @type {string} */ goog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM; /** * @return {string} The string form of the url. * @override */ goog.Uri.prototype.toString = function() { var out = []; var scheme = this.getScheme(); if (scheme) { out.push( goog.Uri.encodeSpecialChars_( scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), ':'); } var domain = this.getDomain(); if (domain || scheme == 'file') { out.push('//'); var userInfo = this.getUserInfo(); if (userInfo) { out.push( goog.Uri.encodeSpecialChars_( userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true), '@'); } out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain))); var port = this.getPort(); if (port != null) { out.push(':', String(port)); } } var path = this.getPath(); if (path) { if (this.hasDomain() && path.charAt(0) != '/') { out.push('/'); } out.push( goog.Uri.encodeSpecialChars_( path, path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ : goog.Uri.reDisallowedInRelativePath_, true)); } var query = this.getEncodedQuery(); if (query) { out.push('?', query); } var fragment = this.getFragment(); if (fragment) { out.push( '#', goog.Uri.encodeSpecialChars_( fragment, goog.Uri.reDisallowedInFragment_)); } return out.join(''); }; /** * Resolves the given relative URI (a goog.Uri object), using the URI * represented by this instance as the base URI. * * There are several kinds of relative URIs:<br> * 1. foo - replaces the last part of the path, the whole query and fragment<br> * 2. /foo - replaces the the path, the query and fragment<br> * 3. //foo - replaces everything from the domain on. foo is a domain name<br> * 4. ?foo - replace the query and fragment<br> * 5. #foo - replace the fragment only * * Additionally, if relative URI has a non-empty path, all ".." and "." * segments will be resolved, as described in RFC 3986. * * @param {!goog.Uri} relativeUri The relative URI to resolve. * @return {!goog.Uri} The resolved URI. */ goog.Uri.prototype.resolve = function(relativeUri) { var absoluteUri = this.clone(); // we satisfy these conditions by looking for the first part of relativeUri // that is not blank and applying defaults to the rest var overridden = relativeUri.hasScheme(); if (overridden) { absoluteUri.setScheme(relativeUri.getScheme()); } else { overridden = relativeUri.hasUserInfo(); } if (overridden) { absoluteUri.setUserInfo(relativeUri.getUserInfo()); } else { overridden = relativeUri.hasDomain(); } if (overridden) { absoluteUri.setDomain(relativeUri.getDomain()); } else { overridden = relativeUri.hasPort(); } var path = relativeUri.getPath(); if (overridden) { absoluteUri.setPort(relativeUri.getPort()); } else { overridden = relativeUri.hasPath(); if (overridden) { // resolve path properly if (path.charAt(0) != '/') { // path is relative if (this.hasDomain() && !this.hasPath()) { // RFC 3986, section 5.2.3, case 1 path = '/' + path; } else { // RFC 3986, section 5.2.3, case 2 var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/'); if (lastSlashIndex != -1) { path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path; } } } path = goog.Uri.removeDotSegments(path); } } if (overridden) { absoluteUri.setPath(path); } else { overridden = relativeUri.hasQuery(); } if (overridden) { absoluteUri.setQueryData(relativeUri.getQueryData().clone()); } else { overridden = relativeUri.hasFragment(); } if (overridden) { absoluteUri.setFragment(relativeUri.getFragment()); } return absoluteUri; }; /** * Clones the URI instance. * @return {!goog.Uri} New instance of the URI object. */ goog.Uri.prototype.clone = function() { return new goog.Uri(this); }; /** * @return {string} The encoded scheme/protocol for the URI. */ goog.Uri.prototype.getScheme = function() { return this.scheme_; }; /** * Sets the scheme/protocol. * @throws URIError If opt_decode is true and newScheme is malformed (that is, * if decodeURIComponent fails). * @param {string} newScheme New scheme value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setScheme = function(newScheme, opt_decode) { this.enforceReadOnly(); this.scheme_ = opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme; // remove an : at the end of the scheme so somebody can pass in // window.location.protocol if (this.scheme_) { this.scheme_ = this.scheme_.replace(/:$/, ''); } return this; }; /** * @return {boolean} Whether the scheme has been set. */ goog.Uri.prototype.hasScheme = function() { return !!this.scheme_; }; /** * @return {string} The decoded user info. */ goog.Uri.prototype.getUserInfo = function() { return this.userInfo_; }; /** * Sets the userInfo. * @throws URIError If opt_decode is true and newUserInfo is malformed (that is, * if decodeURIComponent fails). * @param {string} newUserInfo New userInfo value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) { this.enforceReadOnly(); this.userInfo_ = opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo; return this; }; /** * @return {boolean} Whether the user info has been set. */ goog.Uri.prototype.hasUserInfo = function() { return !!this.userInfo_; }; /** * @return {string} The decoded domain. */ goog.Uri.prototype.getDomain = function() { return this.domain_; }; /** * Sets the domain. * @throws URIError If opt_decode is true and newDomain is malformed (that is, * if decodeURIComponent fails). * @param {string} newDomain New domain value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setDomain = function(newDomain, opt_decode) { this.enforceReadOnly(); this.domain_ = opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain; return this; }; /** * @return {boolean} Whether the domain has been set. */ goog.Uri.prototype.hasDomain = function() { return !!this.domain_; }; /** * @return {?number} The port number. */ goog.Uri.prototype.getPort = function() { return this.port_; }; /** * Sets the port number. * @param {*} newPort Port number. Will be explicitly casted to a number. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setPort = function(newPort) { this.enforceReadOnly(); if (newPort) { newPort = Number(newPort); if (isNaN(newPort) || newPort < 0) { throw new Error('Bad port number ' + newPort); } this.port_ = newPort; } else { this.port_ = null; } return this; }; /** * @return {boolean} Whether the port has been set. */ goog.Uri.prototype.hasPort = function() { return this.port_ != null; }; /** * @return {string} The decoded path. */ goog.Uri.prototype.getPath = function() { return this.path_; }; /** * Sets the path. * @throws URIError If opt_decode is true and newPath is malformed (that is, * if decodeURIComponent fails). * @param {string} newPath New path value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setPath = function(newPath, opt_decode) { this.enforceReadOnly(); this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath; return this; }; /** * @return {boolean} Whether the path has been set. */ goog.Uri.prototype.hasPath = function() { return !!this.path_; }; /** * @return {boolean} Whether the query string has been set. */ goog.Uri.prototype.hasQuery = function() { return this.queryData_.toString() !== ''; }; /** * Sets the query data. * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object. * @param {boolean=} opt_decode Optional param for whether to decode new value. * Applies only if queryData is a string. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setQueryData = function(queryData, opt_decode) { this.enforceReadOnly(); if (queryData instanceof goog.Uri.QueryData) { this.queryData_ = queryData; this.queryData_.setIgnoreCase(this.ignoreCase_); } else { if (!opt_decode) { // QueryData accepts encoded query string, so encode it if // opt_decode flag is not true. queryData = goog.Uri.encodeSpecialChars_( queryData, goog.Uri.reDisallowedInQuery_); } this.queryData_ = new goog.Uri.QueryData(queryData, null, this.ignoreCase_); } return this; }; /** * Sets the URI query. * @param {string} newQuery New query value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setQuery = function(newQuery, opt_decode) { return this.setQueryData(newQuery, opt_decode); }; /** * @return {string} The encoded URI query, not including the ?. */ goog.Uri.prototype.getEncodedQuery = function() { return this.queryData_.toString(); }; /** * @return {string} The decoded URI query, not including the ?. */ goog.Uri.prototype.getDecodedQuery = function() { return this.queryData_.toDecodedString(); }; /** * Returns the query data. * @return {!goog.Uri.QueryData} QueryData object. */ goog.Uri.prototype.getQueryData = function() { return this.queryData_; }; /** * @return {string} The encoded URI query, not including the ?. * * Warning: This method, unlike other getter methods, returns encoded * value, instead of decoded one. */ goog.Uri.prototype.getQuery = function() { return this.getEncodedQuery(); }; /** * Sets the value of the named query parameters, clearing previous values for * that key. * * @param {string} key The parameter to set. * @param {*} value The new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setParameterValue = function(key, value) { this.enforceReadOnly(); this.queryData_.set(key, value); return this; }; /** * Sets the values of the named query parameters, clearing previous values for * that key. Not new values will currently be moved to the end of the query * string. * * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new']) * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p> * * @param {string} key The parameter to set. * @param {*} values The new values. If values is a single * string then it will be treated as the sole value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setParameterValues = function(key, values) { this.enforceReadOnly(); if (!goog.isArray(values)) { values = [String(values)]; } this.queryData_.setValues(key, values); return this; }; /** * Returns the value<b>s</b> for a given cgi parameter as a list of decoded * query parameter values. * @param {string} name The parameter to get values for. * @return {!Array<?>} The values for a given cgi parameter as a list of * decoded query parameter values. */ goog.Uri.prototype.getParameterValues = function(name) { return this.queryData_.getValues(name); }; /** * Returns the first value for a given cgi parameter or undefined if the given * parameter name does not appear in the query string. * @param {string} paramName Unescaped parameter name. * @return {string|undefined} The first value for a given cgi parameter or * undefined if the given parameter name does not appear in the query * string. */ goog.Uri.prototype.getParameterValue = function(paramName) { // NOTE(nicksantos): This type-cast is a lie when // preserveParameterTypesCompatibilityFlag is set to true. // But this should only be set to true in tests. return /** @type {string|undefined} */ (this.queryData_.get(paramName)); }; /** * @return {string} The URI fragment, not including the #. */ goog.Uri.prototype.getFragment = function() { return this.fragment_; }; /** * Sets the URI fragment. * @throws URIError If opt_decode is true and newFragment is malformed (that is, * if decodeURIComponent fails). * @param {string} newFragment New fragment value. * @param {boolean=} opt_decode Optional param for whether to decode new value. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.setFragment = function(newFragment, opt_decode) { this.enforceReadOnly(); this.fragment_ = opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment; return this; }; /** * @return {boolean} Whether the URI has a fragment set. */ goog.Uri.prototype.hasFragment = function() { return !!this.fragment_; }; /** * Returns true if this has the same domain as that of uri2. * @param {!goog.Uri} uri2 The URI object to compare to. * @return {boolean} true if same domain; false otherwise. */ goog.Uri.prototype.hasSameDomainAs = function(uri2) { return ((!this.hasDomain() && !uri2.hasDomain()) || this.getDomain() == uri2.getDomain()) && ((!this.hasPort() && !uri2.hasPort()) || this.getPort() == uri2.getPort()); }; /** * Adds a random parameter to the Uri. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.makeUnique = function() { this.enforceReadOnly(); this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString()); return this; }; /** * Removes the named query parameter. * * @param {string} key The parameter to remove. * @return {!goog.Uri} Reference to this URI object. */ goog.Uri.prototype.removeParameter = function(key) { this.enforceReadOnly(); this.queryData_.remove(key); return this; }; /** * Sets whether Uri is read only. If this goog.Uri is read-only, * enforceReadOnly_ will be called at the start of any function that may modify * this Uri. * @param {boolean} isReadOnly whether this goog.Uri should be read only. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.setReadOnly = function(isReadOnly) { this.isReadOnly_ = isReadOnly; return this; }; /** * @return {boolean} Whether the URI is read only. */ goog.Uri.prototype.isReadOnly = function() { return this.isReadOnly_; }; /** * Checks if this Uri has been marked as read only, and if so, throws an error. * This should be called whenever any modifying function is called. */ goog.Uri.prototype.enforceReadOnly = function() { if (this.isReadOnly_) { throw new Error('Tried to modify a read-only Uri'); } }; /** * Sets whether to ignore case. * NOTE: If there are already key/value pairs in the QueryData, and * ignoreCase_ is set to false, the keys will all be lower-cased. * @param {boolean} ignoreCase whether this goog.Uri should ignore case. * @return {!goog.Uri} Reference to this Uri object. */ goog.Uri.prototype.setIgnoreCase = function(ignoreCase) { this.ignoreCase_ = ignoreCase; if (this.queryData_) { this.queryData_.setIgnoreCase(ignoreCase); } return this; }; /** * @return {boolean} Whether to ignore case. */ goog.Uri.prototype.getIgnoreCase = function() { return this.ignoreCase_; }; //============================================================================== // Static members //============================================================================== /** * Creates a uri from the string form. Basically an alias of new goog.Uri(). * If a Uri object is passed to parse then it will return a clone of the object. * * @throws URIError If parsing the URI is malformed. The passed URI components * should all be parseable by decodeURIComponent. * @param {*} uri Raw URI string or instance of Uri * object. * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter * names in #getParameterValue. * @return {!goog.Uri} The new URI object. */ goog.Uri.parse = function(uri, opt_ignoreCase) { return uri instanceof goog.Uri ? uri.clone() : new goog.Uri(uri, opt_ignoreCase); }; /** * Creates a new goog.Uri object from unencoded parts. * * @param {?string=} opt_scheme Scheme/protocol or full URI to parse. * @param {?string=} opt_userInfo username:password. * @param {?string=} opt_domain www.google.com. * @param {?number=} opt_port 9830. * @param {?string=} opt_path /some/path/to/a/file.html. * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2. * @param {?string=} opt_fragment The fragment without the #. * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in * #getParameterValue. * * @return {!goog.Uri} The new URI object. */ goog.Uri.create = function( opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query, opt_fragment, opt_ignoreCase) { var uri = new goog.Uri(null, opt_ignoreCase); // Only set the parts if they are defined and not empty strings. opt_scheme && uri.setScheme(opt_scheme); opt_userInfo && uri.setUserInfo(opt_userInfo); opt_domain && uri.setDomain(opt_domain); opt_port && uri.setPort(opt_port); opt_path && uri.setPath(opt_path); opt_query && uri.setQueryData(opt_query); opt_fragment && uri.setFragment(opt_fragment); return uri; }; /** * Resolves a relative Uri against a base Uri, accepting both strings and * Uri objects. * * @param {*} base Base Uri. * @param {*} rel Relative Uri. * @return {!goog.Uri} Resolved uri. */ goog.Uri.resolve = function(base, rel) { if (!(base instanceof goog.Uri)) { base = goog.Uri.parse(base); } if (!(rel instanceof goog.Uri)) { rel = goog.Uri.parse(rel); } return base.resolve(rel); }; /** * Removes dot segments in given path component, as described in * RFC 3986, section 5.2.4. * * @param {string} path A non-empty path component. * @return {string} Path component with removed dot segments. */ goog.Uri.removeDotSegments = function(path) { if (path == '..' || path == '.') { return ''; } else if ( !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) { // This optimization detects uris which do not contain dot-segments, // and as a consequence do not require any processing. return path; } else { var leadingSlash = goog.string.startsWith(path, '/'); var segments = path.split('/'); var out = []; for (var pos = 0; pos < segments.length;) { var segment = segments[pos++]; if (segment == '.') { if (leadingSlash && pos == segments.length) { out.push(''); } } else if (segment == '..') { if (out.length > 1 || out.length == 1 && out[0] != '') { out.pop(); } if (leadingSlash && pos == segments.length) { out.push(''); } } else { out.push(segment); leadingSlash = true; } } return out.join('/'); } }; /** * Decodes a value or returns the empty string if it isn't defined or empty. * @throws URIError If decodeURIComponent fails to decode val. * @param {string|undefined} val Value to decode. * @param {boolean=} opt_preserveReserved If true, restricted characters will * not be decoded. * @return {string} Decoded value. * @private */ goog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) { // Don't use UrlDecode() here because val is not a query parameter. if (!val) { return ''; } // decodeURI has the same output for '%2f' and '%252f'. We double encode %25 // so that we can distinguish between the 2 inputs. This is later undone by // removeDoubleEncoding_. return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) : decodeURIComponent(val); }; /** * If unescapedPart is non null, then escapes any characters in it that aren't * valid characters in a url and also escapes any special characters that * appear in extra. * * @param {*} unescapedPart The string to encode. * @param {RegExp} extra A character set of characters in [\01-\177]. * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent * encoding. * @return {?string} null iff unescapedPart == null. * @private */ goog.Uri.encodeSpecialChars_ = function( unescapedPart, extra, opt_removeDoubleEncoding) { if (goog.isString(unescapedPart)) { var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_); if (opt_removeDoubleEncoding) { // encodeURI double-escapes %XX sequences used to represent restricted // characters in some URI components, remove the double escaping here. encoded = goog.Uri.removeDoubleEncoding_(encoded); } return encoded; } return null; }; /** * Converts a character in [\01-\177] to its unicode character equivalent. * @param {string} ch One character string. * @return {string} Encoded string. * @private */ goog.Uri.encodeChar_ = function(ch) { var n = ch.charCodeAt(0); return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16); }; /** * Removes double percent-encoding from a string. * @param {string} doubleEncodedString String * @return {string} String with double encoding removed. * @private */ goog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) { return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1'); }; /** * Regular expression for characters that are disallowed in the scheme or * userInfo part of the URI. * @type {RegExp} * @private */ goog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\/\?@]/g; /** * Regular expression for characters that are disallowed in a relative path. * Colon is included due to RFC 3986 3.3. * @type {RegExp} * @private */ goog.Uri.reDisallowedInRelativePath_ = /[\#\?:]/g; /** * Regular expression for characters that are disallowed in an absolute path. * @type {RegExp} * @private */ goog.Uri.reDisallowedInAbsolutePath_ = /[\#\?]/g; /** * Regular expression for characters that are disallowed in the query. * @type {RegExp} * @private */ goog.Uri.reDisallowedInQuery_ = /[\#\?@]/g; /** * Regular expression for characters that are disallowed in the fragment. * @type {RegExp} * @private */ goog.Uri.reDisallowedInFragment_ = /#/g; /** * Checks whether two URIs have the same domain. * @param {string} uri1String First URI string. * @param {string} uri2String Second URI string. * @return {boolean} true if the two URIs have the same domain; false otherwise. */ goog.Uri.haveSameDomain = function(uri1String, uri2String) { // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme. // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain. var pieces1 = goog.uri.utils.split(uri1String); var pieces2 = goog.uri.utils.split(uri2String); return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] == pieces2[goog.uri.utils.ComponentIndex.DOMAIN] && pieces1[goog.uri.utils.ComponentIndex.PORT] == pieces2[goog.uri.utils.ComponentIndex.PORT]; }; /** * Class used to represent URI query parameters. It is essentially a hash of * name-value pairs, though a name can be present more than once. * * Has the same interface as the collections in goog.structs. * * @param {?string=} opt_query Optional encoded query string to parse into * the object. * @param {goog.Uri=} opt_uri Optional uri object that should have its * cache invalidated when this object updates. Deprecated -- this * is no longer required. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @constructor * @struct * @final */ goog.Uri.QueryData = function(opt_query, opt_uri, opt_ignoreCase) { /** * The map containing name/value or name/array-of-values pairs. * May be null if it requires parsing from the query string. * * We need to use a Map because we cannot guarantee that the key names will * not be problematic for IE. * * @private {goog.structs.Map<string, !Array<*>>} */ this.keyMap_ = null; /** * The number of params, or null if it requires computing. * @private {?number} */ this.count_ = null; /** * Encoded query string, or null if it requires computing from the key map. * @private {?string} */ this.encodedQuery_ = opt_query || null; /** * If true, ignore the case of the parameter name in #get. * @private {boolean} */ this.ignoreCase_ = !!opt_ignoreCase; }; /** * If the underlying key map is not yet initialized, it parses the * query string and fills the map with parsed data. * @private */ goog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() { if (!this.keyMap_) { this.keyMap_ = new goog.structs.Map(); this.count_ = 0; if (this.encodedQuery_) { var self = this; goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) { self.add(goog.string.urlDecode(name), value); }); } } }; /** * Creates a new query data instance from a map of names and values. * * @param {!goog.structs.Map<string, ?>|!Object} map Map of string parameter * names to parameter value. If parameter value is an array, it is * treated as if the key maps to each individual value in the * array. * @param {goog.Uri=} opt_uri URI object that should have its cache * invalidated when this object updates. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @return {!goog.Uri.QueryData} The populated query data instance. */ goog.Uri.QueryData.createFromMap = function(map, opt_uri, opt_ignoreCase) { var keys = goog.structs.getKeys(map); if (typeof keys == 'undefined') { throw new Error('Keys are undefined'); } var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); var values = goog.structs.getValues(map); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = values[i]; if (!goog.isArray(value)) { queryData.add(key, value); } else { queryData.setValues(key, value); } } return queryData; }; /** * Creates a new query data instance from parallel arrays of parameter names * and values. Allows for duplicate parameter names. Throws an error if the * lengths of the arrays differ. * * @param {!Array<string>} keys Parameter names. * @param {!Array<?>} values Parameter values. * @param {goog.Uri=} opt_uri URI object that should have its cache * invalidated when this object updates. * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter * name in #get. * @return {!goog.Uri.QueryData} The populated query data instance. */ goog.Uri.QueryData.createFromKeysValues = function( keys, values, opt_uri, opt_ignoreCase) { if (keys.length != values.length) { throw new Error('Mismatched lengths for keys/values'); } var queryData = new goog.Uri.QueryData(null, null, opt_ignoreCase); for (var i = 0; i < keys.length; i++) { queryData.add(keys[i], values[i]); } return queryData; }; /** * @return {?number} The number of parameters. */ goog.Uri.QueryData.prototype.getCount = function() { this.ensureKeyMapInitialized_(); return this.count_; }; /** * Adds a key value pair. * @param {string} key Name. * @param {*} value Value. * @return {!goog.Uri.QueryData} Instance of this object. */ goog.Uri.QueryData.prototype.add = function(key, value) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); key = this.getKeyName_(key); var values = this.keyMap_.get(key); if (!values) { this.keyMap_.set(key, (values = [])); } values.push(value); this.count_ = goog.asserts.assertNumber(this.count_) + 1; return this; }; /** * Removes all the params with the given key. * @param {string} key Name. * @return {boolean} Whether any parameter was removed. */ goog.Uri.QueryData.prototype.remove = function(key) { this.ensureKeyMapInitialized_(); key = this.getKeyName_(key); if (this.keyMap_.containsKey(key)) { this.invalidateCache_(); // Decrement parameter count. this.count_ = goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length; return this.keyMap_.remove(key); } return false; }; /** * Clears the parameters. */ goog.Uri.QueryData.prototype.clear = function() { this.invalidateCache_(); this.keyMap_ = null; this.count_ = 0; }; /** * @return {boolean} Whether we have any parameters. */ goog.Uri.QueryData.prototype.isEmpty = function() { this.ensureKeyMapInitialized_(); return this.count_ == 0; }; /** * Whether there is a parameter with the given name * @param {string} key The parameter name to check for. * @return {boolean} Whether there is a parameter with the given name. */ goog.Uri.QueryData.prototype.containsKey = function(key) { this.ensureKeyMapInitialized_(); key = this.getKeyName_(key); return this.keyMap_.containsKey(key); }; /** * Whether there is a parameter with the given value. * @param {*} value The value to check for. * @return {boolean} Whether there is a parameter with the given value. */ goog.Uri.QueryData.prototype.containsValue = function(value) { // NOTE(arv): This solution goes through all the params even if it was the // first param. We can get around this by not reusing code or by switching to // iterators. var vals = this.getValues(); return goog.array.contains(vals, value); }; /** * Runs a callback on every key-value pair in the map, including duplicate keys. * This won't maintain original order when duplicate keys are interspersed (like * getKeys() / getValues()). * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f * @param {SCOPE=} opt_scope The value of "this" inside f. * @template SCOPE */ goog.Uri.QueryData.prototype.forEach = function(f, opt_scope) { this.ensureKeyMapInitialized_(); this.keyMap_.forEach(function(values, key) { goog.array.forEach(values, function(value) { f.call(opt_scope, value, key, this); }, this); }, this); }; /** * Returns all the keys of the parameters. If a key is used multiple times * it will be included multiple times in the returned array * @return {!Array<string>} All the keys of the parameters. */ goog.Uri.QueryData.prototype.getKeys = function() { this.ensureKeyMapInitialized_(); // We need to get the values to know how many keys to add. var vals = this.keyMap_.getValues(); var keys = this.keyMap_.getKeys(); var rv = []; for (var i = 0; i < keys.length; i++) { var val = vals[i]; for (var j = 0; j < val.length; j++) { rv.push(keys[i]); } } return rv; }; /** * Returns all the values of the parameters with the given name. If the query * data has no such key this will return an empty array. If no key is given * all values wil be returned. * @param {string=} opt_key The name of the parameter to get the values for. * @return {!Array<?>} All the values of the parameters with the given name. */ goog.Uri.QueryData.prototype.getValues = function(opt_key) { this.ensureKeyMapInitialized_(); var rv = []; if (goog.isString(opt_key)) { if (this.containsKey(opt_key)) { rv = goog.array.concat(rv, this.keyMap_.get(this.getKeyName_(opt_key))); } } else { // Return all values. var values = this.keyMap_.getValues(); for (var i = 0; i < values.length; i++) { rv = goog.array.concat(rv, values[i]); } } return rv; }; /** * Sets a key value pair and removes all other keys with the same value. * * @param {string} key Name. * @param {*} value Value. * @return {!goog.Uri.QueryData} Instance of this object. */ goog.Uri.QueryData.prototype.set = function(key, value) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); // TODO(chrishenry): This could be better written as // this.remove(key), this.add(key, value), but that would reorder // the key (since the key is first removed and then added at the // end) and we would have to fix unit tests that depend on key // ordering. key = this.getKeyName_(key); if (this.containsKey(key)) { this.count_ = goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length; } this.keyMap_.set(key, [value]); this.count_ = goog.asserts.assertNumber(this.count_) + 1; return this; }; /** * Returns the first value associated with the key. If the query data has no * such key this will return undefined or the optional default. * @param {string} key The name of the parameter to get the value for. * @param {*=} opt_default The default value to return if the query data * has no such key. * @return {*} The first string value associated with the key, or opt_default * if there's no value. */ goog.Uri.QueryData.prototype.get = function(key, opt_default) { var values = key ? this.getValues(key) : []; if (goog.Uri.preserveParameterTypesCompatibilityFlag) { return values.length > 0 ? values[0] : opt_default; } else { return values.length > 0 ? String(values[0]) : opt_default; } }; /** * Sets the values for a key. If the key already exists, this will * override all of the existing values that correspond to the key. * @param {string} key The key to set values for. * @param {!Array<?>} values The values to set. */ goog.Uri.QueryData.prototype.setValues = function(key, values) { this.remove(key); if (values.length > 0) { this.invalidateCache_(); this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values)); this.count_ = goog.asserts.assertNumber(this.count_) + values.length; } }; /** * @return {string} Encoded query string. * @override */ goog.Uri.QueryData.prototype.toString = function() { if (this.encodedQuery_) { return this.encodedQuery_; } if (!this.keyMap_) { return ''; } var sb = []; // In the past, we use this.getKeys() and this.getVals(), but that // generates a lot of allocations as compared to simply iterating // over the keys. var keys = this.keyMap_.getKeys(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var encodedKey = goog.string.urlEncode(key); var val = this.getValues(key); for (var j = 0; j < val.length; j++) { var param = encodedKey; // Ensure that null and undefined are encoded into the url as // literal strings. if (val[j] !== '') { param += '=' + goog.string.urlEncode(val[j]); } sb.push(param); } } return this.encodedQuery_ = sb.join('&'); }; /** * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on * any of the URI components). * @return {string} Decoded query string. */ goog.Uri.QueryData.prototype.toDecodedString = function() { return goog.Uri.decodeOrEmpty_(this.toString()); }; /** * Invalidate the cache. * @private */ goog.Uri.QueryData.prototype.invalidateCache_ = function() { this.encodedQuery_ = null; }; /** * Removes all keys that are not in the provided list. (Modifies this object.) * @param {Array<string>} keys The desired keys. * @return {!goog.Uri.QueryData} a reference to this object. */ goog.Uri.QueryData.prototype.filterKeys = function(keys) { this.ensureKeyMapInitialized_(); this.keyMap_.forEach(function(value, key) { if (!goog.array.contains(keys, key)) { this.remove(key); } }, this); return this; }; /** * Clone the query data instance. * @return {!goog.Uri.QueryData} New instance of the QueryData object. */ goog.Uri.QueryData.prototype.clone = function() { var rv = new goog.Uri.QueryData(); rv.encodedQuery_ = this.encodedQuery_; if (this.keyMap_) { rv.keyMap_ = this.keyMap_.clone(); rv.count_ = this.count_; } return rv; }; /** * Helper function to get the key name from a JavaScript object. Converts * the object to a string, and to lower case if necessary. * @private * @param {*} arg The object to get a key name from. * @return {string} valid key name which can be looked up in #keyMap_. */ goog.Uri.QueryData.prototype.getKeyName_ = function(arg) { var keyName = String(arg); if (this.ignoreCase_) { keyName = keyName.toLowerCase(); } return keyName; }; /** * Ignore case in parameter names. * NOTE: If there are already key/value pairs in the QueryData, and * ignoreCase_ is set to false, the keys will all be lower-cased. * @param {boolean} ignoreCase whether this goog.Uri should ignore case. */ goog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) { var resetKeys = ignoreCase && !this.ignoreCase_; if (resetKeys) { this.ensureKeyMapInitialized_(); this.invalidateCache_(); this.keyMap_.forEach(function(value, key) { var lowerCase = key.toLowerCase(); if (key != lowerCase) { this.remove(key); this.setValues(lowerCase, value); } }, this); } this.ignoreCase_ = ignoreCase; }; /** * Extends a query data object with another query data or map like object. This * operates 'in-place', it does not create a new QueryData object. * * @param {...(?goog.Uri.QueryData|?goog.structs.Map<?, ?>|?Object)} var_args * The object from which key value pairs will be copied. * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different * types of parameters. */ goog.Uri.QueryData.prototype.extend = function(var_args) { for (var i = 0; i < arguments.length; i++) { var data = arguments[i]; goog.structs.forEach( data, function(value, key) { this.add(key, value); }, this); } }; //javascript/closure/soy/data.js // Copyright 2012 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Soy data primitives. * * The goal is to encompass data types used by Soy, especially to mark content * as known to be "safe". * * @author <EMAIL> (<NAME>) */ goog.provide('goog.soy.data.SanitizedContent'); goog.provide('goog.soy.data.SanitizedContentKind'); goog.provide('goog.soy.data.SanitizedCss'); goog.provide('goog.soy.data.SanitizedHtml'); goog.provide('goog.soy.data.SanitizedHtmlAttribute'); goog.provide('goog.soy.data.SanitizedJs'); goog.provide('goog.soy.data.SanitizedStyle'); goog.provide('goog.soy.data.SanitizedTrustedResourceUri'); goog.provide('goog.soy.data.SanitizedUri'); goog.provide('goog.soy.data.UnsanitizedText'); goog.require('goog.Uri'); goog.require('goog.asserts'); goog.require('goog.html.SafeHtml'); goog.require('goog.html.SafeScript'); goog.require('goog.html.SafeStyle'); goog.require('goog.html.SafeStyleSheet'); goog.require('goog.html.SafeUrl'); goog.require('goog.html.TrustedResourceUrl'); goog.require('goog.html.uncheckedconversions'); goog.require('goog.i18n.bidi.Dir'); goog.require('goog.string.Const'); /** * A type of textual content. * * This is an enum of type Object so that these values are unforgeable. * * @enum {!Object} */ goog.soy.data.SanitizedContentKind = { /** * A snippet of HTML that does not start or end inside a tag, comment, entity, * or DOCTYPE; and that does not contain any executable code * (JS, {@code <object>}s, etc.) from a different trust domain. */ HTML: goog.DEBUG ? {sanitizedContentKindHtml: true} : {}, /** * Executable Javascript code or expression, safe for insertion in a * script-tag or event handler context, known to be free of any * attacker-controlled scripts. This can either be side-effect-free * Javascript (such as JSON) or Javascript that's entirely under Google's * control. */ JS: goog.DEBUG ? {sanitizedContentJsChars: true} : {}, /** A properly encoded portion of a URI. */ URI: goog.DEBUG ? {sanitizedContentUri: true} : {}, /** A resource URI not under attacker control. */ TRUSTED_RESOURCE_URI: goog.DEBUG ? {sanitizedContentTrustedResourceUri: true} : {}, /** * Repeated attribute names and values. For example, * {@code dir="ltr" foo="bar" onclick="trustedFunction()" checked}. */ ATTRIBUTES: goog.DEBUG ? {sanitizedContentHtmlAttribute: true} : {}, // TODO: Consider separating rules, declarations, and values into // separate types, but for simplicity, we'll treat explicitly blessed // SanitizedContent as allowed in all of these contexts. /** * A CSS3 declaration, property, value or group of semicolon separated * declarations. */ STYLE: goog.DEBUG ? {sanitizedContentStyle: true} : {}, /** A CSS3 style sheet (list of rules). */ CSS: goog.DEBUG ? {sanitizedContentCss: true} : {}, /** * Unsanitized plain-text content. * * This is effectively the "null" entry of this enum, and is sometimes used * to explicitly mark content that should never be used unescaped. Since any * string is safe to use as text, being of ContentKind.TEXT makes no * guarantees about its safety in any other context such as HTML. */ TEXT: goog.DEBUG ? {sanitizedContentKindText: true} : {} }; /** * A string-like object that carries a content-type and a content direction. * * IMPORTANT! Do not create these directly, nor instantiate the subclasses. * Instead, use a trusted, centrally reviewed library as endorsed by your team * to generate these objects. Otherwise, you risk accidentally creating * SanitizedContent that is attacker-controlled and gets evaluated unescaped in * templates. * * @constructor */ goog.soy.data.SanitizedContent = function() { throw new Error('Do not instantiate directly'); }; /** * The context in which this content is safe from XSS attacks. * @type {goog.soy.data.SanitizedContentKind} */ goog.soy.data.SanitizedContent.prototype.contentKind; /** * The content's direction; null if unknown and thus to be estimated when * necessary. * @type {?goog.i18n.bidi.Dir} */ goog.soy.data.SanitizedContent.prototype.contentDir = null; /** * The already-safe content. * @protected {string} */ goog.soy.data.SanitizedContent.prototype.content; /** * Gets the already-safe content. * @return {string} */ goog.soy.data.SanitizedContent.prototype.getContent = function() { return this.content; }; /** @override */ goog.soy.data.SanitizedContent.prototype.toString = function() { return this.content; }; /** * Converts sanitized content of kind TEXT or HTML into SafeHtml. HTML content * is converted without modification, while text content is HTML-escaped. * @return {!goog.html.SafeHtml} * @throws {Error} when the content kind is not TEXT or HTML. */ goog.soy.data.SanitizedContent.prototype.toSafeHtml = function() { if (this.contentKind === goog.soy.data.SanitizedContentKind.TEXT) { return goog.html.SafeHtml.htmlEscape(this.toString()); } if (this.contentKind !== goog.soy.data.SanitizedContentKind.HTML) { throw new Error('Sanitized content was not of kind TEXT or HTML.'); } return goog.html.uncheckedconversions .safeHtmlFromStringKnownToSatisfyTypeContract( goog.string.Const.from( 'Soy SanitizedContent of kind HTML produces ' + 'SafeHtml-contract-compliant value.'), this.toString(), this.contentDir); }; /** * Converts sanitized content of kind URI into SafeUrl without modification. * @return {!goog.html.SafeUrl} * @throws {Error} when the content kind is not URI. */ goog.soy.data.SanitizedContent.prototype.toSafeUrl = function() { if (this.contentKind !== goog.soy.data.SanitizedContentKind.URI) { throw new Error('Sanitized content was not of kind URI.'); } return goog.html.uncheckedconversions .safeUrlFromStringKnownToSatisfyTypeContract( goog.string.Const.from( 'Soy SanitizedContent of kind URI produces ' + 'SafeHtml-contract-compliant value.'), this.toString()); }; /** * Unsanitized plain text string. * * While all strings are effectively safe to use as a plain text, there are no * guarantees about safety in any other context such as HTML. This is * sometimes used to mark that should never be used unescaped. * * @param {*} content Plain text with no guarantees. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if * unknown and thus to be estimated when necessary. Default: null. * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.UnsanitizedText = function(content, opt_contentDir) { // Not calling the superclass constructor which just throws an exception. /** @override */ this.content = String(content); this.contentDir = opt_contentDir != null ? opt_contentDir : null; }; goog.inherits(goog.soy.data.UnsanitizedText, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.UnsanitizedText.prototype.contentKind = goog.soy.data.SanitizedContentKind.TEXT; /** * Content of type {@link goog.soy.data.SanitizedContentKind.HTML}. * * The content is a string of HTML that can safely be embedded in a PCDATA * context in your app. If you would be surprised to find that an HTML * sanitizer produced `s` (e.g. it runs code or fetches bad URLs) and * you wouldn't write a template that produces `s` on security or privacy * grounds, then don't pass `s` here. The default content direction is * unknown, i.e. to be estimated when necessary. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedHtml = function() { goog.soy.data.SanitizedHtml.base(this, 'constructor'); }; goog.inherits(goog.soy.data.SanitizedHtml, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedHtml.prototype.contentKind = goog.soy.data.SanitizedContentKind.HTML; /** * Checks if the value could be used as the Soy type {html}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedHtml.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedHtml || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.SafeHtml; }; /** * Content of type {@link goog.soy.data.SanitizedContentKind.JS}. * * The content is JavaScript source that when evaluated does not execute any * attacker-controlled scripts. The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedJs = function() { goog.soy.data.SanitizedJs.base(this, 'constructor'); }; goog.inherits(goog.soy.data.SanitizedJs, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedJs.prototype.contentKind = goog.soy.data.SanitizedContentKind.JS; /** @override */ goog.soy.data.SanitizedJs.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Checks if the value could be used as the Soy type {js}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedJs.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedJs || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.SafeScript; }; /** * Content of type {@link goog.soy.data.SanitizedContentKind.URI}. * * The content is a URI chunk that the caller knows is safe to emit in a * template. The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedUri = function() { goog.soy.data.SanitizedUri.base(this, 'constructor'); }; goog.inherits(goog.soy.data.SanitizedUri, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedUri.prototype.contentKind = goog.soy.data.SanitizedContentKind.URI; /** @override */ goog.soy.data.SanitizedUri.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Checks if the value could be used as the Soy type {uri}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedUri.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedUri || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.SafeUrl || value instanceof goog.html.TrustedResourceUrl || value instanceof goog.Uri; }; /** * Content of type * {@link goog.soy.data.SanitizedContentKind.TRUSTED_RESOURCE_URI}. * * The content is a TrustedResourceUri chunk that is not under attacker control. * The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedTrustedResourceUri = function() { goog.soy.data.SanitizedTrustedResourceUri.base(this, 'constructor'); }; goog.inherits( goog.soy.data.SanitizedTrustedResourceUri, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedTrustedResourceUri.prototype.contentKind = goog.soy.data.SanitizedContentKind.TRUSTED_RESOURCE_URI; /** @override */ goog.soy.data.SanitizedTrustedResourceUri.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Converts sanitized content into TrustedResourceUrl without modification. * @return {!goog.html.TrustedResourceUrl} */ goog.soy.data.SanitizedTrustedResourceUri.prototype.toTrustedResourceUrl = function() { return goog.html.uncheckedconversions .trustedResourceUrlFromStringKnownToSatisfyTypeContract( goog.string.Const.from( 'Soy SanitizedContent of kind TRUSTED_RESOURCE_URI produces ' + 'TrustedResourceUrl-contract-compliant value.'), this.toString()); }; /** * Checks if the value could be used as the Soy type {trusted_resource_uri}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedTrustedResourceUri.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedTrustedResourceUri || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.TrustedResourceUrl; }; /** * Content of type {@link goog.soy.data.SanitizedContentKind.ATTRIBUTES}. * * The content should be safely embeddable within an open tag, such as a * key="value" pair. The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedHtmlAttribute = function() { goog.soy.data.SanitizedHtmlAttribute.base(this, 'constructor'); }; goog.inherits( goog.soy.data.SanitizedHtmlAttribute, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedHtmlAttribute.prototype.contentKind = goog.soy.data.SanitizedContentKind.ATTRIBUTES; /** @override */ goog.soy.data.SanitizedHtmlAttribute.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Checks if the value could be used as the Soy type {attribute}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedHtmlAttribute.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedHtmlAttribute || value instanceof goog.soy.data.UnsanitizedText; }; /** * Content of type {@link goog.soy.data.SanitizedContentKind.STYLE}. * * The content is non-attacker-exploitable CSS, such as `color:#c3d9ff`. * The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedStyle = function() { goog.soy.data.SanitizedStyle.base(this, 'constructor'); }; goog.inherits(goog.soy.data.SanitizedStyle, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedStyle.prototype.contentKind = goog.soy.data.SanitizedContentKind.STYLE; /** @override */ goog.soy.data.SanitizedStyle.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Checks if the value could be used as the Soy type {css}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedStyle.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedStyle || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.SafeStyle; }; /** * Content of type {@link goog.soy.data.SanitizedContentKind.CSS}. * * The content is non-attacker-exploitable CSS, such as {@code @import url(x)}. * The content direction is LTR. * * @extends {goog.soy.data.SanitizedContent} * @constructor */ goog.soy.data.SanitizedCss = function() { goog.soy.data.SanitizedCss.base(this, 'constructor'); }; goog.inherits(goog.soy.data.SanitizedCss, goog.soy.data.SanitizedContent); /** @override */ goog.soy.data.SanitizedCss.prototype.contentKind = goog.soy.data.SanitizedContentKind.CSS; /** @override */ goog.soy.data.SanitizedCss.prototype.contentDir = goog.i18n.bidi.Dir.LTR; /** * Checks if the value could be used as the Soy type {css}. * @param {*} value * @return {boolean} */ goog.soy.data.SanitizedCss.isCompatibleWith = function(value) { return goog.isString(value) || value instanceof goog.soy.data.SanitizedCss || value instanceof goog.soy.data.UnsanitizedText || value instanceof goog.html.SafeStyle || // TODO(jakubvrana): Delete. value instanceof goog.html.SafeStyleSheet; }; /** * Converts SanitizedCss into SafeStyleSheet. * Note: SanitizedCss in Soy represents both SafeStyle and SafeStyleSheet in * Closure. It's about to be split so that SanitizedCss represents only * SafeStyleSheet. * @return {!goog.html.SafeStyleSheet} */ goog.soy.data.SanitizedCss.prototype.toSafeStyleSheet = function() { var value = this.toString(); // TODO(jakubvrana): Remove this check when there's a separate type for style // declaration. goog.asserts.assert( /[@{]|^\s*$/.test(value), 'value doesn\'t look like style sheet: ' + value); return goog.html.uncheckedconversions .safeStyleSheetFromStringKnownToSatisfyTypeContract( goog.string.Const.from( 'Soy SanitizedCss produces SafeStyleSheet-contract-compliant ' + 'value.'), value); }; //javascript/template/soy/soyutils_usegoog.js /* * Copyright 2008 Google Inc. * * 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. */ /** * @fileoverview * Utility functions and classes for Soy gencode * * <p> * This file contains utilities that should only be called by Soy-generated * JS code. Please do not use these functions directly from * your hand-written code. Their names all start with '$$', or exist within the * soydata.VERY_UNSAFE namespace. * * <p>TODO(lukes): ensure that the above pattern is actually followed * consistently. * * @author <NAME> * @author <NAME> * @author <NAME> * @author <NAME> */ goog.provide('soy'); goog.provide('soy.asserts'); goog.provide('soy.esc'); goog.provide('soydata'); goog.provide('soydata.SanitizedHtml'); goog.provide('soydata.VERY_UNSAFE'); goog.require('goog.array'); goog.require('goog.asserts'); goog.require('goog.debug'); goog.require('goog.format'); goog.require('goog.html.SafeHtml'); goog.require('goog.html.SafeScript'); goog.require('goog.html.SafeStyle'); goog.require('goog.html.SafeStyleSheet'); goog.require('goog.html.SafeUrl'); goog.require('goog.html.TrustedResourceUrl'); goog.require('goog.html.uncheckedconversions'); goog.require('goog.i18n.BidiFormatter'); goog.require('goog.i18n.bidi'); goog.require('goog.object'); goog.require('goog.soy.data.SanitizedContent'); goog.require('goog.soy.data.SanitizedContentKind'); goog.require('goog.soy.data.SanitizedCss'); goog.require('goog.soy.data.SanitizedHtml'); goog.require('goog.soy.data.SanitizedHtmlAttribute'); goog.require('goog.soy.data.SanitizedJs'); goog.require('goog.soy.data.SanitizedStyle'); goog.require('goog.soy.data.SanitizedTrustedResourceUri'); goog.require('goog.soy.data.SanitizedUri'); goog.require('goog.soy.data.UnsanitizedText'); goog.require('goog.string'); goog.require('goog.string.Const'); // ----------------------------------------------------------------------------- // soydata: Defines typed strings, e.g. an HTML string {@code "a<b>c"} is // semantically distinct from the plain text string {@code "a<b>c"} and smart // templates can take that distinction into account. /** * Checks whether a given value is of a given content kind. * * @param {*} value The value to be examined. * @param {goog.soy.data.SanitizedContentKind} contentKind The desired content * kind. * @return {boolean} Whether the given value is of the given kind. * @private */ soydata.isContentKind_ = function(value, contentKind) { // TODO(aharon): This function should really include the assert on // value.constructor that is currently sprinkled at most of the call sites. // Unfortunately, that would require a (debug-mode-only) switch statement. // TODO(aharon): Perhaps we should get rid of the contentKind property // altogether and only at the constructor. return value != null && value.contentKind === contentKind; }; /** * Returns a given value's contentDir property, constrained to a * goog.i18n.bidi.Dir value or null. Returns null if the value is null, * undefined, a primitive or does not have a contentDir property, or the * property's value is not 1 (for LTR), -1 (for RTL), or 0 (for neutral). * * @param {*} value The value whose contentDir property, if any, is to * be returned. * @return {?goog.i18n.bidi.Dir} The contentDir property. */ soydata.getContentDir = function(value) { if (value != null) { switch (value.contentDir) { case goog.i18n.bidi.Dir.LTR: return goog.i18n.bidi.Dir.LTR; case goog.i18n.bidi.Dir.RTL: return goog.i18n.bidi.Dir.RTL; case goog.i18n.bidi.Dir.NEUTRAL: return goog.i18n.bidi.Dir.NEUTRAL; } } return null; }; /** * This class is only a holder for `soydata.SanitizedHtml.from`. Do not * instantiate or extend it. Use `goog.soy.data.SanitizedHtml` instead. * * @constructor * @extends {goog.soy.data.SanitizedHtml} * @abstract */ soydata.SanitizedHtml = function() { soydata.SanitizedHtml.base(this, 'constructor'); // Throws an exception. }; goog.inherits(soydata.SanitizedHtml, goog.soy.data.SanitizedHtml); /** * Returns a SanitizedHtml object for a particular value. The content direction * is preserved. * * This HTML-escapes the value unless it is already SanitizedHtml or SafeHtml. * * @param {*} value The value to convert. If it is already a SanitizedHtml * object, it is left alone. * @return {!goog.soy.data.SanitizedHtml} A SanitizedHtml object derived from * the stringified value. It is escaped unless the input is SanitizedHtml or * SafeHtml. */ soydata.SanitizedHtml.from = function(value) { // The check is soydata.isContentKind_() inlined for performance. if (value != null && value.contentKind === goog.soy.data.SanitizedContentKind.HTML) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedHtml); return /** @type {!goog.soy.data.SanitizedHtml} */ (value); } if (value instanceof goog.html.SafeHtml) { return soydata.VERY_UNSAFE.ordainSanitizedHtml( goog.html.SafeHtml.unwrap(value), value.getDirection()); } return soydata.VERY_UNSAFE.ordainSanitizedHtml( soy.esc.$$escapeHtmlHelper(String(value)), soydata.getContentDir(value)); }; /** * Empty string, used as a type in Soy templates. * @enum {string} * @private */ soydata.$$EMPTY_STRING_ = { VALUE: '' }; /** * Creates a factory for SanitizedContent types. * * This is a hack so that the soydata.VERY_UNSAFE.ordainSanitized* can * instantiate Sanitized* classes, without making the Sanitized* constructors * publicly usable. Requiring all construction to use the VERY_UNSAFE names * helps callers and their reviewers easily tell that creating SanitizedContent * is not always safe and calls for careful review. * * @param {function(new: T)} ctor A constructor. * @return {!function(*, ?goog.i18n.bidi.Dir=): T} A factory that takes * content and an optional content direction and returns a new instance. If * the content direction is undefined, ctor.prototype.contentDir is used. * @template T * @private */ soydata.$$makeSanitizedContentFactory_ = function(ctor) { /** * @param {string} content * @constructor * @extends {goog.soy.data.SanitizedContent} */ function InstantiableCtor(content) { /** @override */ this.content = content; } InstantiableCtor.prototype = ctor.prototype; /** * Creates a ctor-type SanitizedContent instance. * * @param {*} content The content to put in the instance. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction. If * undefined, ctor.prototype.contentDir is used. * @return {!goog.soy.data.SanitizedContent} The new instance. It is actually * of type T above (ctor's type, a descendant of SanitizedContent), but * there is no way to express that here. */ function sanitizedContentFactory(content, opt_contentDir) { var result = new InstantiableCtor(String(content)); if (opt_contentDir !== undefined) { result.contentDir = opt_contentDir; } return result; } return sanitizedContentFactory; }; /** * Creates a factory for SanitizedContent types that should always have their * default directionality. * * This is a hack so that the soydata.VERY_UNSAFE.ordainSanitized* can * instantiate Sanitized* classes, without making the Sanitized* constructors * publicly usable. Requiring all construction to use the VERY_UNSAFE names * helps callers and their reviewers easily tell that creating SanitizedContent * is not always safe and calls for careful review. * * @param {function(new: T, string)} ctor A constructor. * @return {!function(*): T} A factory that takes content and returns a new * instance (with default directionality, i.e. ctor.prototype.contentDir). * @template T * @private */ soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_ = function(ctor) { /** * @param {string} content * @constructor * @extends {goog.soy.data.SanitizedContent} */ function InstantiableCtor(content) { /** @override */ this.content = content; } InstantiableCtor.prototype = ctor.prototype; /** * Creates a ctor-type SanitizedContent instance. * * @param {*} content The content to put in the instance. * @return {!goog.soy.data.SanitizedContent} The new instance. It is actually * of type T above (ctor's type, a descendant of SanitizedContent), but * there is no way to express that here. */ function sanitizedContentFactory(content) { var result = new InstantiableCtor(String(content)); return result; } return sanitizedContentFactory; }; // ----------------------------------------------------------------------------- // Sanitized content ordainers. Please use these with extreme caution (with the // exception of markUnsanitizedText). A good recommendation is to limit usage // of these to just a handful of files in your source tree where usages can be // carefully audited. /** * Protects a string from being used in an noAutoescaped context. * * This is useful for content where there is significant risk of accidental * unescaped usage in a Soy template. A great case is for user-controlled * data that has historically been a source of vulernabilities. * * @param {*} content Text to protect. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if * unknown and thus to be estimated when necessary. Default: null. * @return {!goog.soy.data.UnsanitizedText} A wrapper that is rejected by the * Soy noAutoescape print directive. */ soydata.markUnsanitizedText = function(content, opt_contentDir) { return new goog.soy.data.UnsanitizedText(content, opt_contentDir); }; /** * Takes a leap of faith that the provided content is "safe" HTML. * * @param {*} content A string of HTML that can safely be embedded in * a PCDATA context in your app. If you would be surprised to find that an * HTML sanitizer produced `s` (e.g. it runs code or fetches bad URLs) * and you wouldn't write a template that produces `s` on security or * privacy grounds, then don't pass `s` here. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if * unknown and thus to be estimated when necessary. Default: null. * @return {!goog.soy.data.SanitizedHtml} Sanitized content wrapper that * indicates to Soy not to escape when printed as HTML. */ soydata.VERY_UNSAFE.ordainSanitizedHtml = soydata.$$makeSanitizedContentFactory_(goog.soy.data.SanitizedHtml); /** * Takes a leap of faith that the provided content is "safe" (non-attacker- * controlled, XSS-free) Javascript. * * @param {*} content Javascript source that when evaluated does not * execute any attacker-controlled scripts. * @return {!goog.soy.data.SanitizedJs} Sanitized content wrapper that indicates * to Soy not to escape when printed as Javascript source. */ soydata.VERY_UNSAFE.ordainSanitizedJs = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedJs); /** * Takes a leap of faith that the provided content is "safe" to use as a URI * in a Soy template. * * This creates a Soy SanitizedContent object which indicates to Soy there is * no need to escape it when printed as a URI (e.g. in an href or src * attribute), such as if it's already been encoded or if it's a Javascript: * URI. * * @param {*} content A chunk of URI that the caller knows is safe to * emit in a template. * @return {!goog.soy.data.SanitizedUri} Sanitized content wrapper that * indicates to Soy not to escape or filter when printed in URI context. */ soydata.VERY_UNSAFE.ordainSanitizedUri = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedUri); /** * Takes a leap of faith that the provided content is "safe" to use as a * TrustedResourceUri in a Soy template. * * This creates a Soy SanitizedContent object which indicates to Soy there is * no need to filter it when printed as a TrustedResourceUri. * * @param {*} content A chunk of TrustedResourceUri such as that the caller * knows is safe to emit in a template. * @return {!goog.soy.data.SanitizedTrustedResourceUri} Sanitized content * wrapper that indicates to Soy not to escape or filter when printed in * TrustedResourceUri context. */ soydata.VERY_UNSAFE.ordainSanitizedTrustedResourceUri = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedTrustedResourceUri); /** * Takes a leap of faith that the provided content is "safe" to use as an * HTML attribute. * * @param {*} content An attribute name and value, such as * {@code dir="ltr"}. * @return {!goog.soy.data.SanitizedHtmlAttribute} Sanitized content wrapper * that indicates to Soy not to escape when printed as an HTML attribute. */ soydata.VERY_UNSAFE.ordainSanitizedHtmlAttribute = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedHtmlAttribute); /** * Takes a leap of faith that the provided content is "safe" to use as STYLE * in a style attribute. * * @param {*} content CSS, such as `color:#c3d9ff`. * @return {!goog.soy.data.SanitizedStyle} Sanitized style wrapper that * indicates to Soy there is no need to escape or filter when printed in CSS * context. */ soydata.VERY_UNSAFE.ordainSanitizedStyle = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedStyle); /** * Takes a leap of faith that the provided content is "safe" to use as CSS * in a style block. * * @param {*} content CSS, such as `color:#c3d9ff`. * @return {!goog.soy.data.SanitizedCss} Sanitized CSS wrapper that indicates to * Soy there is no need to escape or filter when printed in CSS context. */ soydata.VERY_UNSAFE.ordainSanitizedCss = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnly_( goog.soy.data.SanitizedCss); // ----------------------------------------------------------------------------- // Soy-generated utilities in the soy namespace. Contains implementations for // common soyfunctions (e.g. keys()) and escaping/print directives. /** * Whether the locale is right-to-left. * * @type {boolean} */ soy.$$IS_LOCALE_RTL = goog.i18n.bidi.IS_RTL; /** * Builds an augmented map. The returned map will contain mappings from both * the base map and the additional map. If the same key appears in both, then * the value from the additional map will be visible, while the value from the * base map will be hidden. The base map will be used, but not modified. * * @param {!Object} baseMap The original map to augment. * @param {!Object} additionalMap A map containing the additional mappings. * @return {!Object} An augmented map containing both the original and * additional mappings. */ soy.$$augmentMap = function(baseMap, additionalMap) { return soy.$$assignDefaults(soy.$$assignDefaults({}, additionalMap), baseMap); }; /** * Copies extra properties into an object if they do not already exist. The * destination object is mutated in the process. * * @param {!Object} obj The destination object to update. * @param {!Object} defaults An object with default properties to apply. * @return {!Object} The destination object for convenience. */ soy.$$assignDefaults = function(obj, defaults) { for (var key in defaults) { if (!(key in obj)) { obj[key] = defaults[key]; } } return obj; }; /** * Checks that the given map key is a string. * * <p>This is used to validate keys for legacy object map literals. * * @param {*} key Key to check. * @return {string} The given key. */ soy.$$checkLegacyObjectMapLiteralKey = function(key) { if ((typeof key) != 'string') { throw Error( 'Map literal\'s key expression must evaluate to string' + ' (encountered type "' + (typeof key) + '").'); } return key; }; /** * Gets the keys in a map as an array. There are no guarantees on the order. * @param {Object} map The map to get the keys of. * @return {!Array<string>} The array of keys in the given map. */ soy.$$getMapKeys = function(map) { var mapKeys = []; for (var key in map) { mapKeys.push(key); } return mapKeys; }; /** * Returns the argument if it is not null. * * @param {T} val The value to check * @return {T} val if is isn't null * @template T */ soy.$$checkNotNull = function(val) { if (val == null) { throw Error('unexpected null value'); } return val; }; /** * Parses the given string into a base 10 integer. Returns null if parse is * unsuccessful. * @param {string} str The string to parse * @return {?number} The string parsed as a base 10 integer, or null if * unsuccessful */ soy.$$parseInt = function(str) { var parsed = parseInt(str, 10); return isNaN(parsed) ? null : parsed; }; /** * Parses the given string into a float. Returns null if parse is unsuccessful. * @param {string} str The string to parse * @return {?number} The string parsed as a float, or null if unsuccessful. */ soy.$$parseFloat = function(str) { var parsed = parseFloat(str); return isNaN(parsed) ? null : parsed; }; /** * Gets a consistent unique id for the given delegate template name. Two calls * to this function will return the same id if and only if the input names are * the same. * * <p> Important: This function must always be called with a string constant. * * <p> If Closure Compiler is not being used, then this is just this identity * function. If Closure Compiler is being used, then each call to this function * will be replaced with a short string constant, which will be consistent per * input name. * * @param {string} delTemplateName The delegate template name for which to get a * consistent unique id. * @return {string} A unique id that is consistent per input name. * * @idGenerator {consistent} */ soy.$$getDelTemplateId = function(delTemplateName) { return delTemplateName; }; /** * Map from registered delegate template key to the priority of the * implementation. * @type {Object} * @private */ soy.$$DELEGATE_REGISTRY_PRIORITIES_ = {}; /** * Map from registered delegate template key to the implementation function. * @type {Object} * @private */ soy.$$DELEGATE_REGISTRY_FUNCTIONS_ = {}; /** * Registers a delegate implementation. If the same delegate template key (id * and variant) has been registered previously, then priority values are * compared and only the higher priority implementation is stored (if * priorities are equal, an error is thrown). * * @param {string} delTemplateId The delegate template id. * @param {string} delTemplateVariant The delegate template variant (can be * empty string). * @param {number} delPriority The implementation's priority value. * @param {Function} delFn The implementation function. */ soy.$$registerDelegateFn = function( delTemplateId, delTemplateVariant, delPriority, delFn) { var mapKey = 'key_' + delTemplateId + ':' + delTemplateVariant; var currPriority = soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey]; if (currPriority === undefined || delPriority > currPriority) { // Registering new or higher-priority function: replace registry entry. soy.$$DELEGATE_REGISTRY_PRIORITIES_[mapKey] = delPriority; soy.$$DELEGATE_REGISTRY_FUNCTIONS_[mapKey] = delFn; } else if (delPriority == currPriority) { // Registering same-priority function: error. throw Error( 'Encountered two active delegates with the same priority ("' + delTemplateId + ':' + delTemplateVariant + '").'); } else { // Registering lower-priority function: do nothing. } }; /** * Retrieves the (highest-priority) implementation that has been registered for * a given delegate template key (id and variant). If no implementation has * been registered for the key, then the fallback is the same id with empty * variant. If the fallback is also not registered, and allowsEmptyDefault is * true, then returns an implementation that is equivalent to an empty template * (i.e. rendered output would be empty string). * * @param {string} delTemplateId The delegate template id. * @param {string} delTemplateVariant The delegate template variant (can be * empty string). * @param {boolean} allowsEmptyDefault Whether to default to the empty template * function if there's no active implementation. * @return {Function} The retrieved implementation function. */ soy.$$getDelegateFn = function( delTemplateId, delTemplateVariant, allowsEmptyDefault) { var delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_[ 'key_' + delTemplateId + ':' + delTemplateVariant]; if (! delFn && delTemplateVariant != '') { // Fallback to empty variant. delFn = soy.$$DELEGATE_REGISTRY_FUNCTIONS_['key_' + delTemplateId + ':']; } if (delFn) { return delFn; } else if (allowsEmptyDefault) { return soy.$$EMPTY_TEMPLATE_FN_; } else { throw Error( 'Found no active impl for delegate call to "' + delTemplateId + (delTemplateVariant ? ':' + delTemplateVariant : '') + '" (and delcall does not set allowemptydefault="true").'); } }; /** * Private helper soy.$$getDelegateFn(). This is the empty template function * that is returned whenever there's no delegate implementation found. * * @param {Object<string, *>=} opt_data * @param {Object<string, *>=} opt_ijData * @param {Object<string, *>=} opt_ijData_deprecated TODO(b/36644846): remove * @return {string} * @private */ soy.$$EMPTY_TEMPLATE_FN_ = function( opt_data, opt_ijData, opt_ijData_deprecated) { return ''; }; // ----------------------------------------------------------------------------- // Internal sanitized content wrappers. /** * Creates a SanitizedContent factory for SanitizedContent types for internal * Soy let and param blocks. * * This is a hack within Soy so that SanitizedContent objects created via let * and param blocks will truth-test as false if they are empty string. * Tricking the Javascript runtime to treat empty SanitizedContent as falsey is * not possible, and changing the Soy compiler to wrap every boolean statement * for just this purpose is impractical. Instead, we just avoid wrapping empty * string as SanitizedContent, since it's a no-op for empty strings anyways. * * @param {function(new: T)} ctor A constructor. * @return {!function(*, ?goog.i18n.bidi.Dir=): (T|soydata.$$EMPTY_STRING_)} * A factory that takes content and an optional content direction and * returns a new instance, or an empty string. If the content direction is * undefined, ctor.prototype.contentDir is used. * @template T * @private */ soydata.$$makeSanitizedContentFactoryForInternalBlocks_ = function(ctor) { /** * @param {string} content * @constructor * @extends {goog.soy.data.SanitizedContent} */ function InstantiableCtor(content) { /** @override */ this.content = content; } InstantiableCtor.prototype = ctor.prototype; /** * Creates a ctor-type SanitizedContent instance. * * @param {*} content The content to put in the instance. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction. If * undefined, ctor.prototype.contentDir is used. * @return {!goog.soy.data.SanitizedContent|soydata.$$EMPTY_STRING_} The new * instance, or an empty string. A new instance is actually of type T * above (ctor's type, a descendant of SanitizedContent), but there's no * way to express that here. */ function sanitizedContentFactory(content, opt_contentDir) { var contentString = String(content); if (!contentString) { return soydata.$$EMPTY_STRING_.VALUE; } var result = new InstantiableCtor(contentString); if (opt_contentDir !== undefined) { result.contentDir = opt_contentDir; } return result; } return sanitizedContentFactory; }; /** * Creates a SanitizedContent factory for SanitizedContent types that should * always have their default directionality for internal Soy let and param * blocks. * * This is a hack within Soy so that SanitizedContent objects created via let * and param blocks will truth-test as false if they are empty string. * Tricking the Javascript runtime to treat empty SanitizedContent as falsey is * not possible, and changing the Soy compiler to wrap every boolean statement * for just this purpose is impractical. Instead, we just avoid wrapping empty * string as SanitizedContent, since it's a no-op for empty strings anyways. * * @param {function(new: T)} ctor A constructor. * @return {!function(*): (T|soydata.$$EMPTY_STRING_)} A * factory that takes content and returns a * new instance (with default directionality, i.e. * ctor.prototype.contentDir), or an empty string. * @template T * @private */ soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_ = function(ctor) { /** * @param {string} content * @constructor * @extends {goog.soy.data.SanitizedContent} */ function InstantiableCtor(content) { /** @override */ this.content = content; } InstantiableCtor.prototype = ctor.prototype; /** * Creates a ctor-type SanitizedContent instance. * * @param {*} content The content to put in the instance. * @return {!goog.soy.data.SanitizedContent|soydata.$$EMPTY_STRING_} The new * instance, or an empty string. A new instance is actually of type T * above (ctor's type, a descendant of SanitizedContent), but there's no * way to express that here. */ function sanitizedContentFactory(content) { var contentString = String(content); if (!contentString) { return soydata.$$EMPTY_STRING_.VALUE; } var result = new InstantiableCtor(contentString); return result; } return sanitizedContentFactory; }; /** * Creates kind="text" block contents (internal use only). * * @param {*} content Text. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if * unknown and thus to be estimated when necessary. Default: null. * @return {!goog.soy.data.UnsanitizedText|soydata.$$EMPTY_STRING_} Wrapped result. */ soydata.$$markUnsanitizedTextForInternalBlocks = function( content, opt_contentDir) { var contentString = String(content); if (!contentString) { return soydata.$$EMPTY_STRING_.VALUE; } return new goog.soy.data.UnsanitizedText(contentString, opt_contentDir); }; /** * Creates kind="html" block contents (internal use only). * * @param {*} content Text. * @param {?goog.i18n.bidi.Dir=} opt_contentDir The content direction; null if * unknown and thus to be estimated when necessary. Default: null. * @return {!goog.soy.data.SanitizedHtml|soydata.$$EMPTY_STRING_} Wrapped * result. */ soydata.VERY_UNSAFE.$$ordainSanitizedHtmlForInternalBlocks = soydata.$$makeSanitizedContentFactoryForInternalBlocks_( goog.soy.data.SanitizedHtml); /** * Creates kind="js" block contents (internal use only). * * @param {*} content Text. * @return {!goog.soy.data.SanitizedJs|soydata.$$EMPTY_STRING_} Wrapped result. */ soydata.VERY_UNSAFE.$$ordainSanitizedJsForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedJs); /** * Creates kind="trustedResourceUri" block contents (internal use only). * * @param {*} content Text. * @return {goog.soy.data.SanitizedTrustedResourceUri|soydata.$$EMPTY_STRING_} * Wrapped result. */ soydata.VERY_UNSAFE.$$ordainSanitizedTrustedResourceUriForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedTrustedResourceUri); /** * Creates kind="uri" block contents (internal use only). * * @param {*} content Text. * @return {goog.soy.data.SanitizedUri|soydata.$$EMPTY_STRING_} Wrapped result. */ soydata.VERY_UNSAFE.$$ordainSanitizedUriForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedUri); /** * Creates kind="attributes" block contents (internal use only). * * @param {*} content Text. * @return {goog.soy.data.SanitizedHtmlAttribute|soydata.$$EMPTY_STRING_} * Wrapped result. */ soydata.VERY_UNSAFE.$$ordainSanitizedAttributesForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedHtmlAttribute); /** * Creates kind="style" block contents (internal use only). * * @param {*} content Text. * @return {goog.soy.data.SanitizedStyle|soydata.$$EMPTY_STRING_} Wrapped * result. */ soydata.VERY_UNSAFE.$$ordainSanitizedStyleForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedStyle); /** * Creates kind="css" block contents (internal use only). * * @param {*} content Text. * @return {goog.soy.data.SanitizedCss|soydata.$$EMPTY_STRING_} Wrapped result. */ soydata.VERY_UNSAFE.$$ordainSanitizedCssForInternalBlocks = soydata.$$makeSanitizedContentFactoryWithDefaultDirOnlyForInternalBlocks_( goog.soy.data.SanitizedCss); // ----------------------------------------------------------------------------- // Escape/filter/normalize. /** * Returns a SanitizedHtml object for a particular value. The content direction * is preserved. * * This HTML-escapes the value unless it is already SanitizedHtml. Escapes * double quote '"' in addition to '&', '<', and '>' so that a string can be * included in an HTML tag attribute value within double quotes. * * @param {*} value The value to convert. If it is already a SanitizedHtml * object, it is left alone. * @return {!goog.soy.data.SanitizedHtml} An escaped version of value. */ soy.$$escapeHtml = function(value) { return soydata.SanitizedHtml.from(value); }; /** * Strips unsafe tags to convert a string of untrusted HTML into HTML that * is safe to embed. The content direction is preserved. * * @param {?} value The string-like value to be escaped. May not be a string, * but the value will be coerced to a string. * @param {Array<string>=} opt_safeTags Additional tag names to whitelist. * @return {!goog.soy.data.SanitizedHtml} A sanitized and normalized version of * value. */ soy.$$cleanHtml = function(value, opt_safeTags) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedHtml); return /** @type {!goog.soy.data.SanitizedHtml} */ (value); } var tagWhitelist; if (opt_safeTags) { tagWhitelist = goog.object.createSet(opt_safeTags); goog.object.extend(tagWhitelist, soy.esc.$$SAFE_TAG_WHITELIST_); } else { tagWhitelist = soy.esc.$$SAFE_TAG_WHITELIST_; } return soydata.VERY_UNSAFE.ordainSanitizedHtml( soy.$$stripHtmlTags(value, tagWhitelist), soydata.getContentDir(value)); }; /** * Escapes HTML, except preserves entities. * * Used mainly internally for escaping message strings in attribute and rcdata * context, where we explicitly want to preserve any existing entities. * * @param {*} value Value to normalize. * @return {string} A value safe to insert in HTML without any quotes or angle * brackets. */ soy.$$normalizeHtml = function(value) { return soy.esc.$$normalizeHtmlHelper(value); }; /** * Escapes HTML special characters in a string so that it can be embedded in * RCDATA. * <p> * Escapes HTML special characters so that the value will not prematurely end * the body of a tag like {@code <textarea>} or {@code <title>}. RCDATA tags * cannot contain other HTML entities, so it is not strictly necessary to escape * HTML special characters except when part of that text looks like an HTML * entity or like a close tag : {@code </textarea>}. * <p> * Will normalize known safe HTML to make sure that sanitized HTML (which could * contain an innocuous {@code </textarea>} don't prematurely end an RCDATA * element. * * @param {?} value The string-like value to be escaped. May not be a string, * but the value will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeHtmlRcdata = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedHtml); return soy.esc.$$normalizeHtmlHelper(value.getContent()); } return soy.esc.$$escapeHtmlHelper(value); }; /** * Matches any/only HTML5 void elements' start tags. * See http://www.w3.org/TR/html-markup/syntax.html#syntax-elements * @type {RegExp} * @private */ soy.$$HTML5_VOID_ELEMENTS_ = new RegExp( '^<(?:area|base|br|col|command|embed|hr|img|input' + '|keygen|link|meta|param|source|track|wbr)\\b'); /** * Removes HTML tags from a string of known safe HTML. * If opt_tagWhitelist is not specified or is empty, then * the result can be used as an attribute value. * * @param {*} value The HTML to be escaped. May not be a string, but the * value will be coerced to a string. * @param {Object<string, boolean>=} opt_tagWhitelist Has an own property whose * name is a lower-case tag name and whose value is `1` for * each element that is allowed in the output. * @return {string} A representation of value without disallowed tags, * HTML comments, or other non-text content. */ soy.$$stripHtmlTags = function(value, opt_tagWhitelist) { if (!opt_tagWhitelist) { // If we have no white-list, then use a fast track which elides all tags. return String(value).replace(soy.esc.$$HTML_TAG_REGEX_, '') // This is just paranoia since callers should normalize the result // anyway, but if they didn't, it would be necessary to ensure that // after the first replace non-tag uses of < do not recombine into // tags as in "<<foo>script>alert(1337)</<foo>script>". .replace(soy.esc.$$LT_REGEX_, '&lt;'); } // Escapes '[' so that we can use [123] below to mark places where tags // have been removed. var html = String(value).replace(/\[/g, '&#91;'); // Consider all uses of '<' and replace whitelisted tags with markers like // [1] which are indices into a list of approved tag names. // Replace all other uses of < and > with entities. var tags = []; var attrs = []; html = html.replace( soy.esc.$$HTML_TAG_REGEX_, function(tok, tagName) { if (tagName) { tagName = tagName.toLowerCase(); if (opt_tagWhitelist.hasOwnProperty(tagName) && opt_tagWhitelist[tagName]) { var isClose = tok.charAt(1) == '/'; var index = tags.length; var start = '</'; var attributes = ''; if (!isClose) { start = '<'; var match; while ((match = soy.esc.$$HTML_ATTRIBUTE_REGEX_.exec(tok))) { if (match[1] && match[1].toLowerCase() == 'dir') { var dir = match[2]; if (dir) { if (dir.charAt(0) == '\'' || dir.charAt(0) == '"') { dir = dir.substr(1, dir.length - 2); } dir = dir.toLowerCase(); if (dir == 'ltr' || dir == 'rtl' || dir == 'auto') { attributes = ' dir="' + dir + '"'; } } break; } } soy.esc.$$HTML_ATTRIBUTE_REGEX_.lastIndex = 0; } tags[index] = start + tagName + '>'; attrs[index] = attributes; return '[' + index + ']'; } } return ''; }); // Escape HTML special characters. Now there are no '<' in html that could // start a tag. html = soy.esc.$$normalizeHtmlHelper(html); var finalCloseTags = soy.$$balanceTags_(tags); // Now html contains no tags or less-than characters that could become // part of a tag via a replacement operation and tags only contains // approved tags. // Reinsert the white-listed tags. html = html.replace(/\[(\d+)\]/g, function(_, index) { if (attrs[index] && tags[index]) { return tags[index].substr(0, tags[index].length - 1) + attrs[index] + '>'; } return tags[index]; }); // Close any still open tags. // This prevents unclosed formatting elements like <ol> and <table> from // breaking the layout of containing HTML. return html + finalCloseTags; }; /** * Make sure that tag boundaries are not broken by Safe CSS when embedded in a * {@code <style>} element. * @param {string} css * @return {string} * @private */ soy.$$embedCssIntoHtml_ = function(css) { // Port of a method of the same name in // com.google.template.soy.shared.restricted.Sanitizers return css.replace(/<\//g, '<\\/').replace(/\]\]>/g, ']]\\>'); }; /** * Throw out any close tags that don't correspond to start tags. * If {@code <table>} is used for formatting, embedded HTML shouldn't be able * to use a mismatched {@code </table>} to break page layout. * * @param {Array<string>} tags Array of open/close tags (e.g. '<p>', '</p>') * that will be modified in place to be either an open tag, one or more close * tags concatenated, or the empty string. * @return {string} zero or more closed tags that close all elements that are * opened in tags but not closed. * @private */ soy.$$balanceTags_ = function(tags) { var open = []; for (var i = 0, n = tags.length; i < n; ++i) { var tag = tags[i]; if (tag.charAt(1) == '/') { var openTagIndex = goog.array.lastIndexOf(open, tag); if (openTagIndex < 0) { tags[i] = ''; // Drop close tag with no corresponding open tag. } else { tags[i] = open.slice(openTagIndex).reverse().join(''); open.length = openTagIndex; } } else if (tag == '<li>' && goog.array.lastIndexOf(open, '</ol>') < 0 && goog.array.lastIndexOf(open, '</ul>') < 0) { // Drop <li> if it isn't nested in a parent <ol> or <ul>. tags[i] = ''; } else if (!soy.$$HTML5_VOID_ELEMENTS_.test(tag)) { open.push('</' + tag.substring(1)); } } return open.reverse().join(''); }; /** * Escapes HTML special characters in an HTML attribute value. * * @param {?} value The HTML to be escaped. May not be a string, but the * value will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeHtmlAttribute = function(value) { // NOTE: We don't accept ATTRIBUTES here because ATTRIBUTES is actually not // the attribute value context, but instead k/v pairs. if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { // NOTE: After removing tags, we also escape quotes ("normalize") so that // the HTML can be embedded in attribute context. goog.asserts.assert(value.constructor === goog.soy.data.SanitizedHtml); return soy.esc.$$normalizeHtmlHelper( soy.$$stripHtmlTags(value.getContent())); } return soy.esc.$$escapeHtmlHelper(value); }; /** * Escapes HTML special characters in a string including space and other * characters that can end an unquoted HTML attribute value. * * @param {?} value The HTML to be escaped. May not be a string, but the * value will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeHtmlAttributeNospace = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedHtml); return soy.esc.$$normalizeHtmlNospaceHelper( soy.$$stripHtmlTags(value.getContent())); } return soy.esc.$$escapeHtmlNospaceHelper(value); }; /** * Filters out strings that cannot be a substring of a valid HTML attribute. * * Note the input is expected to be key=value pairs. * * @param {?} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} A valid HTML attribute name part or name/value pair. * {@code "zSoyz"} if the input is invalid. */ soy.$$filterHtmlAttributes = function(value) { // NOTE: Explicitly no support for SanitizedContentKind.HTML, since that is // meaningless in this context, which is generally *between* html attributes. if (soydata.isContentKind_( value, goog.soy.data.SanitizedContentKind.ATTRIBUTES)) { goog.asserts.assert( value.constructor === goog.soy.data.SanitizedHtmlAttribute); // Add a space at the end to ensure this won't get merged into following // attributes, unless the interpretation is unambiguous (ending with quotes // or a space). return value.getContent().replace(/([^"'\s])$/, '$1 '); } // TODO: Dynamically inserting attributes that aren't marked as trusted is // probably unnecessary. Any filtering done here will either be inadequate // for security or not flexible enough. Having clients use kind="attributes" // in parameters seems like a wiser idea. return soy.esc.$$filterHtmlAttributesHelper(value); }; /** * Filters out strings that cannot be a substring of a valid HTML element name. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} A valid HTML element name part. * {@code "zSoyz"} if the input is invalid. */ soy.$$filterHtmlElementName = function(value) { // NOTE: We don't accept any SanitizedContent here. HTML indicates valid // PCDATA, not tag names. A sloppy developer shouldn't be able to cause an // exploit: // ... {let userInput}script src=http://evil.com/evil.js{/let} ... // ... {param tagName kind="html"}{$userInput}{/param} ... // ... <{$tagName}>Hello World</{$tagName}> return soy.esc.$$filterHtmlElementNameHelper(value); }; /** * Escapes characters in the value to make it valid content for a JS string * literal. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeJsString = function(value) { return soy.esc.$$escapeJsStringHelper(value); }; /** * Encodes a value as a JavaScript literal. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} A JavaScript code representation of the input. */ soy.$$escapeJsValue = function(value) { // We surround values with spaces so that they can't be interpolated into // identifiers by accident. // We could use parentheses but those might be interpreted as a function call. if (value == null) { // Intentionally matches undefined. // Java returns null from maps where there is no corresponding key while // JS returns undefined. // We always output null for compatibility with Java which does not have a // distinct undefined value. return ' null '; } if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.JS)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedJs); return value.getContent(); } if (value instanceof goog.html.SafeScript) { return goog.html.SafeScript.unwrap(value); } switch (typeof value) { case 'boolean': case 'number': return ' ' + value + ' '; default: return "'" + soy.esc.$$escapeJsStringHelper(String(value)) + "'"; } }; /** * Escapes characters in the string to make it valid content for a JS regular * expression literal. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeJsRegex = function(value) { return soy.esc.$$escapeJsRegexHelper(value); }; /** * Matches all URI mark characters that conflict with HTML attribute delimiters * or that cannot appear in a CSS uri. * From <a href="http://www.w3.org/TR/CSS2/grammar.html">G.2: CSS grammar</a> * <pre> * url ([!#$%&*-~]|{nonascii}|{escape})* * </pre> * * @type {RegExp} * @private */ soy.$$problematicUriMarks_ = /['()]/g; /** * @param {string} ch A single character in {@link soy.$$problematicUriMarks_}. * @return {string} * @private */ soy.$$pctEncode_ = function(ch) { return '%' + ch.charCodeAt(0).toString(16); }; /** * Escapes a string so that it can be safely included in a URI. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeUri = function(value) { // NOTE: We don't check for SanitizedUri or SafeUri, because just because // something is already a valid complete URL doesn't mean we don't want to // encode it as a component. For example, it would be bad if // ?redirect={$url} didn't escape ampersands, because in that template, the // continue URL should be treated as a single unit. // Apostophes and parentheses are not matched by encodeURIComponent. // They are technically special in URIs, but only appear in the obsolete mark // production in Appendix D.2 of RFC 3986, so can be encoded without changing // semantics. var encoded = soy.esc.$$escapeUriHelper(value); soy.$$problematicUriMarks_.lastIndex = 0; if (soy.$$problematicUriMarks_.test(encoded)) { return encoded.replace(soy.$$problematicUriMarks_, soy.$$pctEncode_); } return encoded; }; /** * Removes rough edges from a URI by escaping any raw HTML/JS string delimiters. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$normalizeUri = function(value) { return soy.esc.$$normalizeUriHelper(value); }; /** * Vets a URI's protocol and removes rough edges from a URI by escaping * any raw HTML/JS string delimiters. * * @param {?} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$filterNormalizeUri = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.URI)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedUri); return soy.$$normalizeUri(value); } if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.TRUSTED_RESOURCE_URI)) { goog.asserts.assert( value.constructor === goog.soy.data.SanitizedTrustedResourceUri); return soy.$$normalizeUri(value); } if (value instanceof goog.html.SafeUrl) { return soy.$$normalizeUri(goog.html.SafeUrl.unwrap(value)); } if (value instanceof goog.html.TrustedResourceUrl) { return soy.$$normalizeUri(goog.html.TrustedResourceUrl.unwrap(value)); } return soy.esc.$$filterNormalizeUriHelper(value); }; /** * Vets a URI for usage as an image source. * * @param {?} value The value to filter. Might not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$filterNormalizeMediaUri = function(value) { // Image URIs are filtered strictly more loosely than other types of URIs. // TODO(shwetakarwa): Add tests for this in soyutils_test_helper while adding // tests for filterTrustedResourceUri. if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.URI)) { goog.asserts.assert(value.constructor === goog.soy.data.SanitizedUri); return soy.$$normalizeUri(value); } if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.TRUSTED_RESOURCE_URI)) { goog.asserts.assert( value.constructor === goog.soy.data.SanitizedTrustedResourceUri); return soy.$$normalizeUri(value); } if (value instanceof goog.html.SafeUrl) { return soy.$$normalizeUri(goog.html.SafeUrl.unwrap(value)); } if (value instanceof goog.html.TrustedResourceUrl) { return soy.$$normalizeUri(goog.html.TrustedResourceUrl.unwrap(value)); } return soy.esc.$$filterNormalizeMediaUriHelper(value); }; /** * Vets a URI for usage as a resource. Makes sure the input value is a compile * time constant or a TrustedResouce not in attacker's control. * * @param {?} value The value to filter. * @return {string} The value content. */ soy.$$filterTrustedResourceUri = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.TRUSTED_RESOURCE_URI)) { goog.asserts.assert( value.constructor === goog.soy.data.SanitizedTrustedResourceUri); return value.getContent(); } if (value instanceof goog.html.TrustedResourceUrl) { return goog.html.TrustedResourceUrl.unwrap(value); } goog.asserts.fail('Bad value `%s` for |filterTrustedResourceUri', [String(value)]); return 'about:invalid#zSoyz'; }; /** * For any resource string/variable which has * |blessStringAsTrustedResuorceUrlForLegacy directive return the value as is. * * @param {*} value The value to be blessed. Might not be a string * @return {*} value Return current value. */ soy.$$blessStringAsTrustedResourceUrlForLegacy = function(value) { return value; }; /** * Allows only data-protocol image URI's. * * @param {*} value The value to process. May not be a string, but the value * will be coerced to a string. * @return {!goog.soy.data.SanitizedUri} An escaped version of value. */ soy.$$filterImageDataUri = function(value) { // NOTE: Even if it's a SanitizedUri, we will still filter it. return soydata.VERY_UNSAFE.ordainSanitizedUri( soy.esc.$$filterImageDataUriHelper(value)); }; /** * Allows only sip URIs. * * @param {*} value The value to process. May not be a string, but the value * will be coerced to a string. * @return {!goog.soy.data.SanitizedUri} An escaped version of value. */ soy.$$filterSipUri = function(value) { // NOTE: Even if it's a SanitizedUri, we will still filter it. return soydata.VERY_UNSAFE.ordainSanitizedUri( soy.esc.$$filterSipUriHelper(value)); }; /** * Allows only tel URIs. * * @param {*} value The value to process. May not be a string, but the value * will be coerced to a string. * @return {!goog.soy.data.SanitizedUri} An escaped version of value. */ soy.$$filterTelUri = function(value) { // NOTE: Even if it's a SanitizedUri, we will still filter it. return soydata.VERY_UNSAFE.ordainSanitizedUri( soy.esc.$$filterTelUriHelper(value)); }; /** * Escapes a string so it can safely be included inside a quoted CSS string. * * @param {*} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} An escaped version of value. */ soy.$$escapeCssString = function(value) { return soy.esc.$$escapeCssStringHelper(value); }; /** * Encodes a value as a CSS identifier part, keyword, or quantity. * * @param {?} value The value to escape. May not be a string, but the value * will be coerced to a string. * @return {string} A safe CSS identifier part, keyword, or quanitity. */ soy.$$filterCssValue = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.CSS)) { goog.asserts.assertInstanceof(value, goog.soy.data.SanitizedCss); return soy.$$embedCssIntoHtml_(value.getContent()); } // Uses == to intentionally match null and undefined for Java compatibility. if (value == null) { return ''; } if (value instanceof goog.html.SafeStyle) { return soy.$$embedCssIntoHtml_(goog.html.SafeStyle.unwrap(value)); } // Note: SoyToJsSrcCompiler uses soy.$$filterCssValue both for the contents of // <style> (list of rules) and for the contents of style="" (one set of // declarations). We support SafeStyleSheet here to be used inside <style> but // it also wrongly allows it inside style="". We should instead change // SoyToJsSrcCompiler to use a different function inside <style>. if (value instanceof goog.html.SafeStyleSheet) { return soy.$$embedCssIntoHtml_(goog.html.SafeStyleSheet.unwrap(value)); } return soy.esc.$$filterCssValueHelper(value); }; /** * Sanity-checks noAutoescape input for explicitly tainted content. * * SanitizedContentKind.TEXT is used to explicitly mark input that was never * meant to be used unescaped. * * @param {?} value The value to filter. * @return {*} The value, that we dearly hope will not cause an attack. */ soy.$$filterNoAutoescape = function(value) { if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.TEXT)) { // Fail in development mode. goog.asserts.fail( 'Tainted SanitizedContentKind.TEXT for |noAutoescape: `%s`', [value.getContent()]); // Return innocuous data in production. return 'zSoyz'; } return value; }; // ----------------------------------------------------------------------------- // Basic directives/functions. /** * Converts \r\n, \r, and \n to <br>s * @param {*} value The string in which to convert newlines. * @return {string|!goog.soy.data.SanitizedHtml} A copy of `value` with * converted newlines. If `value` is SanitizedHtml, the return value * is also SanitizedHtml, of the same known directionality. */ soy.$$changeNewlineToBr = function(value) { var result = goog.string.newLineToBr(String(value), false); if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { return soydata.VERY_UNSAFE.ordainSanitizedHtml( result, soydata.getContentDir(value)); } return result; }; /** * Inserts word breaks ('wbr' tags) into a HTML string at a given interval. The * counter is reset if a space is encountered. Word breaks aren't inserted into * HTML tags or entities. Entites count towards the character count; HTML tags * do not. * * @param {*} value The HTML string to insert word breaks into. Can be other * types, but the value will be coerced to a string. * @param {number} maxCharsBetweenWordBreaks Maximum number of non-space * characters to allow before adding a word break. * @return {string|!goog.soy.data.SanitizedHtml} The string including word * breaks. If `value` is SanitizedHtml, the return value * is also SanitizedHtml, of the same known directionality. * @deprecated The |insertWordBreaks directive is deprecated. * Prefer wrapping with CSS white-space: break-word. */ soy.$$insertWordBreaks = function(value, maxCharsBetweenWordBreaks) { var result = goog.format.insertWordBreaks( String(value), maxCharsBetweenWordBreaks); if (soydata.isContentKind_(value, goog.soy.data.SanitizedContentKind.HTML)) { return soydata.VERY_UNSAFE.ordainSanitizedHtml( result, soydata.getContentDir(value)); } return result; }; /** * Truncates a string to a given max length (if it's currently longer), * optionally adding ellipsis at the end. * * @param {*} str The string to truncate. Can be other types, but the value will * be coerced to a string. * @param {number} maxLen The maximum length of the string after truncation * (including ellipsis, if applicable). * @param {boolean} doAddEllipsis Whether to add ellipsis if the string needs * truncation. * @return {string} The string after truncation. */ soy.$$truncate = function(str, maxLen, doAddEllipsis) { str = String(str); if (str.length <= maxLen) { return str; // no need to truncate } // If doAddEllipsis, either reduce maxLen to compensate, or else if maxLen is // too small, just turn off doAddEllipsis. if (doAddEllipsis) { if (maxLen > 3) { maxLen -= 3; } else { doAddEllipsis = false; } } // Make sure truncating at maxLen doesn't cut up a unicode surrogate pair. if (soy.$$isHighSurrogate_(str.charCodeAt(maxLen - 1)) && soy.$$isLowSurrogate_(str.charCodeAt(maxLen))) { maxLen -= 1; } // Truncate. str = str.substring(0, maxLen); // Add ellipsis. if (doAddEllipsis) { str += '...'; } return str; }; /** * Private helper for $$truncate() to check whether a char is a high surrogate. * @param {number} cc The codepoint to check. * @return {boolean} Whether the given codepoint is a unicode high surrogate. * @private */ soy.$$isHighSurrogate_ = function(cc) { return 0xD800 <= cc && cc <= 0xDBFF; }; /** * Private helper for $$truncate() to check whether a char is a low surrogate. * @param {number} cc The codepoint to check. * @return {boolean} Whether the given codepoint is a unicode low surrogate. * @private */ soy.$$isLowSurrogate_ = function(cc) { return 0xDC00 <= cc && cc <= 0xDFFF; }; // ----------------------------------------------------------------------------- // Bidi directives/functions. /** * Cache of bidi formatter by context directionality, so we don't keep on * creating new objects. * @type {!Object<!goog.i18n.BidiFormatter>} * @private */ soy.$$bidiFormatterCache_ = {}; /** * Returns cached bidi formatter for bidiGlobalDir, or creates a new one. * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1 * if rtl, 0 if unknown. * @return {!goog.i18n.BidiFormatter} A formatter for bidiGlobalDir. * @private */ soy.$$getBidiFormatterInstance_ = function(bidiGlobalDir) { return soy.$$bidiFormatterCache_[bidiGlobalDir] || (soy.$$bidiFormatterCache_[bidiGlobalDir] = new goog.i18n.BidiFormatter(bidiGlobalDir)); }; /** * Estimate the overall directionality of text. If opt_isHtml, makes sure to * ignore the LTR nature of the mark-up and escapes in text, making the logic * suitable for HTML and HTML-escaped text. * If text has a goog.i18n.bidi.Dir-valued contentDir, this is used instead of * estimating the directionality. * * @param {*} text The content whose directionality is to be estimated. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped. * Default: false. * @return {number} 1 if text is LTR, -1 if it is RTL, and 0 if it is neutral. */ soy.$$bidiTextDir = function(text, opt_isHtml) { var contentDir = soydata.getContentDir(text); if (contentDir != null) { return contentDir; } var isHtml = opt_isHtml || soydata.isContentKind_(text, goog.soy.data.SanitizedContentKind.HTML); return goog.i18n.bidi.estimateDirection(text + '', isHtml); }; /** * Returns 'dir="ltr"' or 'dir="rtl"', depending on text's estimated * directionality, if it is not the same as bidiGlobalDir. * Otherwise, returns the empty string. * If opt_isHtml, makes sure to ignore the LTR nature of the mark-up and escapes * in text, making the logic suitable for HTML and HTML-escaped text. * If text has a goog.i18n.bidi.Dir-valued contentDir, this is used instead of * estimating the directionality. * * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1 * if rtl, 0 if unknown. * @param {*} text The content whose directionality is to be estimated. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped. * Default: false. * @return {!goog.soy.data.SanitizedHtmlAttribute} 'dir="rtl"' for RTL text in * non-RTL context; 'dir="ltr"' for LTR text in non-LTR context; * else, the empty string. */ soy.$$bidiDirAttr = function(bidiGlobalDir, text, opt_isHtml) { var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir); var contentDir = soydata.getContentDir(text); if (contentDir == null) { var isHtml = opt_isHtml || soydata.isContentKind_(text, goog.soy.data.SanitizedContentKind.HTML); contentDir = goog.i18n.bidi.estimateDirection(text + '', isHtml); } return soydata.VERY_UNSAFE.ordainSanitizedHtmlAttribute( formatter.knownDirAttr(contentDir)); }; /** * Returns a Unicode BiDi mark matching bidiGlobalDir (LRM or RLM) if the * directionality or the exit directionality of text are opposite to * bidiGlobalDir. Otherwise returns the empty string. * If opt_isHtml, makes sure to ignore the LTR nature of the mark-up and escapes * in text, making the logic suitable for HTML and HTML-escaped text. * If text has a goog.i18n.bidi.Dir-valued contentDir, this is used instead of * estimating the directionality. * * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1 * if rtl, 0 if unknown. * @param {*} text The content whose directionality is to be estimated. * @param {boolean=} opt_isHtml Whether text is HTML/HTML-escaped. * Default: false. * @return {string} A Unicode bidi mark matching bidiGlobalDir, or the empty * string when text's overall and exit directionalities both match * bidiGlobalDir, or bidiGlobalDir is 0 (unknown). */ soy.$$bidiMarkAfter = function(bidiGlobalDir, text, opt_isHtml) { var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir); var isHtml = opt_isHtml || soydata.isContentKind_(text, goog.soy.data.SanitizedContentKind.HTML); return formatter.markAfterKnownDir(soydata.getContentDir(text), text + '', isHtml); }; /** * Returns text wrapped in a <span dir="ltr|rtl"> according to its * directionality - but only if that is neither neutral nor the same as the * global context. Otherwise, returns text unchanged. * Always treats text as HTML/HTML-escaped, i.e. ignores mark-up and escapes * when estimating text's directionality. * If text has a goog.i18n.bidi.Dir-valued contentDir, this is used instead of * estimating the directionality. * * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1 * if rtl, 0 if unknown. * @param {*} text The string to be wrapped. Can be other types, but the value * will be coerced to a string. * @return {!goog.soy.data.SanitizedContent|string} The wrapped text. */ soy.$$bidiSpanWrap = function(bidiGlobalDir, text) { var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir); // We always treat the value as HTML, because span-wrapping is only useful // when its output will be treated as HTML (without escaping), and because // |bidiSpanWrap is not itself specified to do HTML escaping in Soy. (Both // explicit and automatic HTML escaping, if any, is done before calling // |bidiSpanWrap because the BidiSpanWrapDirective Java class implements // SanitizedContentOperator, but this does not mean that the input has to be // HTML SanitizedContent. In legacy usage, a string that is not // SanitizedContent is often printed in an autoescape="false" template or by // a print with a |noAutoescape, in which case our input is just SoyData.) If // the output will be treated as HTML, the input had better be safe // HTML/HTML-escaped (even if it isn't HTML SanitizedData), or we have an XSS // opportunity and a much bigger problem than bidi garbling. var html = goog.html.uncheckedconversions. safeHtmlFromStringKnownToSatisfyTypeContract( goog.string.Const.from( 'Soy |bidiSpanWrap is applied on an autoescaped text.'), String(text)); var wrappedHtml = formatter.spanWrapSafeHtmlWithKnownDir( soydata.getContentDir(text), html); // Like other directives whose Java class implements SanitizedContentOperator, // |bidiSpanWrap is called after the escaping (if any) has already been done, // and thus there is no need for it to produce actual SanitizedContent. return goog.html.SafeHtml.unwrap(wrappedHtml); }; /** * Returns text wrapped in Unicode BiDi formatting characters according to its * directionality, i.e. either LRE or RLE at the beginning and PDF at the end - * but only if text's directionality is neither neutral nor the same as the * global context. Otherwise, returns text unchanged. * Only treats SanitizedHtml as HTML/HTML-escaped, i.e. ignores mark-up * and escapes when estimating text's directionality. * If text has a goog.i18n.bidi.Dir-valued contentDir, this is used instead of * estimating the directionality. * * @param {number} bidiGlobalDir The global directionality context: 1 if ltr, -1 * if rtl, 0 if unknown. * @param {*} text The string to be wrapped. Can be other types, but the value * will be coerced to a string. * @return {!goog.soy.data.SanitizedContent|string} The wrapped string. */ soy.$$bidiUnicodeWrap = function(bidiGlobalDir, text) { var formatter = soy.$$getBidiFormatterInstance_(bidiGlobalDir); // We treat the value as HTML if and only if it says it's HTML, even though in // legacy usage, we sometimes have an HTML string (not SanitizedContent) that // is passed to an autoescape="false" template or a {print $foo|noAutoescape}, // with the output going into an HTML context without escaping. We simply have // no way of knowing if this is what is happening when we get // non-SanitizedContent input, and most of the time it isn't. var isHtml = soydata.isContentKind_(text, goog.soy.data.SanitizedContentKind.HTML); var wrappedText = formatter.unicodeWrapWithKnownDir( soydata.getContentDir(text), text + '', isHtml); // Bidi-wrapping a value converts it to the context directionality. Since it // does not cost us anything, we will indicate this known direction in the // output SanitizedContent, even though the intended consumer of that // information - a bidi wrapping directive - has already been run. var wrappedTextDir = formatter.getContextDir(); // Unicode-wrapping UnsanitizedText gives UnsanitizedText. // Unicode-wrapping safe HTML or JS string data gives valid, safe HTML or JS // string data. // ATTENTION: Do these need to be ...ForInternalBlocks()? if (soydata.isContentKind_(text, goog.soy.data.SanitizedContentKind.TEXT)) { return new goog.soy.data.UnsanitizedText(wrappedText, wrappedTextDir); } if (isHtml) { return soydata.VERY_UNSAFE.ordainSanitizedHtml(wrappedText, wrappedTextDir); } // Unicode-wrapping does not conform to the syntax of the other types of // content. For lack of anything better to do, we we do not declare a content // kind at all by falling through to the non-SanitizedContent case below. // TODO(aharon): Consider throwing a runtime error on receipt of // SanitizedContent other than TEXT, HTML, or JS_STR_CHARS. // The input was not SanitizedContent, so our output isn't SanitizedContent // either. return wrappedText; }; // ----------------------------------------------------------------------------- // Assertion methods used by runtime. /** * Checks if the type assertion is true if goog.asserts.ENABLE_ASSERTS is * true. Report errors on runtime types if goog.DEBUG is true. * @param {boolean} condition The type check condition. * @param {string} paramName The Soy name of the parameter. * @param {?} param The JS object for the parameter. * @param {!string} jsDocTypeStr SoyDoc type str. * @return {?} the param value * @throws {goog.asserts.AssertionError} When the condition evaluates to false. */ soy.asserts.assertType = function(condition, paramName, param, jsDocTypeStr) { if (goog.asserts.ENABLE_ASSERTS && !condition) { var msg = 'expected param ' + paramName + ' of type ' + jsDocTypeStr + (goog.DEBUG ? (', but got ' + goog.debug.runtimeType(param)) : '') + '.'; goog.asserts.fail(msg); } return param; }; // ----------------------------------------------------------------------------- // Used for inspecting Soy template information from rendered pages. /** * Whether we should generate additional HTML comments. * @type {boolean} */ soy.$$debugSoyTemplateInfo = false; if (goog.DEBUG) { /** * Configures whether we should generate additional HTML comments for * inspecting Soy template information from rendered pages. * @param {boolean} debugSoyTemplateInfo */ soy.setDebugSoyTemplateInfo = function(debugSoyTemplateInfo) { soy.$$debugSoyTemplateInfo = debugSoyTemplateInfo; }; } // ----------------------------------------------------------------------------- // Generated code. // START GENERATED CODE FOR ESCAPERS. /** * @type {function (*) : string} */ soy.esc.$$escapeHtmlHelper = function(v) { return goog.string.htmlEscape(String(v)); }; /** * @type {function (*) : string} */ soy.esc.$$escapeUriHelper = function(v) { return goog.string.urlEncode(String(v)); }; /** * Maps characters to the escaped versions for the named escape directives. * @private {!Object<string, string>} */ soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_ = { '\x00': '\x26#0;', '\x09': '\x26#9;', '\x0a': '\x26#10;', '\x0b': '\x26#11;', '\x0c': '\x26#12;', '\x0d': '\x26#13;', ' ': '\x26#32;', '\x22': '\x26quot;', '\x26': '\x26amp;', '\x27': '\x26#39;', '-': '\x26#45;', '\/': '\x26#47;', '\x3c': '\x26lt;', '\x3d': '\x26#61;', '\x3e': '\x26gt;', '`': '\x26#96;', '\x85': '\x26#133;', '\xa0': '\x26#160;', '\u2028': '\x26#8232;', '\u2029': '\x26#8233;' }; /** * A function that can be used with String.replace. * @param {string} ch A single character matched by a compatible matcher. * @return {string} A token in the output language. * @private */ soy.esc.$$REPLACER_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_ = function(ch) { return soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_[ch]; }; /** * Maps characters to the escaped versions for the named escape directives. * @private {!Object<string, string>} */ soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_ = { '\x00': '\\x00', '\x08': '\\x08', '\x09': '\\t', '\x0a': '\\n', '\x0b': '\\x0b', '\x0c': '\\f', '\x0d': '\\r', '\x22': '\\x22', '$': '\\x24', '\x26': '\\x26', '\x27': '\\x27', '(': '\\x28', ')': '\\x29', '*': '\\x2a', '+': '\\x2b', ',': '\\x2c', '-': '\\x2d', '.': '\\x2e', '\/': '\\\/', ':': '\\x3a', '\x3c': '\\x3c', '\x3d': '\\x3d', '\x3e': '\\x3e', '?': '\\x3f', '\x5b': '\\x5b', '\\': '\\\\', '\x5d': '\\x5d', '^': '\\x5e', '\x7b': '\\x7b', '|': '\\x7c', '\x7d': '\\x7d', '\x85': '\\x85', '\u2028': '\\u2028', '\u2029': '\\u2029' }; /** * A function that can be used with String.replace. * @param {string} ch A single character matched by a compatible matcher. * @return {string} A token in the output language. * @private */ soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_ = function(ch) { return soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_[ch]; }; /** * Maps characters to the escaped versions for the named escape directives. * @private {!Object<string, string>} */ soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_CSS_STRING_ = { '\x00': '\\0 ', '\x08': '\\8 ', '\x09': '\\9 ', '\x0a': '\\a ', '\x0b': '\\b ', '\x0c': '\\c ', '\x0d': '\\d ', '\x22': '\\22 ', '\x26': '\\26 ', '\x27': '\\27 ', '(': '\\28 ', ')': '\\29 ', '*': '\\2a ', '\/': '\\2f ', ':': '\\3a ', ';': '\\3b ', '\x3c': '\\3c ', '\x3d': '\\3d ', '\x3e': '\\3e ', '@': '\\40 ', '\\': '\\5c ', '\x7b': '\\7b ', '\x7d': '\\7d ', '\x85': '\\85 ', '\xa0': '\\a0 ', '\u2028': '\\2028 ', '\u2029': '\\2029 ' }; /** * A function that can be used with String.replace. * @param {string} ch A single character matched by a compatible matcher. * @return {string} A token in the output language. * @private */ soy.esc.$$REPLACER_FOR_ESCAPE_CSS_STRING_ = function(ch) { return soy.esc.$$ESCAPE_MAP_FOR_ESCAPE_CSS_STRING_[ch]; }; /** * Maps characters to the escaped versions for the named escape directives. * @private {!Object<string, string>} */ soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_ = { '\x00': '%00', '\x01': '%01', '\x02': '%02', '\x03': '%03', '\x04': '%04', '\x05': '%05', '\x06': '%06', '\x07': '%07', '\x08': '%08', '\x09': '%09', '\x0a': '%0A', '\x0b': '%0B', '\x0c': '%0C', '\x0d': '%0D', '\x0e': '%0E', '\x0f': '%0F', '\x10': '%10', '\x11': '%11', '\x12': '%12', '\x13': '%13', '\x14': '%14', '\x15': '%15', '\x16': '%16', '\x17': '%17', '\x18': '%18', '\x19': '%19', '\x1a': '%1A', '\x1b': '%1B', '\x1c': '%1C', '\x1d': '%1D', '\x1e': '%1E', '\x1f': '%1F', ' ': '%20', '\x22': '%22', '\x27': '%27', '(': '%28', ')': '%29', '\x3c': '%3C', '\x3e': '%3E', '\\': '%5C', '\x7b': '%7B', '\x7d': '%7D', '\x7f': '%7F', '\x85': '%C2%85', '\xa0': '%C2%A0', '\u2028': '%E2%80%A8', '\u2029': '%E2%80%A9', '\uff01': '%EF%BC%81', '\uff03': '%EF%BC%83', '\uff04': '%EF%BC%84', '\uff06': '%EF%BC%86', '\uff07': '%EF%BC%87', '\uff08': '%EF%BC%88', '\uff09': '%EF%BC%89', '\uff0a': '%EF%BC%8A', '\uff0b': '%EF%BC%8B', '\uff0c': '%EF%BC%8C', '\uff0f': '%EF%BC%8F', '\uff1a': '%EF%BC%9A', '\uff1b': '%EF%BC%9B', '\uff1d': '%EF%BC%9D', '\uff1f': '%EF%BC%9F', '\uff20': '%EF%BC%A0', '\uff3b': '%EF%BC%BB', '\uff3d': '%EF%BC%BD' }; /** * A function that can be used with String.replace. * @param {string} ch A single character matched by a compatible matcher. * @return {string} A token in the output language. * @private */ soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_ = function(ch) { return soy.esc.$$ESCAPE_MAP_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_[ch]; }; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_ = /[\x00\x22\x27\x3c\x3e]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_ESCAPE_HTML_NOSPACE_ = /[\x00\x09-\x0d \x22\x26\x27\x2d\/\x3c-\x3e`\x85\xa0\u2028\u2029]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_NOSPACE_ = /[\x00\x09-\x0d \x22\x27\x2d\/\x3c-\x3e`\x85\xa0\u2028\u2029]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_ESCAPE_JS_STRING_ = /[\x00\x08-\x0d\x22\x26\x27\/\x3c-\x3e\x5b-\x5d\x7b\x7d\x85\u2028\u2029]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_ESCAPE_JS_REGEX_ = /[\x00\x08-\x0d\x22\x24\x26-\/\x3a\x3c-\x3f\x5b-\x5e\x7b-\x7d\x85\u2028\u2029]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_ESCAPE_CSS_STRING_ = /[\x00\x08-\x0d\x22\x26-\x2a\/\x3a-\x3e@\\\x7b\x7d\x85\xa0\u2028\u2029]/g; /** * Matches characters that need to be escaped for the named directives. * @private {!RegExp} */ soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_ = /[\x00- \x22\x27-\x29\x3c\x3e\\\x7b\x7d\x7f\x85\xa0\u2028\u2029\uff01\uff03\uff04\uff06-\uff0c\uff0f\uff1a\uff1b\uff1d\uff1f\uff20\uff3b\uff3d]/g; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_ = /^(?!-*(?:expression|(?:moz-)?binding))(?!\s+)(?:[.#]?-?(?:[_a-z0-9-]+)(?:-[_a-z0-9-]+)*-?|(?:rgb|hsl)a?\([0-9.%,\u0020]+\)|-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[a-z]{1,2}|%)?|!important|\s+)*$/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_URI_ = /^(?![^#?]*\/(?:\.|%2E){2}(?:[\/?#]|$))(?:(?:https?|mailto):|[^&:\/?#]*(?:[\/?#]|$))/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_MEDIA_URI_ = /^[^&:\/?#]*(?:[\/?#]|$)|^https?:|^data:image\/[a-z0-9+]+;base64,[a-z0-9+\/]+=*$|^blob:/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_IMAGE_DATA_URI_ = /^data:image\/(?:bmp|gif|jpe?g|png|tiff|webp);base64,[a-z0-9+\/]+=*$/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_SIP_URI_ = /^sip:[0-9a-z;=\-+._!~*'\u0020\/():&$#?@,]+$/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_TEL_URI_ = /^tel:[0-9a-z;=\-+._!~*'\u0020\/():&$#?@,]+$/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_ = /^(?!on|src|(?:style|action|archive|background|cite|classid|codebase|data|dsync|href|longdesc|usemap)\s*$)(?:[a-z0-9_$:-]*)$/i; /** * A pattern that vets values produced by the named directives. * @private {!RegExp} */ soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_ = /^(?!link|script|style|title|textarea|xmp|no)[a-z0-9_$:-]*$/i; /** * A helper for the Soy directive |normalizeHtml * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$normalizeHtmlHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_, soy.esc.$$REPLACER_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_); }; /** * A helper for the Soy directive |escapeHtmlNospace * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$escapeHtmlNospaceHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_ESCAPE_HTML_NOSPACE_, soy.esc.$$REPLACER_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_); }; /** * A helper for the Soy directive |normalizeHtmlNospace * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$normalizeHtmlNospaceHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_NORMALIZE_HTML_NOSPACE_, soy.esc.$$REPLACER_FOR_NORMALIZE_HTML__AND__ESCAPE_HTML_NOSPACE__AND__NORMALIZE_HTML_NOSPACE_); }; /** * A helper for the Soy directive |escapeJsString * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$escapeJsStringHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_ESCAPE_JS_STRING_, soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_); }; /** * A helper for the Soy directive |escapeJsRegex * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$escapeJsRegexHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_ESCAPE_JS_REGEX_, soy.esc.$$REPLACER_FOR_ESCAPE_JS_STRING__AND__ESCAPE_JS_REGEX_); }; /** * A helper for the Soy directive |escapeCssString * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$escapeCssStringHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_ESCAPE_CSS_STRING_, soy.esc.$$REPLACER_FOR_ESCAPE_CSS_STRING_); }; /** * A helper for the Soy directive |filterCssValue * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterCssValueHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_CSS_VALUE_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterCssValue', [str]); return 'zSoyz'; } return str; }; /** * A helper for the Soy directive |normalizeUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$normalizeUriHelper = function(value) { var str = String(value); return str.replace( soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_, soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_); }; /** * A helper for the Soy directive |filterNormalizeUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterNormalizeUriHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_URI_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterNormalizeUri', [str]); return 'about:invalid#zSoyz'; } return str.replace( soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_, soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_); }; /** * A helper for the Soy directive |filterNormalizeMediaUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterNormalizeMediaUriHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_NORMALIZE_MEDIA_URI_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterNormalizeMediaUri', [str]); return 'about:invalid#zSoyz'; } return str.replace( soy.esc.$$MATCHER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_, soy.esc.$$REPLACER_FOR_NORMALIZE_URI__AND__FILTER_NORMALIZE_URI__AND__FILTER_NORMALIZE_MEDIA_URI_); }; /** * A helper for the Soy directive |filterImageDataUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterImageDataUriHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_IMAGE_DATA_URI_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterImageDataUri', [str]); return 'data:image/gif;base64,zSoyz'; } return str; }; /** * A helper for the Soy directive |filterSipUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterSipUriHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_SIP_URI_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterSipUri', [str]); return 'about:invalid#zSoyz'; } return str; }; /** * A helper for the Soy directive |filterTelUri * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterTelUriHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_TEL_URI_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterTelUri', [str]); return 'about:invalid#zSoyz'; } return str; }; /** * A helper for the Soy directive |filterHtmlAttributes * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterHtmlAttributesHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_HTML_ATTRIBUTES_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterHtmlAttributes', [str]); return 'zSoyz'; } return str; }; /** * A helper for the Soy directive |filterHtmlElementName * @param {*} value Can be of any type but will be coerced to a string. * @return {string} The escaped text. */ soy.esc.$$filterHtmlElementNameHelper = function(value) { var str = String(value); if (!soy.esc.$$FILTER_FOR_FILTER_HTML_ELEMENT_NAME_.test(str)) { goog.asserts.fail('Bad value `%s` for |filterHtmlElementName', [str]); return 'zSoyz'; } return str; }; /** * Matches all tags, HTML comments, and DOCTYPEs in tag soup HTML. * By removing these, and replacing any '<' or '>' characters with * entities we guarantee that the result can be embedded into a * an attribute without introducing a tag boundary. * * @private {!RegExp} */ soy.esc.$$HTML_TAG_REGEX_ = /<(?:!|\/?([a-zA-Z][a-zA-Z0-9:\-]*))(?:[^>'"]|"[^"]*"|'[^']*')*>/g; /** * Matches all occurrences of '<'. * * @private {!RegExp} */ soy.esc.$$LT_REGEX_ = /</g; /** * Maps lower-case names of innocuous tags to true. * * @private {!Object<string, boolean>} */ soy.esc.$$SAFE_TAG_WHITELIST_ = {'b': true, 'br': true, 'em': true, 'i': true, 's': true, 'sub': true, 'sup': true, 'u': true}; /** * Pattern for matching attribute name and value, where value is single-quoted * or double-quoted. * See http://www.w3.org/TR/2011/WD-html5-20110525/syntax.html#attributes-0 * * @private {!RegExp} */ soy.esc.$$HTML_ATTRIBUTE_REGEX_ = /([a-zA-Z][a-zA-Z0-9:\-]*)[\t\n\r\u0020]*=[\t\n\r\u0020]*("[^"]*"|'[^']*')/g; // END GENERATED CODE
# # Process the command line # version=undefined for abc do case $1 in -v) version=$2 shift 2 ;; esac done if [ $version = undefined ] then echo "Usage: -v <version>" exit fi version2=`echo $version | tr "." "_"` # # Create the distribution. # tar zxf visit$version.tar.gz cd visit$version mkdir build cd build /home/visit/third-party/cmake/3.14.7/*/bin/cmake \ -DCMAKE_BUILD_TYPE:STRING=Release -DVISIT_INSTALL_THIRD_PARTY:BOOL=ON \ -DVISIT_ENABLE_XDB:BOOL=ON -DVISIT_PARADIS:BOOL=ON \ -DVISIT_CONFIG_SITE="/home/visit/visit-config.cmake" ../src make manuals make -j 4 package mv visit$version2.linux-x86_64.tar.gz ../.. # # Test the distribution. # cd ../.. cp visit$version/src/tools/dev/scripts/visit-install . ./visit-install -c none $version linux-x86_64 visit visit/bin/visit -cli -nowin -s test_visit.py
package com.yin.springboot.mybatis.server; import java.util.List; import com.yin.springboot.mybatis.domain.SmsCouponProductRelation; public interface SmsCouponProductRelationService{ int deleteByPrimaryKey(Long id); int insert(SmsCouponProductRelation record); int insertOrUpdate(SmsCouponProductRelation record); int insertOrUpdateSelective(SmsCouponProductRelation record); int insertSelective(SmsCouponProductRelation record); SmsCouponProductRelation selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(SmsCouponProductRelation record); int updateByPrimaryKey(SmsCouponProductRelation record); int updateBatch(List<SmsCouponProductRelation> list); int batchInsert(List<SmsCouponProductRelation> list); }
import { PropTypes } from 'react-desc'; export var a11yTitlePropType = PropTypes.string.description('Custom title to be used by screen readers.'); export var backgroundPropType = PropTypes.oneOfType([PropTypes.string, PropTypes.shape({ color: PropTypes.string, opacity: PropTypes.oneOfType([PropTypes.oneOf(['weak', 'medium', 'strong']), PropTypes.bool]) })]).description('Background color'); export var colorPropType = PropTypes.oneOfType([PropTypes.string, PropTypes.shape({ dark: PropTypes.string, light: PropTypes.string })]); var MARGIN_SIZES = ['xxsmall', 'xsmall', 'small', 'medium', 'large', 'xlarge']; export var marginProp = PropTypes.oneOfType([PropTypes.oneOf(['none'].concat(MARGIN_SIZES)), PropTypes.shape({ bottom: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]), horizontal: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]), left: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]), right: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]), top: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]), vertical: PropTypes.oneOfType([PropTypes.oneOf(MARGIN_SIZES), PropTypes.string]) }), PropTypes.string]).description("The amount of margin around the component. An object can\n be specified to distinguish horizontal margin, vertical margin, and\n margin on a particular side."); export var genericProps = { a11yTitle: a11yTitlePropType, alignSelf: PropTypes.oneOf(['start', 'center', 'end', 'stretch']).description("How to align along the cross axis when contained in\n a Box or along the column axis when contained in a Grid."), gridArea: PropTypes.string.description("The name of the area to place\n this inside a parent Grid."), margin: marginProp };
/** * Copyright 2017 <NAME> * * 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. * * @author: <NAME> * @data: 2017/01/04 * * This source code is intended for educational and illustrative purposes only * and is provided AS-IS without warranty of any kind. * */ package com.kediumm.kednasdake.controller.core; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import com.kediumm.kednasdake.controller.prefs.JdbcEM; import com.kediumm.kednasdake.controller.utils.ErrorMessage; public class ConnectionDB { private Logger logger = Logger.getLogger(getClass().getName()); private static ConnectionDB instance = new ConnectionDB(); private Connection conn; private ConnectionDB() { } public static ConnectionDB getInstance() { return instance; } public Connection getConnection() { logger.info("Try start new DB connection."); try { //Class.forName(JdbcEM.JDBC_DRIVERCLASSNAME.getValue()).newInstance(); Class.forName(JdbcEM.JDBC_DRIVERCLASSNAME.getValue()); conn = DriverManager.getConnection(JdbcEM.JDBC_URL.getValue(), JdbcEM.JDBC_USER.getValue(), JdbcEM.JDBC_PASSWD.getValue()); } catch (SQLException e) { // send error message to server log logger.log(Level.SEVERE, "Error get new db connection.", e); // send error message for JSF page ErrorMessage.addErrorMessage(e); //e.printStackTrace(); } catch (ClassNotFoundException ex) { //Logger.getLogger(ConnectionDB.class.getName()).log(Level.SEVERE, null, ex); logger.log(Level.SEVERE, "Error to get driver class name for connection.", ex); } return conn; } }
#!/bin/bash if [ -n "$(git status --porcelain)" ]; then git diff for f in $(git ls-files --modified); do echo "::warning ::$f may be outdated" done for f in $(git ls-files --others --exclude-standard); do echo "::warning ::$f may be untracked" done exit 1 fi
#!/usr/bin/env bash # Base16 - Gnome Terminal color scheme install script [[ -z "$PROFILE_NAME" ]] && PROFILE_NAME="terminal.sexy" [[ -z "$PROFILE_SLUG" ]] && PROFILE_SLUG="terminal-dot-sexy" [[ -z "$DCONF" ]] && DCONF=dconf [[ -z "$UUIDGEN" ]] && UUIDGEN=uuidgen dset() { local key="$1"; shift local val="$1"; shift if [[ "$type" == "string" ]]; then val="'$val'" fi "$DCONF" write "$PROFILE_KEY/$key" "$val" } # because dconf still doesn't have "append" dlist_append() { local key="$1"; shift local val="$1"; shift local entries="$( { "$DCONF" read "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val" echo "'$val'" } | head -c-1 | tr "\n" , )" "$DCONF" write "$key" "[$entries]" } # Newest versions of gnome-terminal use dconf if which "$DCONF" > /dev/null 2>&1; then [[ -z "$BASE_KEY_NEW" ]] && BASE_KEY_NEW=/org/gnome/terminal/legacy/profiles: if [[ -n "`$DCONF list $BASE_KEY_NEW/`" ]]; then if which "$UUIDGEN" > /dev/null 2>&1; then PROFILE_SLUG=`uuidgen` fi if [[ -n "`$DCONF read $BASE_KEY_NEW/default`" ]]; then DEFAULT_SLUG=`$DCONF read $BASE_KEY_NEW/default | tr -d \'` else DEFAULT_SLUG=`$DCONF list $BASE_KEY_NEW/ | grep '^:' | head -n1 | tr -d :/` fi DEFAULT_KEY="$BASE_KEY_NEW/:$DEFAULT_SLUG" PROFILE_KEY="$BASE_KEY_NEW/:$PROFILE_SLUG" # copy existing settings from default profile $DCONF dump "$DEFAULT_KEY/" | $DCONF load "$PROFILE_KEY/" # add new copy to list of profiles dlist_append $BASE_KEY_NEW/list "$PROFILE_SLUG" # update profile values with theme options dset visible-name "'$PROFILE_NAME'" dset palette "['#cccbd9', '#b7435e', '#7e8f80', '#d88b72', '#6e7ebf', '#cc99cc', '#728a9a', '#9ca6b9', '#d5d4e0', '#cd667b', '#7d9685', '#de956f', '#6a8cbc', '#8787bf', '#829fb0', '#afb5c6']" dset background-color "'#e6e6f1'" dset foreground-color "'#708190'" dset bold-color "'#708190'" dset bold-color-same-as-fg "true" dset use-theme-colors "false" dset use-theme-background "false" unset PROFILE_NAME unset PROFILE_SLUG unset DCONF unset UUIDGEN exit 0 fi fi # Fallback for Gnome 2 and early Gnome 3 [[ -z "$GCONFTOOL" ]] && GCONFTOOL=gconftool [[ -z "$BASE_KEY" ]] && BASE_KEY=/apps/gnome-terminal/profiles PROFILE_KEY="$BASE_KEY/$PROFILE_SLUG" gset() { local type="$1"; shift local key="$1"; shift local val="$1"; shift "$GCONFTOOL" --set --type "$type" "$PROFILE_KEY/$key" -- "$val" } # Because gconftool doesn't have "append" glist_append() { local type="$1"; shift local key="$1"; shift local val="$1"; shift local entries="$( { "$GCONFTOOL" --get "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val" echo "$val" } | head -c-1 | tr "\n" , )" "$GCONFTOOL" --set --type list --list-type $type "$key" "[$entries]" } # Append the Base16 profile to the profile list glist_append string /apps/gnome-terminal/global/profile_list "$PROFILE_SLUG" gset string visible_name "$PROFILE_NAME" gset string palette "#cccbd9:#b7435e:#7e8f80:#d88b72:#6e7ebf:#cc99cc:#728a9a:#9ca6b9:#d5d4e0:#cd667b:#7d9685:#de956f:#6a8cbc:#8787bf:#829fb0:#afb5c6" gset string background_color "#e6e6f1" gset string foreground_color "#708190" gset string bold_color "#708190" gset bool bold_color_same_as_fg "true" gset bool use_theme_colors "false" gset bool use_theme_background "false" unset PROFILE_NAME unset PROFILE_SLUG unset DCONF unset UUIDGEN
import React, { Component } from 'react'; import Libary from './library/library'; import Schedule from './schedule/schedule'; class Home extends Component { render() { return ( <div className="home"> <Libary /> <Schedule /> </div> ); } } export default Home;
$(function(){ // var duration = 300; // aside ---------------------------------------- var $aside = $('.page-main > aside'); var $asidButton = $aside.find('button') .on('click', function(){ $aside.toggleClass('open'); if($aside.hasClass('open')){ $aside.stop(true).animate({left: '-70px'}, duration, 'easeOutBack'); $asidButton.find('img').attr('src', 'img/btn_close.png'); }else{ $aside.stop(true).animate({left: '-350px'}, duration, 'easeInBack'); $asidButton.find('img').attr('src', 'img/btn_open.png'); }; }); });
import numpy as np data = [1, 2, 3, 4, 5] mean = np.mean(data) std = np.std(data) print("Mean of dataset:", mean) print("Standard deviation of dataset:", std)
#!/bin/bash set -e if [ "$1" = 'dynamodb' ]; then exec gosu dynamodb java -Djava.library.path=/opt/dynamodb/DynamoDBLocal_lib -jar /opt/dynamodb/DynamoDBLocal.jar "${@:2}" fi exec "$@"
class TodaySerializer include FastJsonapi::ObjectSerializer attributes :today, :yesterday, :twodaysago, :lastweek end
#!/usr/bin/env bash if [ "$1" = "-h" -o "$1" = "--help" -o -z "$1" ]; then cat <<EOF Usage: `basename "$0"` my-script.sh `basename "$0"` my-script.sh "My App" EOF exit; fi APP_NAME=${2:-$(basename "$1" ".sh")} DIR="$APP_NAME.app/Contents/MacOS" if [ -a "$APP_NAME.app" ]; then echo "$PWD/$APP_NAME.app already exists :(" exit 1 fi mkdir -p "$DIR" cp "$1" "$DIR/$APP_NAME" chmod +x "$DIR/$APP_NAME" echo "$PWD/$APP_NAME.app"
package com.leetcode.offer; public class Solution_21 { public int[] exchange(int[] nums) { int l = 0, r = nums.length - 1; for (int i = 0; i < nums.length; i++) { if (i >= r) break; if (nums[i] % 2 != 0) { l++; } else { while (i < r && nums[i] % 2 == 0) { swap(nums, l, r--); } l++; } } return nums; } private void swap(int[] ints, int i, int j) { int tmp = ints[i]; ints[i] = ints[j]; ints[j] = tmp; } }
#!/bin/sh docker build -t pwn-ubuntu:20.04 . cp ./pu /usr/bin/ echo 'done'
SET FOREIGN_KEY_CHECKS=0; SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; CREATE TABLE `accesos` ( `Id_Accesos` int(11) NOT NULL, `Nombre_User` varchar(35) NOT NULL, `Password_User` varchar(15) NOT NULL, `Personal_Id_Personal` int(11) DEFAULT NULL, `Activo` tinyint(4) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `aulas` ( `Id_Aulas` int(11) NOT NULL, `Codigo_Aula` varchar(30) NOT NULL, `Descripcion` varchar(15) DEFAULT NULL, `Edificios_Id_Edificios` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `cargos` ( `Id_Cargos` int(11) NOT NULL, `Cargo` varchar(45) NOT NULL, `Descripcion` varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `carreras` ( `IdCarrera` int(11) NOT NULL, `Nombre_Carrera` varchar(100) NOT NULL, `Id_Facultad` int(11) NOT NULL, `Descripcion` varchar(255) NOT NULL, `Duracion` double NOT NULL, `Id_ConjuntoClases` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `clases` ( `Id_Clases` int(11) NOT NULL, `Nombre_Clase` varchar(100) NOT NULL, `Creditos` int(9) NOT NULL, `Activo` tinyint(4) NOT NULL, `Aulas_Id_Aulas` int(11) DEFAULT NULL, `Profesores_Id_Profesores` int(11) DEFAULT NULL, `Turno_Id_Turnos` int(11) DEFAULT NULL, `Departamentos_Id_Depertamentos` int(11) DEFAULT NULL, `Niveles_Id_Niveles` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; CREATE TABLE `cursos` ( `Turnos_Id_Turnos` int(11) NOT NULL, `Clases_Id_Clases` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `departamentos` ( `Id_Departamento` int(11) NOT NULL, `Departamento_Nombre` varchar(45) NOT NULL, `Descripcion` varchar(100) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `edificios` ( `Id_Edificios` int(11) NOT NULL, `Codigo_Edificio` varchar(30) NOT NULL, `Descripcion` varchar(100) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `estudiantes` ( `Id_Estudiantes` int(11) NOT NULL, `Estudiantes_Nombres` varchar(60) NOT NULL, `Estudiantes_Apellidos` varchar(60) NOT NULL, `Fecha_nacimiento` datetime DEFAULT NULL, `Fecha_registro` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `Fecha_actualizacion` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP, `Fecha_inscripcion` time DEFAULT NULL, `Nivel-anio` int(11) NOT NULL, `email` varchar(35) DEFAULT NULL, `Direccion` varchar(100) NOT NULL, `Telefono` varchar(8) DEFAULT NULL, `Celular` varchar(8) NOT NULL, `Notas` int(11) DEFAULT NULL, `sexo` varchar(10) NOT NULL, `genero` varchar(15) NOT NULL, `nacionalidad` varchar(35) NOT NULL, `Cedula` varchar(15) DEFAULT NULL, `Ciudad` varchar(45) NOT NULL, `Departamento` varchar(45) NOT NULL, `Fotos_Id_Photo` int(11) NOT NULL, `decuento` double NOT NULL, `Tutores_Id_Tutores` int(11) DEFAULT NULL, `Monto_a_pagar` double DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; CREATE TABLE `niveles` ( `Id_Niveles` int(11) NOT NULL, `Nombre_Nivel` varchar(45) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `notas` ( `Primer_Parcial` double DEFAULT NULL, `Segundo_Parcial` double DEFAULT NULL, `Nota_Final` double DEFAULT NULL, `Periodo_Id_Periodo` int(11) DEFAULT NULL, `Estudiantes_Id_Estudiantes` int(11) DEFAULT NULL, `Clases_Id_Clases` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `periodos` ( `Id_Periodo` int(11) NOT NULL, `NumerodePeriodo` int(11) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `personal` ( `Id_Personal` int(11) NOT NULL, `Personal_Nombre` varchar(60) NOT NULL, `Personal_Apellidos` varchar(60) NOT NULL, `Telefono` varchar(8) DEFAULT NULL, `Celular` varchar(8) NOT NULL, `Email` varchar(45) DEFAULT NULL, `Direccion` varchar(100) NOT NULL, `Fecha_nacimiento` datetime DEFAULT NULL, `Fecha_registro` datetime DEFAULT NULL, `Fecha_modificacion` datetime DEFAULT NULL, `Salario` double NOT NULL, `Cargos_Id_Cargos` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `profesores` ( `Personal_Id_Personal` int(11) NOT NULL, `Departamentos_Id_Departamentos` int(11) DEFAULT NULL, `Fotos_Id_photo` varchar(255) DEFAULT NULL, `documento_vitae` varchar(255) DEFAULT NULL, `Clases_Id_Clases` int(11) DEFAULT NULL, `Descripcion` varchar(255) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `transacestudiantes` ( `Id_TransacEstudiantes` int(11) NOT NULL, `Fecha_Tracsaciones` time DEFAULT NULL, `Cantidad_Total` double NOT NULL, `Descripcion` varchar(100) DEFAULT NULL, `Estudiantes_Id_Estudiantes` int(11) DEFAULT NULL, `Tutores_Id_Tutores` int(11) DEFAULT NULL, `Personal_IdPersonal` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `turnos` ( `Id_Turnos` int(11) NOT NULL, `Turno` varchar(45) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; CREATE TABLE `tutores` ( `Id_tutores` int(11) NOT NULL, `Nombres_Tutor1` varchar(60) NOT NULL, `Nombres_Tutor2` varchar(60) NOT NULL, `Nombres_Tutor3` varchar(60) DEFAULT NULL, `Apellidos_Tutor1` varchar(60) NOT NULL, `Apellidos_Tutor2` varchar(60) DEFAULT NULL, `Apellidos_Tutor3` varchar(60) DEFAULT NULL, `Telefono` varchar(8) DEFAULT NULL, `Celular_Opcion1` varchar(8) NOT NULL, `Celuar_opcion2` varchar(8) DEFAULT NULL, `Direccion` varchar(100) NOT NULL, `email` varchar(35) DEFAULT NULL, `Cedula_Tutor1` varchar(15) NOT NULL, `Cedula_Tutor2` varchar(15) DEFAULT NULL, `Cedula_Tutor3` varchar(15) DEFAULT NULL, `Estudiantes_Id_Estudiantes` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; ALTER TABLE `accesos` ADD PRIMARY KEY (`Id_Accesos`); ALTER TABLE `aulas` ADD PRIMARY KEY (`Id_Aulas`); ALTER TABLE `cargos` ADD PRIMARY KEY (`Id_Cargos`); ALTER TABLE `carreras` ADD PRIMARY KEY (`IdCarrera`); ALTER TABLE `clases` ADD PRIMARY KEY (`Id_Clases`); ALTER TABLE `cursos` ADD PRIMARY KEY (`Turnos_Id_Turnos`); ALTER TABLE `departamentos` ADD PRIMARY KEY (`Id_Departamento`); ALTER TABLE `edificios` ADD PRIMARY KEY (`Id_Edificios`); ALTER TABLE `estudiantes` ADD PRIMARY KEY (`Id_Estudiantes`); ALTER TABLE `niveles` ADD PRIMARY KEY (`Id_Niveles`); ALTER TABLE `periodos` ADD PRIMARY KEY (`Id_Periodo`); ALTER TABLE `personal` ADD PRIMARY KEY (`Id_Personal`); ALTER TABLE `profesores` ADD PRIMARY KEY (`Personal_Id_Personal`); ALTER TABLE `transacestudiantes` ADD PRIMARY KEY (`Id_TransacEstudiantes`); ALTER TABLE `turnos` ADD PRIMARY KEY (`Id_Turnos`); ALTER TABLE `tutores` ADD PRIMARY KEY (`Id_tutores`); ALTER TABLE `accesos` MODIFY `Id_Accesos` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `aulas` MODIFY `Id_Aulas` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `cargos` MODIFY `Id_Cargos` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `carreras` MODIFY `IdCarrera` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `clases` MODIFY `Id_Clases` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `departamentos` MODIFY `Id_Departamento` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `edificios` MODIFY `Id_Edificios` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `estudiantes` MODIFY `Id_Estudiantes` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `niveles` MODIFY `Id_Niveles` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `periodos` MODIFY `Id_Periodo` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `personal` MODIFY `Id_Personal` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `profesores` MODIFY `Personal_Id_Personal` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `transacestudiantes` MODIFY `Id_TransacEstudiantes` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `turnos` MODIFY `Id_Turnos` int(11) NOT NULL AUTO_INCREMENT; ALTER TABLE `tutores` MODIFY `Id_tutores` int(11) NOT NULL AUTO_INCREMENT;SET FOREIGN_KEY_CHECKS=1; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<?php function sum($a, $b) { return $a + $b; } ?>
docker exec -it mongo_on_dnw mongo
#!/bin/bash #set -x set -euo pipefail NF_NAME=pvn-aclfw M_CORE=0 PORT_ONE="0000:01:00.0" PORT_TWO="0000:01:00.1" ../../build.sh run $NF_NAME -n " =========== Running ACL Firewall ============ " -m $M_CORE \ -c 2 -c 3 -c 4 -c 5 \ -p $PORT_ONE -p $PORT_TWO | tee out
<gh_stars>0 import docparser from 'docparser-node'; /** * List of available parsers created */ export const ParserIds = { 'Cash Orders Report': 'injkrceqmwxy', 'Maybank Daily Booking Report': 'iwdlifylqpae', 'UOB Daily Subscription Daily Booking Summary': 'sjvhyxphmcwu', }; export class DocumentParser { constructor ({ DOCPARSERKEY, }) { // Static variables DocumentParser.QUOTA_LEFT = 0; DocumentParser.QUOTA_REFILL = 0; DocumentParser.QUOTA_USED = 0; this.client = new docparser.Client(DOCPARSERKEY); this .client .ping() .then(() => { console.log('Authentication Succeeded'); }) .catch(error => { console.log('Authentication Failed\n', error); }); } uploadFile ({ errorCallback = console.log, singleFilePath, parserId, remoteId = undefined, // User identifier that only allow the user only can download their uploaded file successCallback = console.log, }) { this.parserId = parserId; this.remoteId = remoteId; console.log(parserId); console.log(singleFilePath); this .client .uploadFileByPath( parserId, singleFilePath, JSON.parse(JSON.stringify({ // Remove undefined values remote_id: remoteId, }))) /** * Sample output response = { * id: "document_id", * file_size: 198989, * quota_used: 16, * quota_left: 34, * quota_refill: "1970-01-01T00:00:00+00:00", * } */ .then(response => { DocumentParser.QUOTA_LEFT = response.quota_left; DocumentParser.QUOTA_REFILL = response.quota_refill; DocumentParser.QUOTA_USED = response.quota_used; this.documentId = response.id; successCallback(response); }) .catch(errorCallback); } getParsedDocument ({ documentId = this.documentId, errorCallback = console.log, format = 'object', // 'flat' parserId = this.parserId, successCallback = console.log, }) { this .client .getResultsByDocument(parserId, documentId, { format, }) .then(successCallback) .catch(errorCallback); } getAllParsedDocuments ({ errorCallback = console.log, format = 'object', // 'flat' from, parserId = this.parserId, successCallback = console.log, remoteId = this.remoteId, }) { this .client .getResultsByParser( parserId, JSON.parse(JSON.stringify({ // Remove undefined values date: from, format, list: 'uploaded_after', remoteId, }))) .then(successCallback) .catch(errorCallback); } }
import { InputType, Field } from '@nestjs/graphql'; @InputType() export class UserCreateInput { @Field({ nullable: true }) firstName?: string; @Field({ nullable: true }) lastName?: string; @Field({ nullable: true }) email?: string; @Field({ nullable: true }) username?: string; @Field({ nullable: true }) enabled?: string; @Field({ nullable: true }) password?: string; @Field({ nullable: true }) passwordConfirm?: string; }
<gh_stars>1-10 package cn.shiyanjun.platform.scheduled.utils; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.google.common.base.Throwables; import com.rabbitmq.client.ConnectionFactory; import cn.shiyanjun.platform.api.Context; import cn.shiyanjun.platform.api.common.ContextImpl; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public class ResourceUtils { private static final Log LOG = LogFactory.getLog(ResourceUtils.class); private static final ConcurrentMap<Class<?>, Object> pooledInstances = new ConcurrentHashMap<>(); private static final ConcurrentMap<Class<?>, String> pooledConfigurations = new ConcurrentHashMap<>(); private static final Map<Class<?>, ResourceBuilder<?>> builders = new HashMap<>(); static { // register resource builder instances builders.put(JedisPool.class, new JedisPoolBuilder()); builders.put(ConnectionFactory.class, new RabbitConnectionFactoryBuilder()); } @SuppressWarnings({ "unchecked" }) public static synchronized <T> void registerResource(String config, Class<T> resourceClazz) { try { ResourceBuilder<?> builder = builders.get(resourceClazz); T resource = (T) builder.build(config); pooledInstances.putIfAbsent(resourceClazz, resource); pooledConfigurations.putIfAbsent(resourceClazz, config); LOG.info("Resource registered: config=" + config + ", resource=" + resource); } catch (Exception e) { Throwables.propagate(e); } } @SuppressWarnings({ "unchecked" }) public static synchronized <T> T registerAndGetResource(String config, Class<T> resourceClazz) { try { ResourceBuilder<?> builder = builders.get(resourceClazz); T resource = (T) builder.build(config); pooledInstances.putIfAbsent(resourceClazz, resource); pooledConfigurations.putIfAbsent(resourceClazz, config); } catch (Exception e) { Throwables.propagate(e); } return (T) pooledInstances.get(resourceClazz); } @SuppressWarnings({ "unchecked" }) public static <T> T getResource(Class<T> resourceClazz) { return (T) pooledInstances.get(resourceClazz); } interface ResourceBuilder<T> { T build(String config) throws Exception; } public static void closeAll() { pooledInstances.keySet().forEach(clazz -> { try { Object o = pooledInstances.get(clazz); if(o instanceof JedisPool) { ((JedisPool) o).close(); } } catch (Exception e) { // ignore it } }); } private static abstract class AbstractResourceBuilder { protected String getString(Context context, String key, String defaultValue) { return context.get(key, defaultValue); } protected int getInt(Context context, String key, int defaultValue) { return context.getInt(key, defaultValue); } protected boolean getBool(Context context, String key, boolean defaultValue) { return context.getBoolean(key, defaultValue); } } private static final class RabbitConnectionFactoryBuilder extends AbstractResourceBuilder implements ResourceBuilder<ConnectionFactory> { private static String RABBITMQ_HOST = "rabbitmq.host"; private static String RABBITMQ_PORT = "rabbitmq.port"; private static String RABBITMQ_USERNAME = "rabbitmq.username"; private static String RABBITMQ_PASSWORD = "<PASSWORD>"; private static String RABBITMQ_CONNECT_TIMEOUT = "rabbitmq.connect.timeout"; private static String RABBITMQ_AUTOMATIC_RECOVERY = "rabbitmq.automatic.recovery"; @Override public ConnectionFactory build(String config) throws Exception { final Context context = new ContextImpl(config); ConnectionFactory factory = new ConnectionFactory(); factory.setHost(getString(context, RABBITMQ_HOST, "localhost")); factory.setPort(getInt(context, RABBITMQ_PORT, 5672)); factory.setUsername(getString(context, RABBITMQ_USERNAME, null)); factory.setPassword(getString(context, RABBITMQ_PASSWORD, null)); factory.setConnectionTimeout(context.getInt(RABBITMQ_CONNECT_TIMEOUT, 30000)); factory.setAutomaticRecoveryEnabled(context.getBoolean(RABBITMQ_AUTOMATIC_RECOVERY, true)); return factory; } } private static final class JedisPoolBuilder extends AbstractResourceBuilder implements ResourceBuilder<JedisPool> { private static String REDIS_HOST = "redis.host"; private static String REDIS_PORT = "redis.port"; private static String REDIS_PASSWORD = "<PASSWORD>"; private static String REDIS_TIMEOUT = "redis.timeout"; private static String REDIS_POOL_MAX_TOTAL = "redis.pool.maxTotal"; private static String REDIS_POOL_MAX_IDLE = "redis.pool.maxIdle"; private static String REDIS_POOL_MIN_IDLE = "redis.pool.minIdle"; private static String REDIS_POOL_MAX_WAIT_MILLIS = "redis.pool.maxWaitMillis"; private static String REDIS_POOL_TEST_ON_BORROW = "redis.pool.testOnBorrow"; private static String REDIS_POOL_TEST_ON_RETURN = "redis.pool.testOnReturn"; @Override public JedisPool build(String config) throws Exception { JedisPoolConfig jpc = new JedisPoolConfig(); final Context context = new ContextImpl(config); jpc.setMaxTotal(getInt(context, REDIS_POOL_MAX_TOTAL, 1)); jpc.setMaxIdle(getInt(context, REDIS_POOL_MAX_IDLE, 1)); jpc.setMinIdle(getInt(context, REDIS_POOL_MIN_IDLE, 1)); jpc.setMaxWaitMillis(getInt(context, REDIS_POOL_MAX_WAIT_MILLIS, 30000)); jpc.setTestOnBorrow(getBool(context, REDIS_POOL_TEST_ON_BORROW, true)); jpc.setTestOnReturn(getBool(context, REDIS_POOL_TEST_ON_RETURN, false)); String host = getString(context, REDIS_HOST, "localhost"); int port = getInt(context, REDIS_PORT, 6379); String password = context.get(REDIS_PASSWORD); if(password != null) { int timeout = getInt(context, REDIS_TIMEOUT, 30000); return new JedisPool(jpc, host, port, timeout, password); } return new JedisPool(jpc, host, port); } } }
# File: L (Python 2.4) from pandac.PandaModules import * from direct.distributed.MsgTypes import * from direct.directnotify import DirectNotifyGlobal import LoginBase from direct.distributed.PyDatagram import PyDatagram class LoginGSAccount(LoginBase.LoginBase): def __init__(self, cr): LoginBase.LoginBase.__init__(self, cr) def createAccount(self, loginName, password, data): self.loginName = loginName self.password = password self.createFlag = 1 self.cr.freeTimeExpiresAt = -1 self.cr.setIsPaid(1) def authorize(self, loginName, password): self.loginName = loginName self.password = password self.createFlag = 0 self.cr.freeTimeExpiresAt = -1 self.cr.setIsPaid(1) def supportsRelogin(self): return 1 def sendLoginMsg(self): DISLID = config.GetInt('fake-DISL-PlayerAccountId', 0) if not DISLID: NameStringId = 'DISLID_%s' % self.loginName DISLID = config.GetInt(NameStringId, 0) cr = self.cr datagram = PyDatagram() datagram.addUint16(CLIENT_LOGIN) datagram.addString(self.loginName) if cr.connectMethod != cr.CM_HTTP: datagram.addUint32(cr.tcpConn.getAddress().getIp()) else: datagram.addUint32(0) datagram.addUint16(5150) datagram.addString(cr.serverVersion) datagram.addUint32(cr.hashVal) datagram.addString(self.password) datagram.addBool(self.createFlag) datagram.addString(cr.validateDownload) datagram.addString(cr.wantMagicWords) datagram.addUint32(DISLID) datagram.addString(config.GetString('otp-whitelist', 'YES')) cr.send(datagram) def resendPlayToken(self): pass def requestPwdReminder(self, email = None, acctName = None): return 0 def getAccountData(self, loginName, password): return 'Unsupported' def supportsParentPassword(self): return 1 def authenticateParentPassword(self, loginName, password, parentPassword): return (password == parentPassword, None) def authenticateParentUsernameAndPassword(self, loginName, password, parentUsername, parentPassword): return (password == parentPassword, None) def supportsAuthenticateDelete(self): return 1 def authenticateDelete(self, loginName, password): return (password == <PASSWORD>, None) def enableSecretFriends(self, loginName, password, parentPassword, enable = 1): return (password == parentPassword, None)
/* * JaamSim Discrete Event Simulation * Copyright (C) 2002-2011 Ausenco Engineering Canada Inc. * Copyright (C) 2016-2021 JaamSim Software Inc. * * 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. */ package com.jaamsim.basicsim; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; import com.jaamsim.events.Conditional; import com.jaamsim.events.EventHandle; import com.jaamsim.events.EventManager; import com.jaamsim.events.ProcessTarget; import com.jaamsim.input.AttributeDefinitionListInput; import com.jaamsim.input.AttributeHandle; import com.jaamsim.input.BooleanInput; import com.jaamsim.input.ExpError; import com.jaamsim.input.ExpParser.Expression; import com.jaamsim.input.ExpResType; import com.jaamsim.input.ExpResult; import com.jaamsim.input.ExpValResult; import com.jaamsim.input.ExpressionHandle; import com.jaamsim.input.Input; import com.jaamsim.input.InputAgent; import com.jaamsim.input.InputErrorException; import com.jaamsim.input.Keyword; import com.jaamsim.input.KeywordIndex; import com.jaamsim.input.NamedExpression; import com.jaamsim.input.NamedExpressionListInput; import com.jaamsim.input.Output; import com.jaamsim.input.OutputHandle; import com.jaamsim.input.StringInput; import com.jaamsim.input.SynonymInput; import com.jaamsim.input.ValueHandle; import com.jaamsim.units.DimensionlessUnit; import com.jaamsim.units.TimeUnit; import com.jaamsim.units.Unit; /** * Abstract class that encapsulates the methods and data needed to create a * simulation object. Encapsulates the basic system objects to achieve discrete * event execution. */ public class Entity { private final JaamSimModel simModel; String entityName; private final long entityNumber; // Package private so it can be accessed by JaamSimModel and EntityListNode EntityListNode listNode; private static final int FLAG_TRACE = 0x01; //public static final int FLAG_TRACEREQUIRED = 0x02; //public static final int FLAG_TRACESTATE = 0x04; //public static final int FLAG_LOCKED = 0x08; //public static final int FLAG_TRACKEVENTS = 0x10; static final int FLAG_ADDED = 0x20; // entity was defined after the 'RecordEdits' flag static final int FLAG_EDITED = 0x40; // one or more inputs were modified after the 'RecordEdits' flag static final int FLAG_GENERATED = 0x80; // entity was created during the execution of the simulation static final int FLAG_DEAD = 0x0100; // entity has been deleted static final int FLAG_REGISTERED = 0x0200; // entity is included in the namedEntities HashMap static final int FLAG_RETAINED = 0x0400; // entity is retained when the model is reset between runs private int flags; Entity parent; private final ArrayList<Input<?>> inpList = new ArrayList<>(); private final HashMap<String, AttributeHandle> attributeMap = new LinkedHashMap<>(); private final HashMap<String, ExpressionHandle> customOutputMap = new LinkedHashMap<>(); public static final String KEY_INPUTS = "Key Inputs"; public static final String OPTIONS = "Options"; public static final String GRAPHICS = "Graphics"; public static final String THRESHOLDS = "Thresholds"; public static final String MAINTENANCE = "Maintenance"; public static final String FONT = "Font"; public static final String FORMAT = "Format"; public static final String GUI = "GUI"; public static final String MULTIPLE_RUNS = "Multiple Runs"; @Keyword(description = "A free-form string describing the object.", exampleList = {"'A very useful entity'"}) protected final StringInput desc; @Keyword(description = "Provides the programmer with a detailed trace of the logic executed " + "by the entity. Trace information is sent to standard out.", exampleList = {"TRUE"}) protected final BooleanInput trace; @Keyword(description = "If TRUE, the object is used in the simulation run.", exampleList = {"FALSE"}) protected final BooleanInput active; @Keyword(description = "Defines one or more attributes for this entity. " + "An attribute's value can be a number with or without units, " + "an entity, a string, an array, a map, or a lambda function. " + "The initial value set by the definition can only be changed by an " + "Assign object.", exampleList = {"{ AAA 1 } { bbb 2[s] } { c '\"abc\"' } { d [Queue1] }", "{ e '{1,2,3}' } { f '|x|(2*x)' }"}) public final AttributeDefinitionListInput attributeDefinitionList; @Keyword(description = "Defines one or more custom outputs for this entity. " + "A custom output can return a number with or without units, " + "an entity, a string, an array, a map, or a lambda function. " + "The present value of a custom output is calculated on demand by the " + "model.", exampleList = {"{ TwiceSimTime '2*this.SimTime' TimeUnit } { SimTimeInDays 'this.SimTime/1[d]' }", "{ FirstEnt 'size([Queue1].QueueList)>0 ? [Queue1].QueueList(1) : [SimEntity1]' }"}) public final NamedExpressionListInput namedExpressionInput; { desc = new StringInput("Description", KEY_INPUTS, ""); this.addInput(desc); trace = new BooleanInput("Trace", OPTIONS, false); trace.setHidden(true); this.addInput(trace); active = new BooleanInput("Active", OPTIONS, true); active.setHidden(true); this.addInput(active); attributeDefinitionList = new AttributeDefinitionListInput("AttributeDefinitionList", OPTIONS, new ArrayList<AttributeHandle>()); attributeDefinitionList.setHidden(false); this.addInput(attributeDefinitionList); namedExpressionInput = new NamedExpressionListInput("CustomOutputList", OPTIONS, new ArrayList<NamedExpression>()); namedExpressionInput.setHidden(false); this.addInput(namedExpressionInput); } /** * Constructor for entity initializing members. */ public Entity() { simModel = JaamSimModel.getCreateModel(); entityNumber = simModel.getNextEntityID(); flags = 0; } /** * Performs any initialization that must occur after the constructor has finished. */ public void postDefine() {} public JaamSimModel getJaamSimModel() { return simModel; } public Simulation getSimulation() { return simModel.getSimulation(); } /** * Performs any additional actions that are required after a new configuration file has been * loaded. Performed prior to validation. */ public void postLoad() {} public void validate() throws InputErrorException { for (Input<?> in : inpList) { in.validate(); } } /** * Initialises the entity prior to the start of the model run. * <p> * This method must not depend on any other entities so that it can be * called for each entity in any sequence. */ public void earlyInit() { // Reset the attributes to their initial values for (AttributeHandle h : attributeMap.values()) { h.setValue(h.getInitialValue()); } } /** * Initialises the entity prior to the start of the model run. * <p> * This method assumes other entities have already called earlyInit. */ public void lateInit() {} /** * Starts the execution of the model run for this entity. * <p> * If required, initialisation that depends on another entity can be * performed in this method. It is called after earlyInit(). */ public void startUp() {} /** * Resets the statistics collected by the entity. */ public void clearStatistics() {} /** * Assigns input values that are helpful when the entity is dragged and * dropped into a model. */ public void setInputsForDragAndDrop() {} public void kill() { for (Entity ent : getChildren()) { ent.kill(); } if (this.isDead()) return; simModel.removeInstance(this); } /** * Reverses the actions taken by the kill method. * @param name - entity's absolute name before it was deleted */ public void restore(String name) { simModel.restoreInstance(this); this.setName(name); this.clearFlag(Entity.FLAG_DEAD); postDefine(); } public final boolean isAdded() { return this.testFlag(Entity.FLAG_ADDED); } public final boolean isGenerated() { return this.testFlag(Entity.FLAG_GENERATED); } public final boolean isRegistered() { return this.testFlag(Entity.FLAG_REGISTERED); } public final boolean isDead() { return this.testFlag(Entity.FLAG_DEAD); } public final boolean isEdited() { return this.testFlag(Entity.FLAG_EDITED); } public final void setEdited() { this.setFlag(Entity.FLAG_EDITED); } /** * Returns whether the entity can participate in the simulation. * @return true if the entity can be used */ public boolean isActive() { return active.getValue(); } /** * Performs any actions that are required at the end of the simulation run, e.g. to create an output report. */ public void doEnd() {} /** * Performs any actions that are required when a model is closed prior to its scheduled end * time. For example, an entity may need to close a file that it opened. */ public void close() {} /** * Get the current Simulation ticks value. * @return the current simulation tick */ public final long getSimTicks() { return EventManager.simTicks(); } /** * Get the current Simulation time. * @return the current time in seconds */ public final double getSimTime() { return EventManager.simSeconds(); } protected void addInput(Input<?> in) { inpList.add(in); } protected void removeInput(Input<?> in) { inpList.remove(in); } protected void addSynonym(Input<?> in, String synonym) { inpList.add(new SynonymInput(synonym, in)); } public final Input<?> getInput(String key) { for (int i = 0; i < inpList.size(); i++) { Input<?> in = inpList.get(i); if (key.equals(in.getKeyword())) { if (in.isSynonym()) return ((SynonymInput)in).input; else return in; } } return null; } /** * Copy the inputs for each keyword to the caller. * @param ent = entity whose inputs are to be copied */ public void copyInputs(Entity ent) { for (int seq = 0; seq < 2; seq++) { copyInputs(ent, seq, false); } } /** * Copy the inputs for the keywords with the specified sequence number to the caller. * @param ent = entity whose inputs are to be copied * @param seq = sequence number for the keyword (0 = early keyword, 1 = normal keyword) * @param bool = true if each copied input is locked after its value is set */ public void copyInputs(Entity ent, int seq, boolean bool) { String oldParent = ent.getParent().getName(); String oldParent1 = String.format("[%s]", oldParent); String oldParent2 = String.format("%s.", oldParent); String newParent = this.getParent().getName(); String newParent1 = String.format("[%s]", newParent); String newParent2 = String.format("%s.", newParent); // Provide stub definitions for the custom outputs if (seq == 0) { NamedExpressionListInput in = (NamedExpressionListInput) ent.getInput("CustomOutputList"); if (in != null && !in.isDefault()) { KeywordIndex kw = InputAgent.formatInput(in.getKeyword(), in.getStubDefinition()); InputAgent.apply(this, kw); } } // Apply the inputs based on the source entity ArrayList<String> tmp = new ArrayList<>(); for (Input<?> sourceInput : ent.getEditableInputs()) { if (sourceInput.isDefault() || sourceInput.isSynonym() || sourceInput.getSequenceNumber() != seq) continue; String key = sourceInput.getKeyword(); Input<?> targetInput = this.getInput(key); if (targetInput == null) continue; tmp.clear(); sourceInput.getValueTokens(tmp); // Replace references to the parent entity if (this.getParent() != ent.getParent()) { for (int i = 0; i < tmp.size(); i++) { String str = tmp.get(i); if (str.equals(oldParent)) str = newParent; str = str.replace(oldParent1, newParent1); str = str.replace(oldParent2, newParent2); tmp.set(i, str); } } try { KeywordIndex kw = new KeywordIndex(key, tmp, null); InputAgent.apply(this, targetInput, kw); targetInput.setLocked(bool); } catch (Exception e) { GUIListener gui = getJaamSimModel().getGUIListener(); if (gui != null) { String msg = String.format("%s, keyword: %s, value: %s%n%s", this, key, tmp, e.getMessage()); gui.invokeErrorDialogBox("Runtime Error", msg); } } } } /** * Copies the input values from one entity to another. This method is significantly faster * than copying and re-parsing the input data. * @param ent - entity whose inputs are to be copied. * @param target - entity whose inputs are to be assigned. */ public static void fastCopyInputs(Entity ent, Entity target) { // Loop through the original entity's inputs ArrayList<Input<?>> orig = ent.getEditableInputs(); for (int i = 0; i < orig.size(); i++) { Input<?> sourceInput = orig.get(i); // Default values do not need to be copied if (sourceInput.isDefault() || sourceInput.isSynonym()) continue; // Get the matching input for the new entity Input<?> targetInput = target.getEditableInputs().get(i); // Assign the value to the copied entity's input targetInput.copyFrom(target, sourceInput); // Further processing related to this input target.updateForInput(targetInput); } } public ArrayList<Entity> getEntityReferences() { ArrayList<Entity> ret = new ArrayList<>(); for (Input<?> inp : inpList) { inp.appendEntityReferences(ret); } return ret; } final void setFlag(int flag) { flags |= flag; } final void clearFlag(int flag) { flags &= ~flag; } final boolean testFlag(int flag) { return (flags & flag) != 0; } public final void setTraceFlag() { this.setFlag(FLAG_TRACE); } public final void clearTraceFlag() { this.clearFlag(FLAG_TRACE); } public final boolean isTraceFlag() { return this.testFlag(FLAG_TRACE); } /** * Method to return the name of the entity. * This returns the "absolute" name for entities that are the child of other entities. * Use getLocalName() for the name relative to this entity's parent */ public final String getName() { if (!this.isRegistered() || parent == null) { return entityName; } // Build up the name based on the chain of parents ArrayList<String> revNames = new ArrayList<>(); revNames.add(entityName); Entity curEnt = this.getParent(); JaamSimModel model = getJaamSimModel(); while(curEnt != model.getSimulation()) { revNames.add(curEnt.entityName); curEnt = curEnt.getParent(); } // Build up the name back to front StringBuilder sb = new StringBuilder(); for (int i = revNames.size() - 1; i >= 0; i--) { sb.append(revNames.get(i)); if (i > 0) { sb.append('.'); } } return sb.toString(); } public final String getLocalName() { return entityName; } /** * Add a child to this entity, should only be called from JaamSimModel * @param child */ public void addChild(Entity child) { error("Entity [%s] may not have children", getName()); } public void removeChild(Entity child) { error("Entity [%s] may not have children", getName()); } /** * Get the unique number for this entity */ public long getEntityNumber() { return entityNumber; } /** * Method to return the unique identifier of the entity. Used when building Edit tree labels * @return entityName */ @Override public String toString() { return getName(); } /** * Sets the absolute name of the entity. * @param newName - new absolute name */ public void setName(String newName) { String localName = newName; if (newName.contains(".")) { String[] names = newName.split("\\."); localName = names[names.length - 1]; } setLocalName(localName); } /** * Sets the local name of the entity. * @param newName - new local name */ public void setLocalName(String newName) { simModel.renameEntity(this, newName); } /** * Returns the parent entity for this entity */ public Entity getParent() { if (parent != null) return parent; return simModel.getSimulation(); } /** * Gets a named child from this entity. * Default behaviour always returns null, only specific entities may have children * @param name - the local name of the child, implementers must split the name on '.' characters and recursively call getChild() * @return the descendant named or null if no such entity exists */ public Entity getChild(String name) { return null; } /** * Returns the named child entities for this entity. * @return array of child entities */ public ArrayList<Entity> getChildren() { return new ArrayList<>(); } public int getSubModelLevel() { int ret = 0; Entity ent = parent; while (ent != null) { ret++; ent = ent.parent; } return ret; } /** * This method updates the Entity for changes in the given input */ public void updateForInput( Input<?> in ) { if (in == trace) { if (trace.getValue()) this.setTraceFlag(); else this.clearTraceFlag(); return; } if (in == attributeDefinitionList) { attributeMap.clear(); for (AttributeHandle h : attributeDefinitionList.getValue()) { this.addAttribute(h.getName(), h); } return; } if (in == namedExpressionInput) { customOutputMap.clear(); for (NamedExpression ne : namedExpressionInput.getValue()) { addCustomOutput(ne.getName(), ne.getExpression(), ne.getUnitType()); } return; } } public final void startProcess(String methodName, Object... args) { EventManager.startProcess(new ReflectionTarget(this, methodName, args)); } public final void startProcess(ProcessTarget t) { EventManager.startProcess(t); } public final void scheduleProcess(double secs, int priority, ProcessTarget t) { EventManager.scheduleSeconds(secs, priority, false, t, null); } public final void scheduleProcess(double secs, int priority, String methodName, Object... args) { EventManager.scheduleSeconds(secs, priority, false, new ReflectionTarget(this, methodName, args), null); } public final void scheduleProcess(double secs, int priority, ProcessTarget t, EventHandle handle) { EventManager.scheduleSeconds(secs, priority, false, t, handle); } public final void scheduleProcess(double secs, int priority, boolean fifo, ProcessTarget t, EventHandle handle) { EventManager.scheduleSeconds(secs, priority, fifo, t, handle); } public final void scheduleProcessTicks(long ticks, int priority, boolean fifo, ProcessTarget t, EventHandle h) { EventManager.scheduleTicks(ticks, priority, fifo, t, h); } public final void scheduleProcessTicks(long ticks, int priority, ProcessTarget t) { EventManager.scheduleTicks(ticks, priority, false, t, null); } public final void scheduleProcessTicks(long ticks, int priority, String methodName, Object... args) { EventManager.scheduleTicks(ticks, priority, false, new ReflectionTarget(this, methodName, args), null); } public final void waitUntil(Conditional cond, EventHandle handle) { // Don't actually wait if the condition is already true if (cond.evaluate()) return; EventManager.waitUntil(cond, handle); } /** * Wait a number of simulated seconds and a given priority. * @param secs * @param priority */ public final void simWait(double secs, int priority) { EventManager.waitSeconds(secs, priority, false, null); } /** * Wait a number of simulated seconds and a given priority. * @param secs * @param priority */ public final void simWait(double secs, int priority, EventHandle handle) { EventManager.waitSeconds(secs, priority, false, handle); } /** * Wait a number of simulated seconds and a given priority. * @param secs * @param priority */ public final void simWait(double secs, int priority, boolean fifo, EventHandle handle) { EventManager.waitSeconds(secs, priority, fifo, handle); } /** * Wait a number of discrete simulation ticks and a given priority. * @param ticks * @param priority */ public final void simWaitTicks(long ticks, int priority) { EventManager.waitTicks(ticks, priority, false, null); } /** * Wait a number of discrete simulation ticks and a given priority. * @param ticks * @param priority * @param fifo * @param handle */ public final void simWaitTicks(long ticks, int priority, boolean fifo, EventHandle handle) { EventManager.waitTicks(ticks, priority, fifo, handle); } public void handleSelectionLost() {} // ****************************************************************************************************** // EDIT TABLE METHODS // ****************************************************************************************************** public ArrayList<Input<?>> getEditableInputs() { return inpList; } // ****************************************************************************************************** // TRACING METHODS // ****************************************************************************************************** /** * Prints a trace statement for the given subroutine. * The entity name is included in the output. * @param indent - number of tabs with which to indent the text * @param fmt - format string for the trace data (include the method name) * @param args - trace data */ public void trace(int indent, String fmt, Object... args) { simModel.trace(indent, this, fmt, args); } /** * Prints an additional line of trace info. * The entity name is NOT included in the output * @param indent - number of tabs with which to indent the text * @param fmt - format string for the trace data * @param args - trace data */ public void traceLine(int indent, String fmt, Object... args) { simModel.trace(indent, null, fmt, args); } /** * Throws an ErrorException for this entity with the specified message. * @param fmt - format string for the error message * @param args - objects used by the format string * @throws ErrorException */ public void error(String fmt, Object... args) throws ErrorException { if (fmt == null) throw new ErrorException(this, "null"); throw new ErrorException(this, String.format(fmt, args)); } /** * Returns a user specific unit type. This is needed for entity types like distributions that may change the unit type * that is returned at runtime. */ public Class<? extends Unit> getUserUnitType() { return DimensionlessUnit.class; } public ValueHandle getOutputHandle(String outputName) { ValueHandle ret; ret = attributeMap.get(outputName); if (ret != null) return ret; ret = customOutputMap.get(outputName); if (ret != null) return ret; ret = OutputHandle.getOutputHandle(this, outputName); if (ret != null) return ret; return null; } private void addCustomOutput(String name, Expression exp, Class<? extends Unit> unitType) { ExpressionHandle eh = new ExpressionHandle(this, exp, name, unitType); customOutputMap.put(name, eh); } public boolean hasCustomOutput(String name) { return customOutputMap.containsKey(name); } /** * Returns true if there are any outputs that will be printed to the output report. */ public boolean isReportable() { return OutputHandle.isReportable(getClass()); } public String getDescription() { return desc.getValue(); } private void addAttribute(String name, AttributeHandle h) { attributeMap.put(name, h); } public boolean hasAttribute(String name) { return attributeMap.containsKey(name); } // Utility function to help set attribute values for nested indices private ExpResult setAttribIndices(ExpResult.Collection coll, ExpResult[] indices, int indNum, ExpResult value) throws ExpError { assert(indNum < indices.length); ExpResType indType = indices[indNum].type; if (indType != ExpResType.NUMBER && indType != ExpResType.STRING) { this.error("Assigning to attributes must have numeric or string indices. Index #%d is %s", indNum, ExpValResult.typeString(indices[indNum].type)); } if (indNum == indices.length-1) { // Last index, assign the value ExpResult.Collection newCol = coll.assign(indices[indNum], value.getCopy()); return ExpResult.makeCollectionResult(newCol); } // Otherwise, recurse one level deeper ExpResult nestedColl = coll.index(indices[indNum]); if (nestedColl.type != ExpResType.COLLECTION) { this.error("Assigning to value that is not a collection. Value is a %s", ExpValResult.typeString(nestedColl.type)); } ExpResult recurseRes = setAttribIndices(nestedColl.colVal, indices, indNum+1, value); ExpResult.Collection newCol = coll.assign(indices[indNum], recurseRes); return ExpResult.makeCollectionResult(newCol); } public void setAttribute(String name, ExpResult[] indices, ExpResult value) throws ExpError { AttributeHandle h = attributeMap.get(name); if (h == null) throw new ExpError(null, -1, "Invalid attribute name for %s: %s", this, name); ExpResult assignValue = null; // Collection Attribute if (indices != null) { ExpResult attribValue = h.getValue(getSimTime(), ExpResult.class); if (attribValue.type != ExpResType.COLLECTION) { throw new ExpError(null, -1, "Trying to set %s attribute: %s with an index, " + "but it is not a collection", this, name); } try { assignValue = setAttribIndices(attribValue.colVal, indices, 0, value); } catch (ExpError err) { throw new ExpError(err.source, err.pos, "Error during assignment to %s: %s", this, err.getMessage()); } } // Single-Valued Attribute else { if (value.type == ExpResType.NUMBER && h.getUnitType() != value.unitType) { throw new ExpError(null, -1, "Unit returned by the expression does not match the " + "attribute. Received: %s, expected: %s", value.unitType.getSimpleName(), h.getUnitType().getSimpleName()); } assignValue = value.getCopy(); } h.setValue(assignValue); } public ArrayList<ValueHandle> getAllOutputs() { ArrayList<ValueHandle> ret = OutputHandle.getAllOutputHandles(this); // And the attributes for (Entry<String, AttributeHandle> e : attributeMap.entrySet()) { ret.add(e.getValue()); } // Add the custom outputs for (Entry<String, ExpressionHandle> e : customOutputMap.entrySet()) { ret.add(e.getValue()); } Collections.sort(ret, new ValueHandleComparator()); return ret; } private static class ValueHandleComparator implements Comparator<ValueHandle> { @Override public int compare(ValueHandle hand0, ValueHandle hand1) { Class<?> class0 = hand0.getDeclaringClass(); Class<?> class1 = hand1.getDeclaringClass(); if (class0 == class1) { if (hand0.getSequence() == hand1.getSequence()) return 0; else if (hand0.getSequence() < hand1.getSequence()) return -1; else return 1; } if (class0.isAssignableFrom(class1)) return -1; else return 1; } } public ObjectType getObjectType() { return simModel.getObjectTypeForClass(this.getClass()); } @Output(name = "Name", description = "The unique input name for this entity.", sequence = 0) public final String getNameOutput(double simTime) { return getName(); } @Output(name = "ObjectType", description = "The class of objects that this entity belongs to.", sequence = 1) public String getObjectTypeName(double simTime) { ObjectType ot = this.getObjectType(); if (ot == null) return null; return ot.getName(); } @Output(name = "SimTime", description = "The present simulation time.", unitType = TimeUnit.class, sequence = 2) public double getSimTime(double simTime) { return simTime; } @Output(name = "Parent", description = "The parent entity for this entity.", sequence = 3) public Entity getParentOutput(double simTime) { return getParent(); } }
func getThemeColor(colorIndex: Int) -> String { switch colorIndex { case 0: return "blueColor" case 1: return "greenColor" case 2: return "redColor" default: return "defaultColor" } }