<commit_before>/* NEW BSD LICENSE {{{
Copyright (c) 2009, anekos.
All rights reserved.

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

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. The names of the authors may not be used to endorse or promote products
       derived from this software without specific prior written permission.

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

###################################################################################
# http://sourceforge.jp/projects/opensource/wiki/licenses%2Fnew_BSD_license       #
# に参考になる日本語訳がありますが、有効なのは上記英文となります。                #
###################################################################################

}}} */

// PLUGIN_INFO {{{
let PLUGIN_INFO =
<VimperatorPlugin>
  <name>Auto focus frame</name>
  <description>Automatically focus to largest frame.</description>
  <description lang="ja">最も大きなフレームに自動的にフォーカスする。</description>
  <version>1.0.10</version>
  <author mail="anekos@snca.net" homepage="http://d.hatena.ne.jp/nokturnalmortum/">anekos</author>
  <license>new BSD License (Please read the source code comments of this plugin)</license>
  <license lang="ja">修正BSDライセンス (ソースコードのコメントを参照してください)</license>
  <updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/auto-focus-frame.js</updateURL>
  <minVersion>2.3pre</minVersion>
  <maxVersion>2.3pre</maxVersion>
  <detail><![CDATA[
    == Usage ==
      Only install.
  ]]></detail>
  <detail lang="ja"><![CDATA[
    == Usage ==
      インストールするだけ
      一番面積の大きいフレームをフォーカスします
  ]]></detail>
</VimperatorPlugin>;
// }}}

(function () {

  function onLoad () {
    if (!(window.content.document instanceof HTMLDocument) || (content.frames.length <= 1))
      return;

    let targetFrames = [
      frame
      for (frame in util.Array.iterValues(content.frames))
      if (frame.frameElement instanceof HTMLFrameElement)
    ];

    let [maxSize, maxFrame] = [-1, null];
    targetFrames.forEach(function(frame) {
      if (frame.scrollMaxX <= 0 && frame.scrollMaxY <= 0)
        return;
      let size = frame.innerWidth * frame.innerHeight;
      if (maxSize < size)
        [maxSize, maxFrame] = [size, frame];
    });
    if (maxFrame)
      maxFrame.focus();
  }

  getBrowser().addEventListener("DOMContentLoaded", onLoad, true);

})();

// vim:sw=2 ts=2 et si fdm=marker:
<commit_msg>pentadactyl: Fix auto-focus-frame plugin<commit_after>/* NEW BSD LICENSE {{{
Copyright (c) 2009, anekos.
All rights reserved.

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

    1. Redistributions of source code must retain the above copyright notice,
       this list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. The names of the authors may not be used to endorse or promote products
       derived from this software without specific prior written permission.

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

###################################################################################
# http://sourceforge.jp/projects/opensource/wiki/licenses%2Fnew_BSD_license       #
# に参考になる日本語訳がありますが、有効なのは上記英文となります。                #
###################################################################################

}}} */

// PLUGIN_INFO {{{
let PLUGIN_INFO =
<VimperatorPlugin>
  <name>Auto focus frame</name>
  <description>Automatically focus to largest frame.</description>
  <description lang="ja">最も大きなフレームに自動的にフォーカスする。</description>
  <version>1.0.10</version>
  <author mail="anekos@snca.net" homepage="http://d.hatena.ne.jp/nokturnalmortum/">anekos</author>
  <license>new BSD License (Please read the source code comments of this plugin)</license>
  <license lang="ja">修正BSDライセンス (ソースコードのコメントを参照してください)</license>
  <updateURL>http://svn.coderepos.org/share/lang/javascript/vimperator-plugins/trunk/auto-focus-frame.js</updateURL>
  <minVersion>2.3pre</minVersion>
  <maxVersion>2.3pre</maxVersion>
  <detail><![CDATA[
    == Usage ==
      Only install.
  ]]></detail>
  <detail lang="ja"><![CDATA[
    == Usage ==
      インストールするだけ
      一番面積の大きいフレームをフォーカスします
  ]]></detail>
</VimperatorPlugin>;
// }}}

(function () {

  function onLoad () {
    if (!(window.content.document instanceof HTMLDocument) || (content.frames.length <= 1))
      return;

    let targetFrames = buffer.allFrames();

    let [maxSize, maxFrame] = [-1, null];
    targetFrames.forEach(function(frame) {
      if (frame.scrollMaxX <= 0 && frame.scrollMaxY <= 0)
        return;
      let size = frame.innerWidth * frame.innerHeight;
      if (maxSize < size)
        [maxSize, maxFrame] = [size, frame];
    });
    if (maxFrame)
      maxFrame.focus();
  }

  getBrowser().addEventListener("DOMContentLoaded", onLoad, true);

})();

// vim:sw=2 ts=2 et si fdm=marker:
<|endoftext|>


<commit_before>/*
 * Copyright 2011 The Closure Compiler Authors.
 *
 * 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 Externs for YouTube Player API for <iframe> Embeds.
 * @see http://code.google.com/apis/youtube/iframe_api_reference.html
 * @externs
 */

/** @return {undefined} */
var onYouTubePlayerAPIReady = function() {};

/** @return {undefined} */
window.onYouTubePlayerAPIReady = function() {};

/** @const */
var YT = {};

/**
 * @constructor
 * @param {(string|Element)} container
 * @param {Object.<string, *>} opts
 */
YT.Player = function(container, opts) {};

/** @typedef {!{
 *    videoId: string,
 *    startSeconds: (number|undefined),
 *    endSeconds: (number|undefined),
 *    suggestedQuality: (string|undefined),
 *  }} */
YT.Player.VideoIdParams;

/**
 * Loads the specified video's thumbnail and prepares the player to play the
 * video.
 * @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cueVideoById = function(
    videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and plays the specified video.
 * @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadVideoById = function(
    videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};

/** @typedef {!{
 *    mediaContentUrl: string,
 *    startSeconds: (number|undefined),
 *    endSeconds: (number|undefined),
 *    suggestedQuality: (string|undefined),
 *  }} */
YT.Player.MediaContentUrlParams;

/**
 * Loads the specified video's thumbnail and prepares the player to play the
 * video.
 * @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
 *     YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cueVideoByUrl = function(
    mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and plays the specified video.
 * @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
 *     YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadVideoByUrl = function(
    mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and cues a specified video in a playlist.
 *
 * @param {string|!Array<string>|!Object} playlistOrObject An object containing
 *     the parameters.  N.B. a String object will be treated as an object
 *     instead of as a string.  Otherwise, a string literal that is a playlist
 *     id (without the PL list prefix) or an array of video ids.
 * @param {number=} opt_index The index to begin playback at.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cuePlaylist = function(
    playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};

/**
 * @param {string|!Array<string>|!Object} playlistOrObject An object
 *     containing the parameters.  N.B. a String object will be treated as an
 *     object instead of as a string.  Otherwise, a string literal that is a
 *     playlist id (without the PL list prefix) or an array of video ids.
 * @param {number=} opt_index The index to begin playback at.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadPlaylist = function(
    playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};

/** @return {undefined} */
YT.Player.prototype.playVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.pauseVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.stopVideo = function() {};

/**
 * @param {number} seconds
 * @param {boolean} allowSeekAhead
 */
YT.Player.prototype.seekTo = function(seconds, allowSeekAhead) {};

/** @return {undefined} */
YT.Player.prototype.clearVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.nextVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.previousVideo = function() {};

/** @param {number} index */
YT.Player.prototype.playVideoAt = function(index) {};

/** @return {undefined} */
YT.Player.prototype.mute = function() {};

/** @return {undefined} */
YT.Player.prototype.unMute = function() {};

/** @return {boolean} */
YT.Player.prototype.isMuted = function() {};

/** @param {number} volume */
YT.Player.prototype.setVolume = function(volume) {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVolume = function() {};

/** @param {boolean} loopPlaylists */
YT.Player.prototype.setLoop = function(loopPlaylists) {};

/** @param {boolean} shufflePlaylist */
YT.Player.prototype.setShuffle = function(shufflePlaylist) {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoBytesLoaded = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoBytesTotal = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoLoadedFraction = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoStartBytes = function() {};

/**
 * @return {YT.PlayerState|number}
 * @nosideeffects
 */
YT.Player.prototype.getPlayerState = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getCurrentTime = function() {};

/**
 * @return {(undefined|string)}
 * @nosideeffects
 */
YT.Player.prototype.getPlaybackQuality = function() {};

/** @param {string} suggestedQuality */
YT.Player.prototype.setPlaybackQuality = function(suggestedQuality) {};

/**
 * @return {Array.<string>}
 * @nosideeffects
 */
YT.Player.prototype.getAvailableQualityLevels = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getDuration = function() {};

/**
 * @return {string}
 * @nosideeffects
 */
YT.Player.prototype.getVideoUrl = function() {};

/**
 * @return {string}
 * @nosideeffects
 */
YT.Player.prototype.getVideoEmbedCode = function() {};

/**
 * @return {Array.<string>}
 * @nosideeffects
 */
YT.Player.prototype.getPlaylist = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getPlaylistIndex = function() {};

/**
 * @param {string} eventName
 * @param {string} listenerName
 */
YT.Player.prototype.addEventListener = function(eventName, listenerName) {};

/** Destroys the player reference. */
YT.Player.prototype.destroy = function() {};

/**
 * @return {HTMLIFrameElement} The DOM node for the embedded iframe.
 * @nosideeffects
 */
YT.Player.prototype.getIframe = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getPlaybackRate = function() {};

/** @param {number} suggestedRate */
YT.Player.prototype.setPlaybackRate = function(suggestedRate) {};

/**
 * @return {!Array.<number>}
 * @nosideeffects
 */
YT.Player.prototype.getAvailablePlaybackRates = function() {};

/** @enum */
YT.PlayerState = {
  UNSTARTED: -1,
  ENDED: 0,
  PLAYING: 1,
  PAUSED: 2,
  BUFFERING: 3,
  CUED: 4
};

/**
 * @constructor
 * @private
 */
YT.Event = function() {};

/** @type {string|number|undefined} */
YT.Event.prototype.data;

/** @type {YT.Player} */
YT.Event.prototype.target = null;
<commit_msg>Adding the YouTube 360 video iframe API to google_youtube_iframe.js.<commit_after>/*
 * Copyright 2011 The Closure Compiler Authors.
 *
 * 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 Externs for YouTube Player API for <iframe> Embeds.
 * @see http://code.google.com/apis/youtube/iframe_api_reference.html
 * @externs
 */

/** @return {undefined} */
var onYouTubePlayerAPIReady = function() {};

/** @return {undefined} */
window.onYouTubePlayerAPIReady = function() {};

/** @const */
var YT = {};

/**
 * @constructor
 * @param {(string|Element)} container
 * @param {Object.<string, *>} opts
 */
YT.Player = function(container, opts) {};

/** @typedef {!{
 *    videoId: string,
 *    startSeconds: (number|undefined),
 *    endSeconds: (number|undefined),
 *    suggestedQuality: (string|undefined),
 *  }} */
YT.Player.VideoIdParams;

/**
 * Loads the specified video's thumbnail and prepares the player to play the
 * video.
 * @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cueVideoById = function(
    videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and plays the specified video.
 * @param {!YT.Player.VideoIdParams|string} videoIdOrObject YouTube Video ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadVideoById = function(
    videoIdOrObject, opt_startSeconds, opt_suggestedQuality) {};

/** @typedef {!{
 *    mediaContentUrl: string,
 *    startSeconds: (number|undefined),
 *    endSeconds: (number|undefined),
 *    suggestedQuality: (string|undefined),
 *  }} */
YT.Player.MediaContentUrlParams;

/**
 * Loads the specified video's thumbnail and prepares the player to play the
 * video.
 * @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
 *     YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cueVideoByUrl = function(
    mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and plays the specified video.
 * @param {!YT.Player.MediaContentUrlParams|string} mediaContentUrlOrObject
 *     YouTube player URL in the format http://www.youtube.com/v/VIDEO_ID or
 *     parameters object.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadVideoByUrl = function(
    mediaContentUrlOrObject, opt_startSeconds, opt_suggestedQuality) {};

/**
 * Loads and cues a specified video in a playlist.
 *
 * @param {string|!Array<string>|!Object} playlistOrObject An object containing
 *     the parameters.  N.B. a String object will be treated as an object
 *     instead of as a string.  Otherwise, a string literal that is a playlist
 *     id (without the PL list prefix) or an array of video ids.
 * @param {number=} opt_index The index to begin playback at.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.cuePlaylist = function(
    playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};

/**
 * @param {string|!Array<string>|!Object} playlistOrObject An object
 *     containing the parameters.  N.B. a String object will be treated as an
 *     object instead of as a string.  Otherwise, a string literal that is a
 *     playlist id (without the PL list prefix) or an array of video ids.
 * @param {number=} opt_index The index to begin playback at.
 * @param {number=} opt_startSeconds Float/integer that specifies the time
 *     from which the video should start playing.
 * @param {string=} opt_suggestedQuality The suggested playback quality for
 *     the video.
 */
YT.Player.prototype.loadPlaylist = function(
    playlistOrObject, opt_index, opt_startSeconds, opt_suggestedQuality) {};

/** @return {undefined} */
YT.Player.prototype.playVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.pauseVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.stopVideo = function() {};

/**
 * @param {number} seconds
 * @param {boolean} allowSeekAhead
 */
YT.Player.prototype.seekTo = function(seconds, allowSeekAhead) {};

/** @return {undefined} */
YT.Player.prototype.clearVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.nextVideo = function() {};

/** @return {undefined} */
YT.Player.prototype.previousVideo = function() {};

/** @param {number} index */
YT.Player.prototype.playVideoAt = function(index) {};

/** @return {undefined} */
YT.Player.prototype.mute = function() {};

/** @return {undefined} */
YT.Player.prototype.unMute = function() {};

/** @return {boolean} */
YT.Player.prototype.isMuted = function() {};

/** @param {number} volume */
YT.Player.prototype.setVolume = function(volume) {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVolume = function() {};

/** @param {boolean} loopPlaylists */
YT.Player.prototype.setLoop = function(loopPlaylists) {};

/** @param {boolean} shufflePlaylist */
YT.Player.prototype.setShuffle = function(shufflePlaylist) {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoBytesLoaded = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoBytesTotal = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoLoadedFraction = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getVideoStartBytes = function() {};

/**
 * @return {YT.PlayerState|number}
 * @nosideeffects
 */
YT.Player.prototype.getPlayerState = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getCurrentTime = function() {};

/**
 * @return {(undefined|string)}
 * @nosideeffects
 */
YT.Player.prototype.getPlaybackQuality = function() {};

/** @param {string} suggestedQuality */
YT.Player.prototype.setPlaybackQuality = function(suggestedQuality) {};

/**
 * @return {Array.<string>}
 * @nosideeffects
 */
YT.Player.prototype.getAvailableQualityLevels = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getDuration = function() {};

/**
 * @return {string}
 * @nosideeffects
 */
YT.Player.prototype.getVideoUrl = function() {};

/**
 * @return {string}
 * @nosideeffects
 */
YT.Player.prototype.getVideoEmbedCode = function() {};

/**
 * @return {Array.<string>}
 * @nosideeffects
 */
YT.Player.prototype.getPlaylist = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getPlaylistIndex = function() {};

/**
 * @param {string} eventName
 * @param {string} listenerName
 */
YT.Player.prototype.addEventListener = function(eventName, listenerName) {};

/** Destroys the player reference. */
YT.Player.prototype.destroy = function() {};

/**
 * @return {HTMLIFrameElement} The DOM node for the embedded iframe.
 * @nosideeffects
 */
YT.Player.prototype.getIframe = function() {};

/**
 * @return {number}
 * @nosideeffects
 */
YT.Player.prototype.getPlaybackRate = function() {};

/** @param {number} suggestedRate */
YT.Player.prototype.setPlaybackRate = function(suggestedRate) {};

/**
 * @return {!Array.<number>}
 * @nosideeffects
 */
YT.Player.prototype.getAvailablePlaybackRates = function() {};

/**
 * Gets the spherical video config object, with information about the viewport
 * headings and zoom level.
 *
 * @return {{yaw: (undefined|number), pitch: (undefined|number),
 *     roll: (undefined|number), fov: (undefined|number)}}
 */
YT.Player.prototype.getSphericalProperties = function() {};

/**
 * Sets the spherical video config object. The call will be No-Op for non-360
 * videos, and will change the view port according to the input for 360 videos.
 *
 * @param {?{yaw: (undefined|number), pitch: (undefined|number),
 *     roll: (undefined|number), fov: (undefined|number),
 *     enableOrientationSensor: (undefined|boolean)}} option
 */
YT.Player.prototype.setSphericalProperties = function(option) {};

/** @enum */
YT.PlayerState = {
  UNSTARTED: -1,
  ENDED: 0,
  PLAYING: 1,
  PAUSED: 2,
  BUFFERING: 3,
  CUED: 4
};

/**
 * @constructor
 * @private
 */
YT.Event = function() {};

/** @type {string|number|undefined} */
YT.Event.prototype.data;

/** @type {YT.Player} */
YT.Event.prototype.target = null;
<|endoftext|>


<commit_before>// u = The current user's ID
function _(u) {
	var loc = [1171, 1841, 2517, 3101, 4819, 5233, 6311, 7977, 8103, 9377, 1000]
	var ret =
		(loc[10] + u % loc[10]).toString() +
		((9999999999 - Math.floor(new Date().getTime() / loc[10]) - u) * loc[u % 10]).toString() +
		cN() + cN() + cN() + cN();
	return ret;
}

function cN() {
	return Math.floor(Math.random() * 10).toString();
}
<commit_msg>No need for this anymore<commit_after><|endoftext|>


<commit_before>"use strict";

const _ = require('underscore');
const Timeline = require('pebble-api').Timeline;
const moment = require('moment');

const flavours = require('./pin-flavours');
const debug = require('./debug');
const config = require('./config');

const timeline = new Timeline();

function generateID(userJourney) {
    // The ID is always deterministic so the same journey on the same day will always match
    return [userJourney.from, userJourney.to, moment(userJourney.date).format('YYYY-MM-DD')].join('-');
}

function timeOfDay(date) {
    const hr = date.getHours();

    if (hr < 12) {
        return 'morning';
    } else if (hr < 18) {
        return 'afternoon';
    } else {
        return 'evening';
    }
}

function generatePin(userJourney, oldStatus) {
    const flavourText = flavours.get(userJourney.status);

    const layout = _.extend(flavourText, {
        type: Timeline.Pin.LayoutType.GENERIC_PIN,
        title: `Your ${timeOfDay(userJourney.date)} commute`
    });

    const pin = {
        id: generateID(userJourney),
        time: userJourney.date,
        layout: layout
    };

    if (userJourney.createdAt.getTime() !== userJourney.updatedAt.getTime()) {
        pin.updateNotification = {
            time: userJourney.updatedAt,
            layout: layout
        };
    }

    return new Timeline.Pin(pin);
}

function send(user, userJourney, oldStatus) {
    if (config.environment === 'test') {
        console.log(`Timeline: TEST Would have sent pin to ${user._id} for ${userJourney.from} - ${userJourney.to}`);
        return Promise.resolve();
    }

    return new Promise(function (resolve, reject) {
        try {
            const pin = generatePin(userJourney, oldStatus);
            debug(`Timeline: Sending pin ${pin.id} to ${user._id} for ${userJourney.from} - ${userJourney.to}`);
            debug(JSON.stringify(pin));
            timeline.sendUserPin(user._id, pin, (err) => {
                if (err) {
                    reject(err);
                } else {
                    debug(`Timeline: Sent pin`);
                    resolve();
                }
            });
        } catch (err) {
            reject(err);
        }
    });
}

function remove(user, userJourney) {
    return new Promise(function (resolve, reject) {
        try {
            // This is annoying, but we actually have to generate the full pin again
            // to delete it, even though only the ID is required
            const pin = generatePin(userJourney);
            debug(`Timeline: Removing pin ${pin.id} for ${user._id} for ${userJourney.from} - ${userJourney.to}`);
            timeline.deleteUserPin(user._id, pin, (err) => {
                if (err) {
                    reject(err);
                } else {
                    debug(`Timeline: Removed pin`);
                    resolve();
                }
            });
        } catch (err) {
            reject(err);
        }
    });
}

module.exports = {
    send,
    remove
};
<commit_msg>Include last time updated in pin layout<commit_after>"use strict";

const _ = require('underscore');
const Timeline = require('pebble-api').Timeline;
const moment = require('moment');

const flavours = require('./pin-flavours');
const debug = require('./debug');
const config = require('./config');

const timeline = new Timeline();

function generateID(userJourney) {
    // The ID is always deterministic so the same journey on the same day will always match
    return [userJourney.from, userJourney.to, moment(userJourney.date).format('YYYY-MM-DD')].join('-');
}

function timeOfDay(date) {
    const hr = date.getHours();

    if (hr < 12) {
        return 'morning';
    } else if (hr < 18) {
        return 'afternoon';
    } else {
        return 'evening';
    }
}

function generatePin(userJourney, oldStatus) {
    const flavourText = flavours.get(userJourney.status);

    const layout = _.extend(flavourText, {
        type: Timeline.Pin.LayoutType.GENERIC_PIN,
        title: `Your ${timeOfDay(userJourney.date)} commute`,
        lastUpdated: userJourney.updatedAt,
    });

    const pin = {
        id: generateID(userJourney),
        time: userJourney.date,
        layout: layout
    };

    if (userJourney.createdAt.getTime() !== userJourney.updatedAt.getTime()) {
        pin.updateNotification = {
            time: userJourney.updatedAt,
            layout: layout
        };
    }

    return new Timeline.Pin(pin);
}

function send(user, userJourney, oldStatus) {
    if (config.environment === 'test') {
        console.log(`Timeline: TEST Would have sent pin to ${user._id} for ${userJourney.from} - ${userJourney.to}`);
        return Promise.resolve();
    }

    return new Promise(function (resolve, reject) {
        try {
            const pin = generatePin(userJourney, oldStatus);
            debug(`Timeline: Sending pin ${pin.id} to ${user._id} for ${userJourney.from} - ${userJourney.to}`);
            debug(JSON.stringify(pin));
            timeline.sendUserPin(user._id, pin, (err) => {
                if (err) {
                    reject(err);
                } else {
                    debug(`Timeline: Sent pin`);
                    resolve();
                }
            });
        } catch (err) {
            reject(err);
        }
    });
}

function remove(user, userJourney) {
    return new Promise(function (resolve, reject) {
        try {
            // This is annoying, but we actually have to generate the full pin again
            // to delete it, even though only the ID is required
            const pin = generatePin(userJourney);
            debug(`Timeline: Removing pin ${pin.id} for ${user._id} for ${userJourney.from} - ${userJourney.to}`);
            timeline.deleteUserPin(user._id, pin, (err) => {
                if (err) {
                    reject(err);
                } else {
                    debug(`Timeline: Removed pin`);
                    resolve();
                }
            });
        } catch (err) {
            reject(err);
        }
    });
}

module.exports = {
    send,
    remove
};
<|endoftext|>


<commit_before>//
// Host Page Code
//
// This section is for managing the selection form elements and posting of
// Privly-type links to those form elements.
//
// The script follows this flow of events
// 1. When the user right clicks the page it fires the contextmenu event
// 2. The script records the target node
// 3. If the user selects the context menu for Privly, background.js
// sends a message to this script to freeze posting. This prevents future
// right clicks from changing the destination node.
// 4. Finally, background.js will message this scrit the Privly URL
// to drop into the original form element.
//

// Where the Privly URL will be placed is remembered by the contextmenu event
var privlyUrlReceiptNode = undefined;
document.addEventListener( "contextmenu", function(evt) {
  if (!pendingPost) {
    privlyUrlReceiptNode = evt.target;
  }
})

// Variable used to indicate whether there is a pending pending operation
var pendingPost = false;

/**
 * Place the URL into the host page and fire
 * the appropriate events to get the host page
 * to process the link.
 *
 * @param request json the JSON document sent as part of the message.
 * @param sender tab the tab sending the message.
 * @param sendResponse function the response function is the
 * callback defined by the function sending the message here
 *
 */
function receiveURL(request, sender, sendResponse) {

  // Focus the DOM Node, then fire keydown and keypress events
  privlyUrlReceiptNode.focus();
  var keydownEvent = document.createEvent("KeyboardEvent");
  keydownEvent.initKeyboardEvent('keydown', true, true, window, 0,
                          false, 0, false, 0, 0);
  privlyUrlReceiptNode.dispatchEvent(keydownEvent);
  var keypressEvent = document.createEvent("KeyboardEvent");
  keypressEvent.initKeyboardEvent('keypress', true, true, window, 0,
                          false, 0, false, 0, 0);
  privlyUrlReceiptNode.dispatchEvent(keypressEvent);

  // Some sites need time to execute form initialization
  // callbacks following focus and keydown events.
  // One example includes Facebook.com's wall update
  // form and message page.
  setTimeout(function(){

    privlyUrlReceiptNode.value = request.privlyUrl;
    privlyUrlReceiptNode.textContent = request.privlyUrl;

    var event = document.createEvent("KeyboardEvent");
    event.initKeyboardEvent('keyup', true, true, window,
                            0, false, 0, false, 0, 0);
    privlyUrlReceiptNode.dispatchEvent(event);

    privlyUrlReceiptNode = undefined;
    pendingPost = false;
  },500);
}

// Accepts Privly URL from the background.js script
chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {

    // drop the Privly URL into the form element
    if ( request.privlyUrl !== undefined &&
         privlyUrlReceiptNode !== undefined &&
         pendingPost) {
      receiveURL(request, sender, sendResponse);
    }

    // It will not change the posting location until the last post completes
    // background.js can cancel the last pendingPost by messaging
    // pendingPost: false
    if(request.pendingPost !== undefined) {
      pendingPost = request.pendingPost;
    }
  });

//
// Posting Application Code
//
// For more information:
// https://github.com/privly/privly-organization/wiki/Viewing-and-Posting-Applications
//

// Send the extension the URL for posting to the host page
// This event listener is only used by applications that have been opened by
// background.js to generate a Privly URL.
document.addEventListener('PrivlyUrlEvent', function(evt) {
  chrome.extension.sendMessage(
    {privlyUrl: evt.target.getAttribute("privlyUrl")},
    function(response) {});
});

// Send the secret token to the extension level so that it can send
// messages to the web page.
document.addEventListener("PrivlyMessageSecretEvent", function(evt) {
  var secret = evt.target.getAttribute("privlyMessageSecret");
  chrome.extension.sendMessage(
    {messageSecret: secret},
    function(response) {
      document.defaultView.postMessage(response.hostPageString, "*");
    });
});
<commit_msg>fixed some comments<commit_after>//
// Host Page Code
//
// This section is for managing the selection form elements and posting of
// Privly-type links to those form elements.
//
// The script follows this flow of events
// 1. When the user right clicks the page it fires the contextmenu event
// 2. The script records the target node
// 3. If the user selects the context menu for Privly, background.js
// sends a message to this script to freeze posting. This prevents future
// right clicks from changing the destination node.
// 4. Finally, background.js will message this script the Privly URL
// to drop into the original form element.
//

// Where the Privly URL will be placed is remembered by the contextmenu event
var privlyUrlReceiptNode = undefined;
document.addEventListener( "contextmenu", function(evt) {
  if (!pendingPost) {
    privlyUrlReceiptNode = evt.target;
  }
});

// Variable used to indicate whether there is a pending pending operation
var pendingPost = false;

/**
 * Place the URL into the host page and fire
 * the appropriate events to get the host page
 * to process the link.
 *
 * @param request json the JSON document sent as part of the message.
 * @param sender tab the tab sending the message.
 * @param sendResponse function the response function is the
 * callback defined by the function sending the message here
 *
 */
function receiveURL(request, sender, sendResponse) {

  // Focus the DOM Node, then fire keydown and keypress events
  privlyUrlReceiptNode.focus();
  var keydownEvent = document.createEvent("KeyboardEvent");
  keydownEvent.initKeyboardEvent('keydown', true, true, window, 0,
                          false, 0, false, 0, 0);
  privlyUrlReceiptNode.dispatchEvent(keydownEvent);
  var keypressEvent = document.createEvent("KeyboardEvent");
  keypressEvent.initKeyboardEvent('keypress', true, true, window, 0,
                          false, 0, false, 0, 0);
  privlyUrlReceiptNode.dispatchEvent(keypressEvent);

  // Some sites need time to execute form initialization
  // callbacks following focus and keydown events.
  // One example includes Facebook.com's wall update
  // form and message page.
  setTimeout(function(){

    privlyUrlReceiptNode.value = request.privlyUrl;
    privlyUrlReceiptNode.textContent = request.privlyUrl;

    var event = document.createEvent("KeyboardEvent");
    event.initKeyboardEvent('keyup', true, true, window,
                            0, false, 0, false, 0, 0);
    privlyUrlReceiptNode.dispatchEvent(event);

    privlyUrlReceiptNode = undefined;
    pendingPost = false;
  },500);
}

// Accepts Privly URL from the background.js script
chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {

    // drop the Privly URL into the form element
    if ( request.privlyUrl !== undefined &&
         privlyUrlReceiptNode !== undefined &&
         pendingPost) {
      receiveURL(request, sender, sendResponse);
    }

    // It will not change the posting location until the last post completes
    // background.js can cancel the last pendingPost by messaging
    // pendingPost: false
    if(request.pendingPost !== undefined) {
      pendingPost = request.pendingPost;
    }
  });

//
// Posting Application Code
//
// For more information:
// https://github.com/privly/privly-organization/wiki/Posting-Application
//

// Send the extension the URL for posting to the host page
// This event listener is only used by applications that have been opened by
// background.js to generate a Privly URL.
document.addEventListener('PrivlyUrlEvent', function(evt) {
  chrome.extension.sendMessage(
    {privlyUrl: evt.target.getAttribute("privlyUrl")},
    function(response) {});
});

// Send the secret token to the extension level so that it can send
// messages to the web page. This allows the posting application to
// trust messages sent to it by the extension.
document.addEventListener("PrivlyMessageSecretEvent", function(evt) {
  var secret = evt.target.getAttribute("privlyMessageSecret");
  chrome.extension.sendMessage(
    {messageSecret: secret},
    function(response) {
      document.defaultView.postMessage(response.hostPageString, "*");
    });
});
<|endoftext|>


<commit_before>console.log('Loading Lambda Function (v1234)');

// include some required modules
// remove these if you don't need
var https = require('https');
var AWS = require('aws-sdk');
var async = require('async');

exports.handler = function(event, context) {
    // event ohject is passed to lambda function
    console.log(JSON.stringify(event, null, 4));

    // do some work and call context
    // to notify lambda about sucess of failure
    console.log("key1:", event.key1);
    if (true) {
        context.succeed("Yay :)");
    } else {
        context.fail("Nay :(")
    }
};
<commit_msg>fixed missing semicolon<commit_after>console.log('Loading Lambda Function (v1234)');

// include some required modules
// remove these if you don't need
var https = require('https');
var AWS = require('aws-sdk');
var async = require('async');

exports.handler = function(event, context) {
    // event ohject is passed to lambda function
    console.log(JSON.stringify(event, null, 4));

    // do some work and call context
    // to notify lambda about sucess of failure
    console.log("key1:", event.key1);
    if (true) {
        context.succeed("Yay :)");
    } else {
        context.fail("Nay :(");
    }
};
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { TouchableWithoutFeedback, TouchableNativeFeedback, TouchableOpacity, TouchableHighlight, StyleSheet, View, Platform, ActivityIndicator } from 'react-native'
import colors from '../config/colors'
import Text from '../text/Text'
import MaterialIcon from 'react-native-vector-icons/MaterialIcons'
import getIconType from '../helpers/getIconType'
import normalize from '../helpers/normalizeText'

let styles = {}

const log = () => {
  console.log('please attach method to this component')
}

const Button = ({
  Component,
  disabled,
  loading,
  loadingRight,
  activityIndicatorStyle,
  buttonStyle,
  borderRadius,
  title,
  onPress,
  delayLongPress,
  delayPressIn,
  delayPressOut,
  onLayout,
  onLongPress,
  onPressIn,
  onPressOut,
  hitSlop,
  activeOpacity,
  onHideUnderlay,
  onShowUnderlay,
  background,
  SelectableBackground,
  SelectableBackgroundBorderless,
  Ripple,
  icon,
  secondary,
  secondary2,
  secondary3,
  primary1,
  primary2,
  primary3,
  backgroundColor,
  color,
  fontSize,
  underlayColor,
  raised,
  textStyle,
  large,
  iconRight,
  fontWeight,
  fontFamily}) => {
  let iconElement
  if (icon) {
    let Icon
    if (!icon.type) {
      Icon = MaterialIcon
    } else {
      Icon = getIconType(icon.type)
    }
    iconElement = (
      <Icon
        color={icon.color || 'white'}
        size={icon.size || (large ? 26 : 18)}
        style={[
          iconRight ? styles.iconRight : styles.icon,
          icon.style && icon.style
        ]}
        name={icon.name} />
    )
  }
  let loadingElement;
  if(loading){
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || "white"}
        size={large && "large" || "small"}
      />
    )
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback
  }
  if (!Component) {
    Component = TouchableHighlight
  }
  return (
    <Component
      delayLongPress={delayLongPress}
      delayPressIn={delayPressIn}
      delayPressOut={delayPressOut}
      onLayout={onLayout}
      onLongPress={onLongPress}
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      activeOpacity={activeOpacity}
      onHideUnderlay={onHideUnderlay}
      onShowUnderlay={onShowUnderlay}
      background={background}
      SelectableBackground={SelectableBackground}
      SelectableBackgroundBorderless={SelectableBackgroundBorderless}
      Ripple={Ripple}
      hitSlop={hitSlop}
      underlayColor={underlayColor || 'transparent'}
      onPress={onPress || log}
      disabled={disabled || false}>
      <View
        style={[
          styles.button,
          secondary && {backgroundColor: colors.secondary},
          secondary2 && {backgroundColor: colors.secondary2},
          secondary3 && {backgroundColor: colors.secondary3},
          primary1 && {backgroundColor: colors.primary1},
          primary2 && {backgroundColor: colors.primary2},
          backgroundColor && {backgroundColor: backgroundColor},
          borderRadius && {borderRadius},
          buttonStyle && buttonStyle,
          raised && styles.raised,
          !large && styles.small,
          disabled && {backgroundColor: colors.disabled}
        ]}
        >
        {
          icon && !iconRight && iconElement
        }
        {
          loading && !loadingRight && loadingElement
        }
        <Text
          style={[
            styles.text,
            color && {color},
            fontSize && {fontSize},
            !large && styles.smallFont,
            textStyle && textStyle,
            fontWeight && {fontWeight},
            fontFamily && {fontFamily}
          ]}>
          {title}
        </Text>
        {
          loading && loadingRight && loadingElement
        }
        {
          icon && iconRight && iconElement
        }
      </View>
    </Component>
  )
}

Button.propTypes = {
  buttonStyle: PropTypes.any,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  primary3: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.number,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: PropTypes.any,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: PropTypes.any,
  loadingRight: PropTypes.bool
}

styles = StyleSheet.create({
  button: {
    padding: 19,
    marginLeft: 15,
    marginRight: 15,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row'
  },
  text: {
    color: 'white',
    fontSize: normalize(16)
  },
  icon: {
    marginRight: 10
  },
  iconRight: {
    marginLeft: 10
  },
  small: {
    padding: 12
  },
  smallFont: {
    fontSize: normalize(14)
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: {height: 1, width: 1},
        shadowOpacity: 1,
        shadowRadius: 1
      },
      android: {
        elevation: 2
      }
    })
  }
})

export default Button
<commit_msg>change fontSize proptype to accept any value<commit_after>import React, { PropTypes } from 'react'
import { TouchableWithoutFeedback, TouchableNativeFeedback, TouchableOpacity, TouchableHighlight, StyleSheet, View, Platform, ActivityIndicator } from 'react-native'
import colors from '../config/colors'
import Text from '../text/Text'
import MaterialIcon from 'react-native-vector-icons/MaterialIcons'
import getIconType from '../helpers/getIconType'
import normalize from '../helpers/normalizeText'

let styles = {}

const log = () => {
  console.log('please attach method to this component')
}

const Button = ({
  Component,
  disabled,
  loading,
  loadingRight,
  activityIndicatorStyle,
  buttonStyle,
  borderRadius,
  title,
  onPress,
  delayLongPress,
  delayPressIn,
  delayPressOut,
  onLayout,
  onLongPress,
  onPressIn,
  onPressOut,
  hitSlop,
  activeOpacity,
  onHideUnderlay,
  onShowUnderlay,
  background,
  SelectableBackground,
  SelectableBackgroundBorderless,
  Ripple,
  icon,
  secondary,
  secondary2,
  secondary3,
  primary1,
  primary2,
  primary3,
  backgroundColor,
  color,
  fontSize,
  underlayColor,
  raised,
  textStyle,
  large,
  iconRight,
  fontWeight,
  fontFamily}) => {
  let iconElement
  if (icon) {
    let Icon
    if (!icon.type) {
      Icon = MaterialIcon
    } else {
      Icon = getIconType(icon.type)
    }
    iconElement = (
      <Icon
        color={icon.color || 'white'}
        size={icon.size || (large ? 26 : 18)}
        style={[
          iconRight ? styles.iconRight : styles.icon,
          icon.style && icon.style
        ]}
        name={icon.name} />
    )
  }
  let loadingElement;
  if(loading){
    loadingElement = (
      <ActivityIndicator
        animating={true}
        style={[styles.activityIndicatorStyle, activityIndicatorStyle]}
        color={color || "white"}
        size={large && "large" || "small"}
      />
    )
  }
  if (!Component && Platform.OS === 'ios') {
    Component = TouchableHighlight
  }
  if (!Component && Platform.OS === 'android') {
    Component = TouchableNativeFeedback
  }
  if (!Component) {
    Component = TouchableHighlight
  }
  return (
    <Component
      delayLongPress={delayLongPress}
      delayPressIn={delayPressIn}
      delayPressOut={delayPressOut}
      onLayout={onLayout}
      onLongPress={onLongPress}
      onPressIn={onPressIn}
      onPressOut={onPressOut}
      activeOpacity={activeOpacity}
      onHideUnderlay={onHideUnderlay}
      onShowUnderlay={onShowUnderlay}
      background={background}
      SelectableBackground={SelectableBackground}
      SelectableBackgroundBorderless={SelectableBackgroundBorderless}
      Ripple={Ripple}
      hitSlop={hitSlop}
      underlayColor={underlayColor || 'transparent'}
      onPress={onPress || log}
      disabled={disabled || false}>
      <View
        style={[
          styles.button,
          secondary && {backgroundColor: colors.secondary},
          secondary2 && {backgroundColor: colors.secondary2},
          secondary3 && {backgroundColor: colors.secondary3},
          primary1 && {backgroundColor: colors.primary1},
          primary2 && {backgroundColor: colors.primary2},
          backgroundColor && {backgroundColor: backgroundColor},
          borderRadius && {borderRadius},
          buttonStyle && buttonStyle,
          raised && styles.raised,
          !large && styles.small,
          disabled && {backgroundColor: colors.disabled}
        ]}
        >
        {
          icon && !iconRight && iconElement
        }
        {
          loading && !loadingRight && loadingElement
        }
        <Text
          style={[
            styles.text,
            color && {color},
            fontSize && {fontSize},
            !large && styles.smallFont,
            textStyle && textStyle,
            fontWeight && {fontWeight},
            fontFamily && {fontFamily}
          ]}>
          {title}
        </Text>
        {
          loading && loadingRight && loadingElement
        }
        {
          icon && iconRight && iconElement
        }
      </View>
    </Component>
  )
}

Button.propTypes = {
  buttonStyle: PropTypes.any,
  title: PropTypes.string,
  onPress: PropTypes.any,
  icon: PropTypes.object,
  secondary: PropTypes.bool,
  secondary2: PropTypes.bool,
  secondary3: PropTypes.bool,
  primary1: PropTypes.bool,
  primary2: PropTypes.bool,
  primary3: PropTypes.bool,
  backgroundColor: PropTypes.string,
  color: PropTypes.string,
  fontSize: PropTypes.any,
  underlayColor: PropTypes.string,
  raised: PropTypes.bool,
  textStyle: PropTypes.any,
  disabled: PropTypes.bool,
  loading: PropTypes.bool,
  activityIndicatorStyle: PropTypes.any,
  loadingRight: PropTypes.bool
}

styles = StyleSheet.create({
  button: {
    padding: 19,
    marginLeft: 15,
    marginRight: 15,
    backgroundColor: colors.primary,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row'
  },
  text: {
    color: 'white',
    fontSize: normalize(16)
  },
  icon: {
    marginRight: 10
  },
  iconRight: {
    marginLeft: 10
  },
  small: {
    padding: 12
  },
  smallFont: {
    fontSize: normalize(14)
  },
  activityIndicatorStyle: {
    marginHorizontal: 10,
    height: 0
  },
  raised: {
    ...Platform.select({
      ios: {
        shadowColor: 'rgba(0,0,0, .4)',
        shadowOffset: {height: 1, width: 1},
        shadowOpacity: 1,
        shadowRadius: 1
      },
      android: {
        elevation: 2
      }
    })
  }
})

export default Button
<|endoftext|>


<commit_before>
var fs = require('fs');
var file = 'boba-config.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }
  var jsonConfig = JSON.parse(data);
  addBoba(jsonConfig);
})

var BobaParserTools = require('./BobaParserTools');
var NGDependencyGraph = require('./NGDependencyGraph');
function addBoba(config) {
	var jsonConfig = config;
	if (!jsonConfig) {
		throw ('Boba needs a config to run.');
	}

	if (!jsonConfig.folder && !jsonConfig.files) {
		throw ('Add files or folder option to your config');
	}

	if (jsonConfig.folder && jsonConfig.files) {
		throw ('Both files and folder options cannot be specified.  Choose one.');
	}

	if (!jsonConfig.modules || jsonConfig.modules.length == 0) {
		throw ('Specify one or more angular modules.');
	}

	if (jsonConfig.folder) {
		BobaParserTools.parseFolder(jsonConfig.folder).then(function(dependencies) {

			var g = new NGDependencyGraph(dependencies, {});
			var files = g.getBundleFiles(jsonConfig.modules[0]);
			console.log(files);
			return files;
		})

	}
}
<commit_msg>rename config<commit_after>
var fs = require('fs');
var file = 'boba-config.json';

fs.readFile(file, 'utf8', function (err, data) {
  if (err) {
    console.log('Error: ' + err);
    return;
  }
  var jsonConfig = JSON.parse(data);
  addBoba(jsonConfig);
})

var BobaParserTools = require('./BobaParserTools');
var NGDependencyGraph = require('./data/NGDependencyGraph');
function addBoba(config) {
	if (!config) {
		throw ('Boba needs a config to run.');
	}

	if (!config.folder && !config.files) {
		throw ('Add files or folder option to your config');
	}

	if (config.folder && config.files) {
		throw ('Both files and folder options cannot be specified.  Choose one.');
	}

	if (!config.modules || config.modules.length == 0) {
		throw ('Specify one or more angular modules.');
	}

	if (config.folder) {
		BobaParserTools.parseFolder(config.folder).then(function(dependencies) {

			var g = new NGDependencyGraph(dependencies, {});
			var files = g.getBundleFiles(config.modules[0]);
			console.log(files);
			return files;
		})

	}
}
<|endoftext|>


<commit_before>$(document).ready(function () {
    var path = window.location.pathname;
    var splitPath = path.split('/');
    splitPath = splitPath.filter(function (v) { return v !== '' });
    if (splitPath.length <= 2)
    {
        $("#search-form").hide();
    }
});

search = {
    //Keeps track of whether a search is ongoing.
    //We only want to send one query at a time.
    isSearching: false,
    //Retains the state of the most recent query.
    //When we're done searching, we check the text box to see
    //if the query has changed.
    lastQuery: "",
    beginSearch: function () {
        if (search.isSearching)
            return;
        var query = $("#search-box").val();
        //If there's no query, just clear everything
        if (query == "") {
            search.clearSearch();
            return;
        }
        search.lastQuery = query;
        //Split path, removing empty entries
        var path = window.location.pathname;
        var splitPath = path.split('/');
        splitPath = splitPath.filter(function (v) { return v !== '' });

        //Only search if we're in a repository
        if (splitPath.length > 2) {
            var username = splitPath[1];
            var repository = splitPath[2];

            search.searchRepository(username, repository, query);
        }

        return false;
    },

    searchRepository: function (username, repository, query) {
        data = JSON.stringify({
            "username": username,
            "repository": repository,
            "query": query
        });

        $.ajax({
            type: "POST",
            url: "/Search/Repository/",
            //TODO: If anyone knows a better way to do this, please share it.
            //My Javascript is not strong...
            data: "username=" + username + "&repository=" + repository + "&query=" + query,
            success: search.handleSuccess,
            error: search.handleError
        });
    },

    handleError: function (e) {
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    handleSuccess: function (results) {
        $("#tree-view").hide();
        //If we can't find any results, tell the user.
        if (results.length == 0) {
            $("#search-results").hide();
            $("#no-results").show();
        }
        else {
            $("#no-results").hide();
            $("#search-results").show();
            var htmlResults = search.buildResults(results);
            $("#search-results").empty().append(htmlResults);
            $("#search-results a").on("click", search.handlSearchClick);
        }
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    buildResults: function (results) {
        var htmlResults = "";
        for (var i = 0; i < results.length; i++) {
            var searchResult = results[i];
            var lineNumber = searchResult["LineNumber"];
            var link = "/Browse/" + searchResult["Path"] + "#" + lineNumber;
            html = "";
            html += "";
            html += ""
            html += searchResult["Name"];
            html += "";
            html += ""
            html += searchResult["FullName"];
            html += "";
            html += "";

            htmlResults += html;
        }
        return htmlResults;
    },

    //After searching, we need to check to see if the user has typed
    //any additional characters into search while we were waiting
    //for the server
    checkIfSearchTextChanged: function () {
        var currentQuery = $("#search-box").val();
        if (currentQuery != search.lastQuery)
            search.beginSearch();
    },

    clearSearch: function () {
        $("#search-results").hide();
        $("#no-results").hide();
        $("#tree-view").show();
    },

    handlSearchClick: function (ex) {
        //Stop navigation. We'll take it from here.
        ex.preventDefault();

        var url = ex.currentTarget.href;
        var host = ex.currentTarget.host;

        var idx = url.indexOf(host) + host.length;
        var relativeUrl = url.substr(idx);
        History.pushState({ state: 1 }, "state1", relativeUrl);
    }
}

$("#search-box").keyup(function () {
    search.beginSearch();
});

<commit_msg>Allow browser to navigate when we're already at the correct page.<commit_after>$(document).ready(function () {
    var path = window.location.pathname;
    var splitPath = path.split('/');
    splitPath = splitPath.filter(function (v) { return v !== '' });
    if (splitPath.length <= 2)
    {
        $("#search-form").hide();
    }
});

search = {
    //Keeps track of whether a search is ongoing.
    //We only want to send one query at a time.
    isSearching: false,
    //Retains the state of the most recent query.
    //When we're done searching, we check the text box to see
    //if the query has changed.
    lastQuery: "",
    beginSearch: function () {
        if (search.isSearching)
            return;
        var query = $("#search-box").val();
        //If there's no query, just clear everything
        if (query == "") {
            search.clearSearch();
            return;
        }
        search.lastQuery = query;
        //Split path, removing empty entries
        var path = window.location.pathname;
        var splitPath = path.split('/');
        splitPath = splitPath.filter(function (v) { return v !== '' });

        //Only search if we're in a repository
        if (splitPath.length > 2) {
            var username = splitPath[1];
            var repository = splitPath[2];

            search.searchRepository(username, repository, query);
        }

        return false;
    },

    searchRepository: function (username, repository, query) {
        data = JSON.stringify({
            "username": username,
            "repository": repository,
            "query": query
        });

        $.ajax({
            type: "POST",
            url: "/Search/Repository/",
            //TODO: If anyone knows a better way to do this, please share it.
            //My Javascript is not strong...
            data: "username=" + username + "&repository=" + repository + "&query=" + query,
            success: search.handleSuccess,
            error: search.handleError
        });
    },

    handleError: function (e) {
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    handleSuccess: function (results) {
        $("#tree-view").hide();
        //If we can't find any results, tell the user.
        if (results.length == 0) {
            $("#search-results").hide();
            $("#no-results").show();
        }
        else {
            $("#no-results").hide();
            $("#search-results").show();
            var htmlResults = search.buildResults(results);
            $("#search-results").empty().append(htmlResults);
            $("#search-results a").click(search.handlSearchClick);
        }
        search.isSearching = false;
        search.checkIfSearchTextChanged();
    },

    buildResults: function (results) {
        var htmlResults = "";
        for (var i = 0; i < results.length; i++) {
            var searchResult = results[i];
            var lineNumber = searchResult["LineNumber"];
            var link = "/Browse/" + searchResult["Path"] + "#" + lineNumber;
            html = "";
            html += "";
            html += ""
            html += searchResult["Name"];
            html += "";
            html += ""
            html += searchResult["FullName"];
            html += "";
            html += "";

            htmlResults += html;
        }
        return htmlResults;
    },

    //After searching, we need to check to see if the user has typed
    //any additional characters into search while we were waiting
    //for the server
    checkIfSearchTextChanged: function () {
        var currentQuery = $("#search-box").val();
        if (currentQuery != search.lastQuery)
            search.beginSearch();
    },

    clearSearch: function () {
        $("#search-results").hide();
        $("#no-results").hide();
        $("#tree-view").show();
    },

    handlSearchClick: function (ex) {
        //If we're already on the page, allow the browser to scroll.
        var currentPathName = window.location.pathname;
        var newPathName = ex.currentTarget.pathname;
        if (currentPathName == newPathName)
            return;

        //Stop navigation. We'll take it from here.
        ex.preventDefault();

        var url = ex.currentTarget.href;
        var host = ex.currentTarget.host;

        var idx = url.indexOf(host) + host.length;
        var relativeUrl = url.substr(idx);
        var hashidx = relativeUrl.indexOf("#");
        var newUrl = relativeUrl.substr(0, hashidx);
        window.History.pushState(null, null, newUrl);
        window.History.replaceState(null, null, relativeUrl);

    }
}

// Bind to StateChange Event
$(document).ready(function () {
    window.History.Adapter.bind(window, 'statechange', handleStateChange);
});

function handleStateChange() {
    //TODO
}

$("#search-box").keyup(function () {
    search.beginSearch();
});

<|endoftext|>


<commit_before>///import core
///import commands/inserthtml.js
///commands 插入公式
///commandsName  formula
///commandsTitle  插入公式
///commandsDialog  dialogs\formula\formula.html

UE.plugins['formula'] = function () {
    var me = this;
    me._formulaid = 0;

    var filter = function (node) {
        return domUtils.findParent(node, function (node) {
            return node.nodeType == 1 && node.tagName.toLowerCase() == 'span' && domUtils.hasClass(node, 'mathquill-rendered-math')
        }, true);
    };

    var fnBlock = function (node) {
        return domUtils.findParent(node, function (node) {
            return node.nodeType == 1 && node.tagName.toLowerCase() == 'p' && domUtils.hasClass(node, 'formulaBlock')
        }, true);
    };

    var setCursorPos = function (range, start, end, callback) {
        if (start && end && start === end) {
            if (start.nextSibling) {
                range.setStart(start.nextSibling, 0)
            } else {
                if (start.previousSibling) {
                    range.setStartAtLast(start.previousSibling)
                } else {
                    var p = me.document.createElement('p');
                    domUtils.fillNode(me.document, p);
                    range.setStart(p, 0)
                }
            }
            range.setCursor(false, true);
            callback();
        }
    };

    function toInline(node, ignorePre, ignoreNext) {
        function merge(rtl, start, node) {
            var next;
            if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1) {
                while (next.firstChild) {
                    if (start == 'firstChild') {
                        node.insertBefore(next.lastChild, node.firstChild);
                    }
                    else {
                        node.appendChild(next.firstChild);
                    }
                }
                domUtils.remove(next);
            }
        }

        !ignorePre && merge('previousSibling', 'firstChild', node);
        !ignoreNext && merge('nextSibling', 'lastChild', node);
    }

    me.addListener("ready", function () {
        utils.loadFile(me.document, {
            id:"mathquill_css",
            tag:"link",
            rel:"stylesheet",
            type:"text/css",
            href:me.options.formulaCssUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/mathquill.css"
        });
        utils.loadFile(me.document, {
            id:"jquery.min_js",
            src:me.options.jqueryUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/jquery.min.js",
            tag:"script",
            type:"text/javascript",
            defer:"defer"
        }, function () {
            utils.loadFile(me.document, {
                id:"mathquill_js",
                src:me.options.formulaJsUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/mathquill.min.js",
                tag:"script",
                type:"text/javascript",
                defer:"defer"
            });
        });
    });

    me.addListener("afterbackspace", function (types, evt) {
        if (!browser.ie) {
            var rng = me.selection.getRange();
            var formula = rng.startContainer.childNodes[rng.startOffset - 1];
            if (formula) {
                if (domUtils.hasClass(formula, "mathquill-rendered-math")) {
                    var bk = rng.createBookmark();
                    domUtils.remove(formula);
                    rng.moveToBookmark(bk).select();
                    evt.preventDefault();
                }
            }
        }
    });

    me.addListener("keydown", function (types, evt) {
        if (!browser.ie) {
            var keyCode = evt.keyCode || evt.which;
            if (keyCode == 46) {
                var rng = me.selection.getRange();
                var formula = domUtils.getNextDomNode(rng.startContainer);
                if (formula) {
                    if (domUtils.hasClass(formula, "mathquill-rendered-math")) {
                        var bk = rng.createBookmark();
                        domUtils.remove(formula);
                        rng.moveToBookmark(bk).select();
                        evt.preventDefault();
                    }
                }
            }
        }
    });

    function addFillChar(node) {
        var previous = node.previousSibling,
            next = node.nextSibling;

        if (!previous || !domUtils.isFillChar(previous)) {
            node.parentNode.insertBefore(document.createTextNode(domUtils.fillChar), node);
        }
        if (!next || !domUtils.isFillChar(next)) {
            domUtils.insertAfter(node, document.createTextNode(domUtils.fillChar));
        }
    }

    function queryState() {
        try {
            var rng = this.selection.getRange();
            var start = filter(rng.startContainer);
            end = filter(rng.endContainer);
            if (start && end && start == end) {
                addFillChar(start);
                return 1;
            } else {
                return 0;
            }
        }
        catch (e) {
            return 0;
        }
    }

    //不需要判断highlight的command列表
    me.notNeedmathQuery = {
        help:1,
        undo:1,
        redo:1,
        source:1,
        print:1,
        searchreplace:1,
        fullscreen:1,
        autotypeset:1,
        pasteplain:1,
        preview:1,
        insertparagraph:1,
        elementpath:1,
        formula:1,
        formulainline:1,
        formulablock:1,
        deleteformula:1
    };

    //将queyCommamndState重置
    var orgQuery = me.queryCommandState;
    me.queryCommandState = function (cmd) {
        if (!me.notNeedmathQuery[cmd.toLowerCase()] && queryState.call(this) == 1) {
            return -1;
        }
        return orgQuery.apply(this, arguments)
    };

    me.addListener("beforegetcontent beforegetscene", function () {
        if (!me.window || !me.window.$)return;
        utils.each(domUtils.getElementsByTagName(me.body, 'span', 'mathquill-rendered-math'), function (di) {
            var id = di.getAttribute("formulaid");
            var txt = me.window.$("[formulaid=" + id + "]").mathquill("latex");
            var span = domUtils.createElement(me.document, 'span', {
                'class':'mathquill-embedded-latex',
                'formulaid':id
            });
            span.appendChild(me.document.createTextNode(txt));
            di.parentNode.replaceChild(span, di);
        });
    });

    me.addListener("aftergetcontent aftersetcontent aftergetscene", function () {
        if (!me.window || !me.window.$)return;
        var list = me.window.$(".mathquill-embedded-latex"), obj = {};
        if (list.length) {
            for (var i = 0, len = list.length; i < len; i++) {
                obj[list[i].getAttribute("formulaid")] = list[i].innerText || list[i].textContent || list[i].nodeValue;
            }
            for (var attr in obj) {
                me.window.$("[formulaid=" + attr + "]")
                    .html("")
                    .mathquill("editable")
                    .mathquill("write", obj[attr].replace("{/}", "\\"));
            }
        }
    });

    me.commands['formula'] = {
        execCommand:function (cmdName, txt) {
            var rng = me.selection.getRange();
            var start = filter(rng.startContainer);
            var end = filter(rng.endContainer);
            var id = 0;

            if (start && end && start == end) {
                id = start.getAttribute("formulaid");
            } else {
                var doc = me.document;
                var span = domUtils.createElement(doc, "span", {
                    formulaid:me._formulaid
                });
                span.className = "mathquill-editable";
                span.appendChild(doc.createTextNode(txt));
                me.execCommand('inserthtml', span.outerHTML);

                id = me._formulaid;
                me.window.$("[formulaid=" + id + "]").html("").mathquill('editable');
                me._formulaid += 1;
            }

            var selector = "[formulaid=" + id + "]";
            me.window.$(selector).focus().mathquill("write", txt.replace("{/}", "\\"));
            rng.setStartAfter(me.window.$(selector)[0]).collapse(true);
            rng.setCursor();
        },
        queryCommandState:function () {
            return queryState.call(me);
        }
    };

    me.commands['formulainline'] = {
        execCommand:function () {
            var range = me.selection.getRange();
            range.adjustmentBoundary();
            var start = fnBlock(range.startContainer),
                end = fnBlock(range.endContainer);

            setCursorPos(range, start, end, function () {
                if (start.previousSibling || start.nextSibling || /li/i.test(start.parentNode.tagName)) {
                    toInline(start);
                }
                else {
                    var p = document.createElement("p");
                    p.appendChild(start);
                    start.parentNode.replaceChild(p, start);
                }
                domUtils.removeAttributes(start, ["style", "class"]);
            });
        },
        queryCommandState:function () {
            try {
                var range = this.selection.getRange();
                var start = fnBlock(range.startContainer),
                    end = fnBlock(range.startContainer);

                return start && end && start == end ? 0 : -1;
            }
            catch (e) {
                return -1;
            }
        }
    };

    me.commands['formulablock'] = {
        execCommand:function () {
            var range = me.selection.getRange();
            range.adjustmentBoundary();
            var start = filter(range.startContainer),
                end = filter(range.endContainer);

            setCursorPos(range, start, end, function () {
                domUtils.breakParent(start, domUtils.findParent(start, function (node) {
                    return node.nodeType == 1 && node.tagName.toLowerCase() == 'p'
                }, false));

                var p = domUtils.createElement(document, "p", {
                    "style":"text-align:center",
                    "class":"formulaBlock"
                });
                start.parentNode.replaceChild(p, start);
                p.appendChild(start);
            });
        },
        queryCommandState:function () {
            try {
                var range = me.selection.getRange();
                var start = filter(range.startContainer),
                    end = filter(range.endContainer);

                if (start && end && start == end) {
                    var p = fnBlock(range.startContainer);
                    return p ? -1 : 0;
                } else {
                    return -1;
                }

            }
            catch (e) {
                return -1;
            }
        }
    };

    me.commands["deleteformula"] = {
        execCommand:function () {
            var range = me.selection.getRange();
            var start = filter(range.startContainer),
                end = filter(range.endContainer);

            setCursorPos(range, start, end, function () {
                domUtils.remove(start);
            });
        },
        queryCommandState:function () {
            try {
                var rng = me.selection.getRange();
                var start = filter(rng.startContainer);
                var end = filter(rng.endContainer);
                return start && end && start == end ? 0 : 1;
            } catch (e) {
                return -1;
            }

        }
    }
}<commit_msg>New changelist<commit_after>///import core
///import commands/inserthtml.js
///commands 插入公式
///commandsName  formula
///commandsTitle  插入公式
///commandsDialog  dialogs\formula\formula.html

UE.plugins['formula'] = function () {
    var me = this;
    me._formulaid = 0;

    var filter = function (node) {
        return domUtils.findParent(node, function (node) {
            return node.nodeType == 1 && node.tagName.toLowerCase() == 'span' && domUtils.hasClass(node, 'mathquill-rendered-math')
        }, true);
    };

    var fnBlock = function (node) {
        return domUtils.findParent(node, function (node) {
            return node.nodeType == 1 && node.tagName.toLowerCase() == 'p' && domUtils.hasClass(node, 'formulaBlock')
        }, true);
    };

    var setCursorPos = function (range, start, end, callback) {
        if (start && end && start === end) {
            if (start.nextSibling) {
                range.setStart(start.nextSibling, 0)
            } else {
                if (start.previousSibling) {
                    range.setStartAtLast(start.previousSibling)
                } else {
                    var p = me.document.createElement('p');
                    domUtils.fillNode(me.document, p);
                    range.setStart(p, 0)
                }
            }
            range.setCursor(false, true);
            callback();
        }
    };

    function toInline(node, ignorePre, ignoreNext) {
        function merge(rtl, start, node) {
            var next;
            if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1) {
                while (next.firstChild) {
                    if (start == 'firstChild') {
                        node.insertBefore(next.lastChild, node.firstChild);
                    }
                    else {
                        node.appendChild(next.firstChild);
                    }
                }
                domUtils.remove(next);
            }
        }

        !ignorePre && merge('previousSibling', 'firstChild', node);
        !ignoreNext && merge('nextSibling', 'lastChild', node);
    }

    me.addListener("ready", function () {
        utils.loadFile(me.document, {
            id:"mathquill_css",
            tag:"link",
            rel:"stylesheet",
            type:"text/css",
            href:me.options.formulaCssUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/mathquill.css"
        });
        utils.loadFile(me.document, {
            id:"jquery.min_js",
            src:me.options.jqueryUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/jquery.min.js",
            tag:"script",
            type:"text/javascript",
            defer:"defer"
        }, function () {
            utils.loadFile(me.document, {
                id:"mathquill_js",
                src:me.options.formulaJsUrl || me.options.UEDITOR_HOME_URL + "third-party/mathquill/mathquill.min.js",
                tag:"script",
                type:"text/javascript",
                defer:"defer"
            });
        });
    });

    me.addListener("afterbackspace", function (types, evt) {
        if (!browser.ie) {
            var rng = me.selection.getRange();
            var formula = rng.startContainer.childNodes[rng.startOffset - 1];
            if (formula) {
                if (domUtils.hasClass(formula, "mathquill-rendered-math")) {
                    var bk = rng.createBookmark();
                    domUtils.remove(formula);
                    rng.moveToBookmark(bk).select();
                    evt.preventDefault();
                }
            }
        }
    });

    me.addListener("keydown", function (types, evt) {
        if (!browser.ie) {
            var keyCode = evt.keyCode || evt.which;
            if (keyCode == 46) {
                var rng = me.selection.getRange();
                var formula = domUtils.getNextDomNode(rng.startContainer);
                if (formula) {
                    if (domUtils.hasClass(formula, "mathquill-rendered-math")) {
                        var bk = rng.createBookmark();
                        domUtils.remove(formula);
                        rng.moveToBookmark(bk).select();
                        evt.preventDefault();
                    }
                }
            }
        }
    });

    function addFillChar(node) {
        var previous = node.previousSibling,
            next = node.nextSibling;

        if (!previous || !domUtils.isFillChar(previous)) {
            node.parentNode.insertBefore(document.createTextNode(domUtils.fillChar), node);
        }
        if (!next || !domUtils.isFillChar(next)) {
            domUtils.insertAfter(node, document.createTextNode(domUtils.fillChar));
        }
    }

    function queryState() {
        try {
            var rng = this.selection.getRange();
            var start = filter(rng.startContainer);
            end = filter(rng.endContainer);
            if (start && end && start == end) {
                addFillChar(start);
                return 1;
            } else {
                return 0;
            }
        }
        catch (e) {
            return 0;
        }
    }

    //不需要判断highlight的command列表
    me.notNeedmathQuery = {
        help:1,
        undo:1,
        redo:1,
        source:1,
        print:1,
        searchreplace:1,
        fullscreen:1,
        autotypeset:1,
        pasteplain:1,
        preview:1,
        insertparagraph:1,
        elementpath:1,
        formula:1,
        formulainline:1,
        formulablock:1,
        deleteformula:1
    };

    //将queyCommamndState重置
    var orgQuery = me.queryCommandState;
    me.queryCommandState = function (cmd) {
        if (!me.notNeedmathQuery[cmd.toLowerCase()] && queryState.call(this) == 1) {
            return -1;
        }
        return orgQuery.apply(this, arguments)
    };

    me.addListener("beforegetcontent beforegetscene", function () {
        if (!me.window || !me.window.$)return;
        utils.each(domUtils.getElementsByTagName(me.body, 'span', 'mathquill-rendered-math'), function (di) {
            var id = di.getAttribute("formulaid");
            var txt = me.window.$("[formulaid=" + id + "]").mathquill("latex");
            var span = domUtils.createElement(me.document, 'span', {
                'class':'mathquill-embedded-latex',
                'formulaid':id
            });
            span.appendChild(me.document.createTextNode(txt));
            di.parentNode.replaceChild(span, di);
        });
    });

    me.addListener("aftergetcontent aftersetcontent aftergetscene", function () {
        if (!me.window || !me.window.$)return;
        var list = me.window.$(".mathquill-embedded-latex"), obj = {};
        if (list.length) {
            for (var i = 0, len = list.length; i < len; i++) {
                obj[list[i].getAttribute("formulaid")] = list[i].innerText || list[i].textContent || list[i].nodeValue;
            }
            for (var attr in obj) {
                me.window.$("[formulaid=" + attr + "]")
                    .html("")
                    .mathquill("editable")
                    .mathquill("write", obj[attr].replace("{/}", "\\"));
            }
        }
    });

    me.commands['formula'] = {
        execCommand:function (cmdName, txt) {
            var rng = me.selection.getRange();
            var start = filter(rng.startContainer);
            var end = filter(rng.endContainer);
            var id = 0;

            if (start && end && start == end) {
                id = start.getAttribute("formulaid");
            } else {
                var doc = me.document;
                var span = domUtils.createElement(doc, "span", {
                    formulaid:me._formulaid
                });
                span.className = "mathquill-editable";
                span.appendChild(doc.createTextNode(txt));
                me.execCommand('inserthtml', span.outerHTML);

                id = me._formulaid;
                me.window.$("[formulaid=" + id + "]").html("").mathquill('editable');
                me._formulaid += 1;
            }

            var selector = "[formulaid=" + id + "]";
            me.window.$(selector).focus().mathquill("write", txt.replace("{/}", "\\"));
            rng.setStartAfter(me.window.$(selector)[0]).collapse(true);
            rng.setCursor();
        },
        queryCommandState:function () {
            return queryState.call(me);
        }
    };

    me.commands['formulainline'] = {
        execCommand:function () {
            var range = me.selection.getRange();
            range.adjustmentBoundary();
            var start = fnBlock(range.startContainer),
                end = fnBlock(range.endContainer);

            setCursorPos(range, start, end, function () {
                if (start.previousSibling || start.nextSibling || /li/i.test(start.parentNode.tagName)) {
                    toInline(start);
                }
                else {
                    var p = document.createElement("p");
                    p.appendChild(start);
                    start.parentNode.replaceChild(p, start);
                }
                domUtils.removeAttributes(start, ["style", "class"]);
            });
        },
        queryCommandState:function () {
            try {
                var range = this.selection.getRange();
                var start = fnBlock(range.startContainer),
                    end = fnBlock(range.startContainer);

                return start && end && start == end ? 0 : -1;
            }
            catch (e) {
                return -1;
            }
        }
    };

    me.commands['formulablock'] = {
        execCommand:function () {
            var range = me.selection.getRange();
            range.adjustmentBoundary();
            var start = filter(range.startContainer),
                end = filter(range.endContainer);

            setCursorPos(range, start, end, function () {
                domUtils.breakParent(start, domUtils.findParent(start, function (node) {
                    return node.nodeType == 1 && node.tagName.toLowerCase() == 'p'
                }, false));

                var p = domUtils.createElement(document, "p", {
                    "style":"text-align:center",
                    "class":"formulaBlock"
                });
                start.parentNode.replaceChild(p, start);
                p.appendChild(start);
            });
        },
        queryCommandState:function () {
            try {
                var range = me.selection.getRange();
                var start = filter(range.startContainer),
                    end = filter(range.endContainer);

                if (start && end && start == end) {
                    var p = fnBlock(range.startContainer);
                    return p ? -1 : 0;
                } else {
                    return -1;
                }

            }
            catch (e) {
                return -1;
            }
        }
    };

    me.commands["deleteformula"] = {
        execCommand:function () {
            var range = me.selection.getRange();
            var start = filter(range.startContainer),
                end = filter(range.endContainer);

            setCursorPos(range, start, end, function () {
                domUtils.remove(start);
            });
        },
        queryCommandState:function () {
            try {
                var rng = me.selection.getRange();
                var start = filter(rng.startContainer);
                var end = filter(rng.endContainer);
                return start && end && start == end ? 0 : -1;
            } catch (e) {
                return -1;
            }

        }
    }
}<|endoftext|>


<commit_before>function demoSetup(apis) {

  var apiOptions = $('#demo-api');
  apiOptions.empty();
  $.each(apis, function() {
    apiOptions.append($("<option />").val(this.id).text(this.id));
  });

  $('#demo').show();
}

function demoTeardown() {
  $('#demo-results').empty();
  $('#demo').hide();
}

function doDemo(demoMethod) {
  var fullUrl = '';
  var demoRoute = $('#demo-route').val();
  var demoApi = $('#demo-api').val();
  var demoUrl = $('#demo-url').val().trim();

  if(demoUrl.length===0) {
    demoUrl = '/';
  }

  switch(demoRoute) {
    case '/api':
    case '/data':
      break;
    default:
      console.log(demoRoute + ' route not supported');
      return; // not supported
  }

  if(demoMethod) {
    demoMethod = demoMethod.toUpperCase();
  }

  switch(demoMethod) {
    case 'GET':
      if(demoUrl === '/data') {
        fullUrl = demoRoute + demoUrl;
      }
      else {
        fullUrl = demoRoute + '/' + demoApi + demoUrl;
      }
      break;
    case 'POST':
      if(demoUrl !== '/data') {
        return; // not supported
      }
      fullUrl = demoRoute + '/' + demoApi + demoUrl;
      break;
    default:
      console.log(demoMethod + ' method not supported');
      return; // not supported
  }

  console.log(demoMethod + ' submitted for ' + fullUrl);
  $('#demo-results').empty();

  if(demoMethod === 'GET') {
    $('#demo-results').src = fullUrl;
  }
  else {
    var demoForm = document.createElement('form');
    demoForm.method = demoMethod;
    demoForm.action = fullUrl;
    demoForm.target = 'demo-results';
    demoForm.submit();
  }
}
<commit_msg>using iframe src for get request to prevent question mark<commit_after>function demoSetup(apis) {

  var apiOptions = $('#demo-api');
  apiOptions.empty();
  $.each(apis, function() {
    apiOptions.append($("<option />").val(this.id).text(this.id));
  });

  $('#demo').show();
}

function demoTeardown() {
  $('#demo-results').empty();
  $('#demo').hide();
}

function doDemo(demoMethod) {
  var fullUrl = '';
  var demoRoute = $('#demo-route').val();
  var demoApi = $('#demo-api').val();
  var demoUrl = $('#demo-url').val().trim();

  if(demoUrl.length===0) {
    demoUrl = '/';
  }

  switch(demoRoute) {
    case '/api':
    case '/data':
      break;
    default:
      console.log(demoRoute + ' route not supported');
      return; // not supported
  }

  if(demoMethod) {
    demoMethod = demoMethod.toUpperCase();
  }

  switch(demoMethod) {
    case 'GET':
      if(demoUrl === '/data') {
        fullUrl = demoRoute + demoUrl;
      }
      else {
        fullUrl = demoRoute + '/' + demoApi + demoUrl;
      }
      break;
    case 'POST':
      if(demoUrl !== '/data') {
        return; // not supported
      }
      fullUrl = demoRoute + '/' + demoApi + demoUrl;
      break;
    default:
      console.log(demoMethod + ' method not supported');
      return; // not supported
  }

  console.log(demoMethod + ' submitted for ' + fullUrl);
  $('#demo-results').empty();

  if(demoMethod === 'GET') {
    $('#demo-results').location.href = fullUrl;
  }
  else {
    var demoForm = document.createElement('form');
    demoForm.method = demoMethod;
    demoForm.action = fullUrl;
    demoForm.target = 'demo-results';
    demoForm.submit();
  }
}
<|endoftext|>


<commit_before>var router = require('./router').router;
var cache = require("../utils/cache");
var log = require('./log');
var url = require('url');
var qs = require('querystring');
var mime = require('mime');

exports.handle = function (req, res) {
    var originUrl = req.url;
    //router.dispatch
    log.info("[Req]", req.connection.remoteAddress, originUrl, req.headers["user-agent"]);
    if (originUrl.indexOf("..") > -1) {
        log.warning("[NotFound]", originUrl);
        res.writeHead(404, "file not found!");
        res.end();
        return;
    }
    //压缩方式
    var compress = "";
    var requestHeaders = req.headers;
    //expires
    var now = new Date();
    now.setTime(now.getTime() + global.MAXAGE * 1000);
    res.setHeader('Expires', now.toUTCString());
    res.setHeader('Cache-Control', 'max-age=' + global.MAXAGE);
    //compress
    var gzip = false
        , deflate = false;
    if (requestHeaders['accept-encoding']) {
        gzip = requestHeaders['accept-encoding'].indexOf('gzip') > -1;
        deflate = requestHeaders['accept-encoding'].indexOf('deflate') > -1;
    }
    if (gzip) {
        res.setHeader('Content-Encoding', 'gzip');
        compress = "gzip";
    } else if (deflate) {
        res.setHeader('Content-Encoding', 'deflate');
        compress = "deflate";
    }

    // 不使用缓存 直接交给路由
    if (!global.USECACHE) {
        router.parse(originUrl, [req, res, compress]);
        return;
    }
    //去除originUrl中的参数部分
    var urlObject = url.parse(originUrl);
    var cachePath = urlObject.pathname;
    cachePath = encodeURIComponent(decodeURIComponent(cachePath));
    //替换/
    cachePath = cachePath.replace(/%2F/g, '\/');
    //解析参数
    var params = qs.parse(urlObject.query);
    if (params.cache == "false" && global.DEBUG) {
        //不使用缓存(仅debug模式)
        router.parse(originUrl, [req, res, compress]);
        return;
    }
    //处理缓存
    cache.stats(cachePath, function (stats) {
        if (!stats || !stats.isFile()) {
            //缓存不存在,交给路由处理
            router.parse(originUrl, [req, res, compress]);
        } else {
            //解析content type
            res.setHeader("Content-Type", mime.lookup(cachePath) + ";charset=utf-8");

            var lastModified = stats.mtime.toUTCString();
            //如果没有修改，则返回304
            if (requestHeaders["if-modified-since"] && lastModified == requestHeaders["if-modified-since"]) {
                log.info("[NotModified]", cachePath);
                res.writeHead(304, "Not Modified");
                res.end();
                return;
            }
            res.setHeader("Last-Modified", lastModified);
            //将文件写入response
            res.statusCode = 200;
            log.info('[Success]', cachePath);
            cache.read(cachePath, compress, res);
        }
    });

}<commit_msg>ip address bug fix<commit_after>var router = require('./router').router;
var cache = require("../utils/cache");
var log = require('./log');
var url = require('url');
var qs = require('querystring');
var mime = require('mime');

exports.handle = function (req, res) {
    var originUrl = req.url;
    //router.dispatch
    var ip = req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
    log.info("[Req]", ip, originUrl, req.headers["user-agent"]);
    if (originUrl.indexOf("..") > -1) {
        log.warning("[NotFound]", originUrl);
        res.writeHead(404, "file not found!");
        res.end();
        return;
    }
    //压缩方式
    var compress = "";
    var requestHeaders = req.headers;
    //expires
    var now = new Date();
    now.setTime(now.getTime() + global.MAXAGE * 1000);
    res.setHeader('Expires', now.toUTCString());
    res.setHeader('Cache-Control', 'max-age=' + global.MAXAGE);
    //compress
    var gzip = false
        , deflate = false;
    if (requestHeaders['accept-encoding']) {
        gzip = requestHeaders['accept-encoding'].indexOf('gzip') > -1;
        deflate = requestHeaders['accept-encoding'].indexOf('deflate') > -1;
    }
    if (gzip) {
        res.setHeader('Content-Encoding', 'gzip');
        compress = "gzip";
    } else if (deflate) {
        res.setHeader('Content-Encoding', 'deflate');
        compress = "deflate";
    }

    // 不使用缓存 直接交给路由
    if (!global.USECACHE) {
        router.parse(originUrl, [req, res, compress]);
        return;
    }
    //去除originUrl中的参数部分
    var urlObject = url.parse(originUrl);
    var cachePath = urlObject.pathname;
    cachePath = encodeURIComponent(decodeURIComponent(cachePath));
    //替换/
    cachePath = cachePath.replace(/%2F/g, '\/');
    //解析参数
    var params = qs.parse(urlObject.query);
    if (params.cache == "false" && global.DEBUG) {
        //不使用缓存(仅debug模式)
        router.parse(originUrl, [req, res, compress]);
        return;
    }
    //处理缓存
    cache.stats(cachePath, function (stats) {
        if (!stats || !stats.isFile()) {
            //缓存不存在,交给路由处理
            router.parse(originUrl, [req, res, compress]);
        } else {
            //解析content type
            res.setHeader("Content-Type", mime.lookup(cachePath) + ";charset=utf-8");

            var lastModified = stats.mtime.toUTCString();
            //如果没有修改，则返回304
            if (requestHeaders["if-modified-since"] && lastModified == requestHeaders["if-modified-since"]) {
                log.info("[NotModified]", cachePath);
                res.writeHead(304, "Not Modified");
                res.end();
                return;
            }
            res.setHeader("Last-Modified", lastModified);
            //将文件写入response
            res.statusCode = 200;
            log.info('[Success]', cachePath);
            cache.read(cachePath, compress, res);
        }
    });

}<|endoftext|>