<commit_before>var
    esPhinx,
    Iterable;

(function($) {
    "use strict";

    var
        displayObjects = [];

    $.prototype.extend({

        css: function(property, value, delay) {
            if (typeof delay != "number") {delay = 0;}
        // css: function(property, value, delay = 0) {
            var
                properties,
                number,
                computedStyle,
                propertyPriority,
                callback,
                propertiesIteratorBlock,
                node = this.asNode(),
                offsetPattern = /\b(width|height|top|left)\b/,
                originalProperties = {},
                map2Calculation = {position: "absolute", visibility: "hidden",
                display: "block"},
                toCalculationCollection = ["position", "visibility", "display"],
                nonexistentProperties = [],

                toCalculationCollectionIteratorBlock = function(p) {
                    if(!node.style[p]) {
                        nonexistentProperties.push(p);
                    }
                    originalProperties[p] = node.style[p] ||
                        computedStyle[p];
                    node.style.setProperty(p, map2Calculation[p], "important");
                },

                toRevertCalculationCollectionIteratorBlock = function(p) {
                    node.style.setProperty(p, originalProperties[p], node.style
                                           .getPropertyPriority(p));
                },

                nonexistentPropertiesIteratorBlock = function(prop) {
                    node.style.removeProperty(prop);
                };

            if (value === 0) {
                value = value.toString();
            }

            if (typeof delay != "number") {
                delay = 0;
            }

            // (key, value)
            if (!value && !Object.areFromClass(property, Object)) {
                property = property.strikeCase();
                computedStyle = window.getComputedStyle(node);
                value = computedStyle.getPropertyValue(property);

                if (node.style[property]) {
                    value = node.style[property];
                } else if (computedStyle.display == "none" &&
                           offsetPattern.test(property)) {
                    toCalculationCollection
                        .forEach(toCalculationCollectionIteratorBlock);

                    value = computedStyle.getPropertyValue(property);

                    // remove
                    nonexistentProperties
                        .forEach(nonexistentPropertiesIteratorBlock);

                    // revert
                    toCalculationCollection.difference(nonexistentProperties)
                        .forEach(toRevertCalculationCollectionIteratorBlock);
                }

                number = parseFloat(value);

                if (Number.isNaN(number)) {
                    return value;
                } else {
                    return number;
                }
            }

            if (Object.areFromClass(property, Object)) {

                properties = property;

                // if (/^transition/.test(property)) {
                //     delay = ;
                // }

                callback = function(node) {
                    computedStyle = window.getComputedStyle(node);

                    propertiesIteratorBlock = function(value, property) {
                        property = property.strikeCase();
                        propertyPriority = computedStyle
                            .getPropertyPriority(property);
                        node.style.setProperty(property, value,
                                               propertyPriority);
                    };

                    $.each(properties, propertiesIteratorBlock);
                };

            } else {
                // if (/^transition/.test(property)) {
                //     delay = ;
                // }

                callback = function(node) {
                    computedStyle = window.getComputedStyle(node);
                    property = property.strikeCase();
                    propertyPriority = computedStyle
                        .getPropertyPriority(property);
                    node.style.setProperty(property, value, propertyPriority);
                };
            }

            window.setTimeout(function() {
                this.each(callback);
            }, delay);

            return this;
        },

        centralizeAt: function(reference) {
            var
                self = this,
                parent,

                centralize = function(reference) {
                    this.css("position", "absolute");

                    this.css({
                        top: (reference.height() / 2) -
                            (this.height() / 2) + "px",
                        left: (reference.width() / 2) -
                          (this.width() / 2) + "px"
                    });
                };

            if (!Object.hasSameClass(reference, this)) {
                reference = $(reference);
            }

            centralize.call(this, reference);

            if (reference.isA(window.Element)) {
                parent = reference;
            } else {
                parent = $().push(window);
            }

            parent.on("resize", function() {
                centralize.call(self, reference);
            });

            return this;
        },

        // hide: function(delay = 0) {
        hide: function(delay) {
            if (typeof delay != "number") {delay = 0;}

            var
                exists,
                iterator,
                node = this.asNode(),

                callback = function(hash) {
                    if (hash.element == node) {
                        exists = true;
                        this.finalize();
                    }
                };

            if (node instanceof window.Element) {
                if ($(node).css("display") != "none") {
                    iterator = Iterable.Proxy.new(displayObjects);
                    iterator.each(callback);

                    if (!exists && this.css("display")) {
                        displayObjects.push({
                            element: node,
                            display: this.css("display")
                        });
                    }
                }

            }

            this.css("display", "none", delay);

            return this;
        },

        show: function(displayValue) {
            var
                style,
                inlineDisplay,
                display,
                iterator,
                node = this.asNode(),

                callback = function(hash) {
                    if (hash.element == node) {
                        display = hash.display;
                        this.finalize();
                    }
                };

            if (node instanceof window.Element) {
                style = node.style;
                inlineDisplay = style.display;
            }

            if (this.css("display") == "none") {
                iterator = Iterable.Proxy.new(displayObjects);
                iterator.each(callback);

                if (display) {
                    this.css("display", display);
                } else if (inlineDisplay) {
                    style.display = null;
                    if (this.css("display") == "none") {
                        this.css("display", "block");
                    }
                } else {
                    this.css("display", "block");
                }
            }

            // if (display) {
            //     this.css("display", display);
            // } else if (inlineDisplay) {
            //     style.display = null;
            //     if (this.css("display") == "none") {
            //         this.css("display", "block");
            //     }
            // } else {
            //     this.css("display", "block");
            // }

            return this;
        },

        horizontalToggle: function(initialMargin, callback) {
            initialMargin = initialMargin || 0;
        // horizontalToggle: function(initialMargin = 0) {
            if (typeof initialMargin == "function") {
                callback = initialMargin;
                initialMargin = 0;
            }

            var
                width,
                margin,
                marginRight,
                marginLeft,
                duration,

                iteratorBlock = function(node) {
                    node = $(node);

                    width = Math.round(node.width());
                    marginLeft = Math.abs(node.css("margin-left"));
                    marginRight = Math.abs(node.css("margin-right"));
                    duration = node.transitionDuration();

                    // discovering more criteria to know if align on right (||)
                    if (node.css("float") == "right") {
                        margin = Math.abs(Math.round(node.css("margin-right")));
                        if (margin != (width + marginLeft)) {
                            node.css("margin-right", - (width + marginLeft) +
                                     "px");
                        } else {
                            node.css("margin-right", initialMargin + "px");
                        }
                    } else {
                        margin = Math.abs(Math.round(node.css("margin-left")));
                        if (margin != (width + marginRight)) {
                            node.css("margin-left", - (width + marginRight) +
                                     "px");
                        } else {
                            node.css("margin-left", initialMargin + "px");
                        }
                    }

                    if (duration) {
                        window.setTimeout(function() {
                            callback.call(node);
                        }, duration);
                    } else {
                        callback.call(node);
                    }

                };

            this.each(iteratorBlock);

            return this;
        },

        toggleClass: function(classList, changeTo) {
            var
                callback = function(node) {
                    if ($(node).hasClass(classList)) {
                        $(node).removeClass(classList);
                        if (changeTo) {
                            $(node).addClass(changeTo);
                        }
                    } else if (changeTo) {
                        if ($(node).hasClass(changeTo)) {
                            $(node).removeClass(changeTo);
                            $(node).addClass(classList);
                        } else {
                            $(node).addClass(classList);
                        }
                    } else {
                        $(node).addClass(classList);
                    }
                };

            this.each(callback);

            return this;
        },

        toggle: function() {
            if (this.css("display") == "none") {
                this.show();
            } else {
                this.hide();
            }
        }

    });

}(esPhinx));
<commit_msg>fix .css<commit_after>var
    esPhinx,
    Iterable;

(function($) {
    "use strict";

    var
        displayObjects = [];

    $.prototype.extend({

        css: function(property, value, delay) {
            if (typeof delay != "number") {delay = 0;}
        // css: function(property, value, delay = 0) {
            var
                properties,
                number,
                computedStyle,
                propertyPriority,
                callback,
                propertiesIteratorBlock,
                self = this,
                node = this.asNode(),
                offsetPattern = /\b(width|height|top|left)\b/,
                originalProperties = {},
                map2Calculation = {position: "absolute", visibility: "hidden",
                display: "block"},
                toCalculationCollection = ["position", "visibility", "display"],
                nonexistentProperties = [],

                toCalculationCollectionIteratorBlock = function(p) {
                    if(!node.style[p]) {
                        nonexistentProperties.push(p);
                    }
                    originalProperties[p] = node.style[p] ||
                        computedStyle[p];
                    node.style.setProperty(p, map2Calculation[p], "important");
                },

                toRevertCalculationCollectionIteratorBlock = function(p) {
                    node.style.setProperty(p, originalProperties[p], node.style
                                           .getPropertyPriority(p));
                },

                nonexistentPropertiesIteratorBlock = function(prop) {
                    node.style.removeProperty(prop);
                };

            if (value === 0) {
                value = value.toString();
            }

            if (typeof delay != "number") {
                delay = 0;
            }

            // (key, value)
            if (!value && !Object.areFromClass(property, Object)) {
                property = property.strikeCase();
                computedStyle = window.getComputedStyle(node);
                value = computedStyle.getPropertyValue(property);

                if (node.style[property]) {
                    value = node.style[property];
                } else if (computedStyle.display == "none" &&
                           offsetPattern.test(property)) {
                    toCalculationCollection
                        .forEach(toCalculationCollectionIteratorBlock);

                    value = computedStyle.getPropertyValue(property);

                    // remove
                    nonexistentProperties
                        .forEach(nonexistentPropertiesIteratorBlock);

                    // revert
                    toCalculationCollection.difference(nonexistentProperties)
                        .forEach(toRevertCalculationCollectionIteratorBlock);
                }

                number = parseFloat(value);

                if (Number.isNaN(number)) {
                    return value;
                } else {
                    return number;
                }
            }

            if (Object.areFromClass(property, Object)) {

                properties = property;

                // if (/^transition/.test(property)) {
                //     delay = ;
                // }

                callback = function(node) {
                    computedStyle = window.getComputedStyle(node);

                    propertiesIteratorBlock = function(value, property) {
                        property = property.strikeCase();
                        propertyPriority = computedStyle
                            .getPropertyPriority(property);
                        node.style.setProperty(property, value,
                                               propertyPriority);
                    };

                    $.each(properties, propertiesIteratorBlock);
                };

            } else {
                // if (/^transition/.test(property)) {
                //     delay = ;
                // }

                callback = function(node) {
                    computedStyle = window.getComputedStyle(node);
                    property = property.strikeCase();
                    propertyPriority = computedStyle
                        .getPropertyPriority(property);
                    node.style.setProperty(property, value, propertyPriority);
                };
            }

            window.setTimeout(function() {
                self.each(callback);
            }, delay);

            return this;
        },

        centralizeAt: function(reference) {
            var
                self = this,
                parent,

                centralize = function(reference) {
                    this.css("position", "absolute");

                    this.css({
                        top: (reference.height() / 2) -
                            (this.height() / 2) + "px",
                        left: (reference.width() / 2) -
                          (this.width() / 2) + "px"
                    });
                };

            if (!Object.hasSameClass(reference, this)) {
                reference = $(reference);
            }

            centralize.call(this, reference);

            if (reference.isA(window.Element)) {
                parent = reference;
            } else {
                parent = $().push(window);
            }

            parent.on("resize", function() {
                centralize.call(self, reference);
            });

            return this;
        },

        // hide: function(delay = 0) {
        hide: function(delay) {
            if (typeof delay != "number") {delay = 0;}

            var
                exists,
                iterator,
                node = this.asNode(),

                callback = function(hash) {
                    if (hash.element == node) {
                        exists = true;
                        this.finalize();
                    }
                };

            if (node instanceof window.Element) {
                if ($(node).css("display") != "none") {
                    iterator = Iterable.Proxy.new(displayObjects);
                    iterator.each(callback);

                    if (!exists && this.css("display")) {
                        displayObjects.push({
                            element: node,
                            display: this.css("display")
                        });
                    }
                }

            }

            this.css("display", "none", delay);

            return this;
        },

        show: function(displayValue) {
            var
                style,
                inlineDisplay,
                display,
                iterator,
                node = this.asNode(),

                callback = function(hash) {
                    if (hash.element == node) {
                        display = hash.display;
                        this.finalize();
                    }
                };

            if (node instanceof window.Element) {
                style = node.style;
                inlineDisplay = style.display;
            }

            if (this.css("display") == "none") {
                iterator = Iterable.Proxy.new(displayObjects);
                iterator.each(callback);

                if (display) {
                    this.css("display", display);
                } else if (inlineDisplay) {
                    style.display = null;
                    if (this.css("display") == "none") {
                        this.css("display", "block");
                    }
                } else {
                    this.css("display", "block");
                }
            }

            // if (display) {
            //     this.css("display", display);
            // } else if (inlineDisplay) {
            //     style.display = null;
            //     if (this.css("display") == "none") {
            //         this.css("display", "block");
            //     }
            // } else {
            //     this.css("display", "block");
            // }

            return this;
        },

        horizontalToggle: function(initialMargin, callback) {
            initialMargin = initialMargin || 0;
        // horizontalToggle: function(initialMargin = 0) {
            if (typeof initialMargin == "function") {
                callback = initialMargin;
                initialMargin = 0;
            }

            var
                width,
                margin,
                marginRight,
                marginLeft,
                duration,

                iteratorBlock = function(node) {
                    node = $(node);

                    width = Math.round(node.width());
                    marginLeft = Math.abs(node.css("margin-left"));
                    marginRight = Math.abs(node.css("margin-right"));
                    duration = node.transitionDuration();

                    // discovering more criteria to know if align on right (||)
                    if (node.css("float") == "right") {
                        margin = Math.abs(Math.round(node.css("margin-right")));
                        if (margin != (width + marginLeft)) {
                            node.css("margin-right", - (width + marginLeft) +
                                     "px");
                        } else {
                            node.css("margin-right", initialMargin + "px");
                        }
                    } else {
                        margin = Math.abs(Math.round(node.css("margin-left")));
                        if (margin != (width + marginRight)) {
                            node.css("margin-left", - (width + marginRight) +
                                     "px");
                        } else {
                            node.css("margin-left", initialMargin + "px");
                        }
                    }

                    if (duration) {
                        window.setTimeout(function() {
                            callback.call(node);
                        }, duration);
                    } else {
                        callback.call(node);
                    }

                };

            this.each(iteratorBlock);

            return this;
        },

        toggleClass: function(classList, changeTo) {
            var
                callback = function(node) {
                    if ($(node).hasClass(classList)) {
                        $(node).removeClass(classList);
                        if (changeTo) {
                            $(node).addClass(changeTo);
                        }
                    } else if (changeTo) {
                        if ($(node).hasClass(changeTo)) {
                            $(node).removeClass(changeTo);
                            $(node).addClass(classList);
                        } else {
                            $(node).addClass(classList);
                        }
                    } else {
                        $(node).addClass(classList);
                    }
                };

            this.each(callback);

            return this;
        },

        toggle: function() {
            if (this.css("display") == "none") {
                this.show();
            } else {
                this.hide();
            }
        }

    });

}(esPhinx));
<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import AxiomError from 'axiom/core/error';
import FileSystem from 'axiom/fs/base/file_system';

/** @typedef Channel$$module$axiom$fs$stream$channel */
var Channel;

/** @typedef FileSystemManager$$module$axiom$fs$base$file_system_manager */
var FileSystemManager;

/** @typedef {Path$$module$axiom$fs$path} */
var Path;

/** @typedef {StatResult$$module$axiom$fs$stat_result} */
var StatResult;

/**
 * Implementation of a FileSystem that forwards all request over a Channel
 * to a remote file system.
 *
 * @constructor @extends {FileSystem}
 * @param {!FileSystemManager} fileSystemManager
 * @param {!string} name
 * @param {!Channel} channel
 */
export var StubFileSystem = function(fileSystemManager, name, channel) {
  FileSystem.call(this, fileSystemManager, name);

  /** @const @private @type {Channel} */
  this.channel_ = channel;

  /** @type {string} */
  this.description = 'remote file system';
};

export default StubFileSystem;

StubFileSystem.prototype = Object.create(FileSystem.prototype);

/**
 * @private
 * @param {Path} path
 * @return {!boolean}
 */
StubFileSystem.prototype.isValidPath_ = function(path) {
  return !(!path || !path.isValid || path.root !== this.name);
};

/**
 * @param {Path} path
 * @return {!Promise<!Object<string, StatResult>>}
 */
StubFileSystem.prototype.list = function(path) {
  if (!this.isValidPath_(path))
    return Promise.reject(new AxiomError.Invalid('path', path.originalSpec));

  return this.channel_.sendRequest({
    cmd: 'list',
    path: path.spec,
  }).then(
    function(response) {
      var result = {};
      for(var name in response.entries) {
        result[name] = response.entries[name];
      }
      return result;
    }.bind(this)
  );
};

/**
 * @param {Path} path
 * @return {!Promise<!StatResult>}
 */
StubFileSystem.prototype.stat = function(path) {
  if (!this.isValidPath_(path))
    return Promise.reject(new AxiomError.Invalid('path', path.originalSpec));

  return this.channel_.sendRequest({
    cmd: 'stat',
    path: path.spec,
  }).then(
    function(response) {
      return response.statResult;
    }.bind(this)
  );
};
<commit_msg>Better handling of error coming from remote fs.<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import AxiomError from 'axiom/core/error';
import FileSystem from 'axiom/fs/base/file_system';

/** @typedef Channel$$module$axiom$fs$stream$channel */
var Channel;

/** @typedef FileSystemManager$$module$axiom$fs$base$file_system_manager */
var FileSystemManager;

/** @typedef {Path$$module$axiom$fs$path} */
var Path;

/** @typedef {StatResult$$module$axiom$fs$stat_result} */
var StatResult;

/**
 * Implementation of a FileSystem that forwards all request over a Channel
 * to a remote file system.
 *
 * @constructor @extends {FileSystem}
 * @param {!FileSystemManager} fileSystemManager
 * @param {!string} name
 * @param {!Channel} channel
 */
export var StubFileSystem = function(fileSystemManager, name, channel) {
  FileSystem.call(this, fileSystemManager, name);

  /** @const @private @type {Channel} */
  this.channel_ = channel;

  /** @type {string} */
  this.description = 'remote file system';
};

export default StubFileSystem;

StubFileSystem.prototype = Object.create(FileSystem.prototype);

/**
 * @private
 * @param {Path} path
 * @return {!boolean}
 */
StubFileSystem.prototype.isValidPath_ = function(path) {
  return !(!path || !path.isValid || path.root !== this.name);
};

/**
 * Send a request to the peer, returning a promise that completes when the
 * response is available.
 * @param {Object} request
 * @return {Promise<Object>}
 */
StubFileSystem.prototype.sendRequest_ = function(request) {
  return this.channel_.sendRequest(request).then(
    function(response) {
      if (response.error)
        return Promise.reject(response.error);
      return response;
    }.bind(this)
  );
};

/**
 * @param {Path} path
 * @return {!Promise<!Object<string, StatResult>>}
 */
StubFileSystem.prototype.list = function(path) {
  if (!this.isValidPath_(path))
    return Promise.reject(new AxiomError.Invalid('path', path.originalSpec));

  return this.sendRequest_({
    cmd: 'list',
    path: path.spec,
  }).then(
    function(response) {
      var result = {};
      for(var name in response.entries) {
        result[name] = response.entries[name];
      }
      return result;
    }.bind(this)
  );
};

/**
 * @param {Path} path
 * @return {!Promise<!StatResult>}
 */
StubFileSystem.prototype.stat = function(path) {
  if (!this.isValidPath_(path))
    return Promise.reject(new AxiomError.Invalid('path', path.originalSpec));

  return this.sendRequest_({
    cmd: 'stat',
    path: path.spec,
  }).then(
    function(response) {
      return response.statResult;
    }.bind(this)
  );
};
<|endoftext|>


<commit_before>import startCase from 'lodash/startCase'
import React from 'react'

import {ALL_TRANSIT_MODES} from '../constants'

import {Select} from './input'

const toStartCase = o => startCase(o.toLowerCase())

const r5Warning =
  'Note: routing engine versions prior to v4.6.0 will use tram regardless.'

/**
 * Only show an empty option if no mode has been selected. Do not allow de-selection.
 */
export default function TransitModeSelector(p) {
  const value = parseInt(p.value)
  return (
    <>
      <Select
        help={r5Warning}
        label='Transit Mode'
        onChange={e => {
          const mode = parseInt(e.target.value)
          if (mode >= 0) p.onChange(mode)
        }}
        value={p.value}
      >
        {ALL_TRANSIT_MODES.map((m, i) => (
          <option key={m} value={i}>
            {toStartCase(m)}
          </option>
        ))}
      </Select>
    </>
  )
}
<commit_msg>Fix lint warning<commit_after>import startCase from 'lodash/startCase'
import React from 'react'

import {ALL_TRANSIT_MODES} from '../constants'

import {Select} from './input'

const toStartCase = o => startCase(o.toLowerCase())

const r5Warning =
  'Note: routing engine versions prior to v4.6.0 will use tram regardless.'

/**
 * Only show an empty option if no mode has been selected. Do not allow de-selection.
 */
export default function TransitModeSelector(p) {
  return (
    <>
      <Select
        help={r5Warning}
        label='Transit Mode'
        onChange={e => {
          const mode = parseInt(e.target.value)
          if (mode >= 0) p.onChange(mode)
        }}
        value={p.value}
      >
        {ALL_TRANSIT_MODES.map((m, i) => (
          <option key={m} value={i}>
            {toStartCase(m)}
          </option>
        ))}
      </Select>
    </>
  )
}
<|endoftext|>


<commit_before>SocialStream.Document = (function(SS, $, undefined){
	var indexCallbacks = [];

	var addIndexCallback = function(callback){
		indexCallbacks.push(callback);
	};

	var index = function(options){
		$.each(indexCallbacks, function(i, callback){ callback(options); });
	};

	var editCallbacks = [];

	var addEditCallback = function(callback){
		editCallbacks.push(callback);
	};

	var edit = function(options){
		$.each(editCallbacks, function(i, callback){ callback(options); });
	};

  var initTagsForm = function(options) {
    $('select[name*="[tag_list]"]').fcbkcomplete({
        json_url: options.tags.path,
        cache: false,
        filter_case: true,
        filter_hide: true,
        newel: false,
        height: 6
    });
  };

  var initNewActivity = function() {
    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $(this).addClass("selected");

      // build document form
      if ($('.wall_input input[name^=document]').length === 0) {
        $('<label/>', {
          "for": 'document_title',
          text: I18n.t('activerecord.attributes.document.title')
        }).insertBefore($('#post_text'));

        $('<textarea/>', {
          name: 'document[description]',
          'class': 'document_description',
          placeholder: I18n.t('document.description.input')
        }).insertAfter($('#post_text'));

        $('.wall_input textarea.document_description').val($('#post_text').val());

        $('#post_text').
          attr('name', 'document[title]').
          attr('placeholder', I18n.t('document.title.input'));

        $('<input>', {
          name: 'document[file]',
          type: 'file',
          style: 'display: none;'
        }).insertAfter('.wall_input textarea.document_description');

        $('.wall_input form').
          attr('action', $(this).attr('data-path')).
          attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

        $('.wall_input input[name="post[owner_id]"]').attr('name', 'document[owner_id');
        SS.Wall.changeRelationSelect('document');
      }

      $('.wall_input input[type=file]').trigger('click');

      $('.wall_input input[type=file]').change(function(){
        $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    });

  };

  var initPagination = function() {
    SS.Pagination.show();
  };

  addIndexCallback(initPagination);

  addEditCallback(initTagsForm);

  SS.Wall.addShowCallback(initNewActivity);

	return {
		edit: edit,
    index: index
  };

})(SocialStream, jQuery);
<commit_msg>Fix tabs<commit_after>SocialStream.Document = (function(SS, $, undefined){
  var indexCallbacks = [];

  var addIndexCallback = function(callback){
    indexCallbacks.push(callback);
  };

  var index = function(options){
    $.each(indexCallbacks, function(i, callback){ callback(options); });
  };

  var editCallbacks = [];

  var addEditCallback = function(callback){
    editCallbacks.push(callback);
  };

  var edit = function(options){
    $.each(editCallbacks, function(i, callback){ callback(options); });
  };

  var initTagsForm = function(options) {
    $('select[name*="[tag_list]"]').fcbkcomplete({
        json_url: options.tags.path,
        cache: false,
        filter_case: true,
        filter_hide: true,
        newel: false,
        height: 6
    });
  };

  var initNewActivity = function() {
    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $(this).addClass("selected");

      // build document form
      if ($('.wall_input input[name^=document]').length === 0) {
        $('<label/>', {
          "for": 'document_title',
          text: I18n.t('activerecord.attributes.document.title')
        }).insertBefore($('#post_text'));

        $('<textarea/>', {
          name: 'document[description]',
          'class': 'document_description',
          placeholder: I18n.t('document.description.input')
        }).insertAfter($('#post_text'));

        $('.wall_input textarea.document_description').val($('#post_text').val());

        $('#post_text').
          attr('name', 'document[title]').
          attr('placeholder', I18n.t('document.title.input'));

        $('<input>', {
          name: 'document[file]',
          type: 'file',
          style: 'display: none;'
        }).insertAfter('.wall_input textarea.document_description');

        $('.wall_input form').
          attr('action', $(this).attr('data-path')).
          attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

        $('.wall_input input[name="post[owner_id]"]').attr('name', 'document[owner_id');
        SS.Wall.changeRelationSelect('document');
      }

      $('.wall_input input[type=file]').trigger('click');

      $('.wall_input input[type=file]').change(function(){
        $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    });

  };

  var initPagination = function() {
    SS.Pagination.show();
  };

  addIndexCallback(initPagination);

  addEditCallback(initTagsForm);

  SS.Wall.addShowCallback(initNewActivity);

  return {
    edit: edit,
    index: index
  };

})(SocialStream, jQuery);
<|endoftext|>


<commit_before>SocialStream.Document = (function(SS, $, undefined){
	var editCallbacks = [];

	var addEditCallback = function(callback){
		editCallbacks.push(callback);
	};

	var edit = function(options){
		$.each(editCallbacks, function(i, callback){ callback(options); });
	};

  var initTagsForm = function(options) {
    $('#document_tag_list').fcbkcomplete({
        json_url: options.tags.path,
        cache: false,
        filter_case: true,
        filter_hide: true,
        newel: false,
        height: 6
    });
  };

  var initNewActivity = function() {
    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $(this).addClass("selected");

      // build document form
      if ($('.wall_input input[name^=document]').length === 0) {
        $('<label/>', {
          "for": 'document_title',
          text: I18n.t('activerecord.attributes.document.title')
        }).insertBefore($('#post_text'));

        $('<textarea/>', {
          name: 'document[description]',
          'class': 'document_description',
          placeholder: I18n.t('document.description.input')
        }).insertAfter($('#post_text'));

        $('.wall_input textarea.document_description').val($('#post_text').val());

        $('#post_text').
          attr('name', 'document[title]').
          attr('placeholder', I18n.t('document.title.input'));

        $('<input>', {
          name: 'document[file]',
          type: 'file'
        }).insertAfter('.wall_input textarea.document_description');

        $('.wall_input form').
          attr('action', $(this).attr('data-path')).
          attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

        $('.wall_input input[name="post[owner_id]"]').attr('name', 'document[owner_id');
        SS.Wall.changeRelationSelect('document');
      }

      if ($('.wall_input input[type=file]').is(":visible")) {
        $('.wall_input input[type=file]').trigger('click');
      }

      $('.wall_input input[type=file]').change(function(){
        $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    });

  };

  addEditCallback(initTagsForm);

  SS.Wall.addShowCallback(initNewActivity);

	return {
		edit: edit
  };

})(SocialStream, jQuery);
<commit_msg>Hide hidden field<commit_after>SocialStream.Document = (function(SS, $, undefined){
	var editCallbacks = [];

	var addEditCallback = function(callback){
		editCallbacks.push(callback);
	};

	var edit = function(options){
		$.each(editCallbacks, function(i, callback){ callback(options); });
	};

  var initTagsForm = function(options) {
    $('#document_tag_list').fcbkcomplete({
        json_url: options.tags.path,
        cache: false,
        filter_case: true,
        filter_hide: true,
        newel: false,
        height: 6
    });
  };

  var initNewActivity = function() {
    $('.wall_input button.new_document').click(function(event){
      event.preventDefault();

      $(this).addClass("selected");

      // build document form
      if ($('.wall_input input[name^=document]').length === 0) {
        $('<label/>', {
          "for": 'document_title',
          text: I18n.t('activerecord.attributes.document.title')
        }).insertBefore($('#post_text'));

        $('<textarea/>', {
          name: 'document[description]',
          'class': 'document_description',
          placeholder: I18n.t('document.description.input')
        }).insertAfter($('#post_text'));

        $('.wall_input textarea.document_description').val($('#post_text').val());

        $('#post_text').
          attr('name', 'document[title]').
          attr('placeholder', I18n.t('document.title.input'));

        $('<input>', {
          name: 'document[file]',
          type: 'file',
          style: 'display: none;'
        }).insertAfter('.wall_input textarea.document_description');

        $('.wall_input form').
          attr('action', $(this).attr('data-path')).
          attr('enctype', 'multipart/form-data'); // this is ignored if done after creating the file input

        $('.wall_input input[name="post[owner_id]"]').attr('name', 'document[owner_id');
        SS.Wall.changeRelationSelect('document');
      }

      $('.wall_input input[type=file]').trigger('click');

      $('.wall_input input[type=file]').change(function(){
        $("#post_text").val($(this).val().replace(/C:\\fakepath\\/i, ''));
      });
    });

  };

  addEditCallback(initTagsForm);

  SS.Wall.addShowCallback(initNewActivity);

	return {
		edit: edit
  };

})(SocialStream, jQuery);
<|endoftext|>


<commit_before>// Use container fluid
var containers = $(".container");
containers.removeClass("container");
containers.addClass("container-fluid");

WINDOW_CONTENTS = window.location.href.split('/')
var SELECTED_LANGUAGE = ''
var PACKAGE_REGEX = ''
var PACKAGE_REPLACEMENT = ''

ATTR1 = '[System.ComponentModel.EditorBrowsable]\n<'

// Navbar Hamburger
$(function () {
    $(".navbar-toggle").click(function () {
        $(this).toggleClass("change");
    })
})

// Select list to replace affix on small screens
$(function () {
    var navItems = $(".sideaffix .level1 > li");

    if (navItems.length == 0) {
        return;
    }

    var selector = $("<select/>");
    selector.addClass("form-control visible-sm visible-xs");
    var form = $("<form/>");
    form.append(selector);
    form.prependTo("article");

    selector.change(function () {
        window.location = $(this).find("option:selected").val();
    })

    function work(item, level) {
        var link = item.children('a');

        var text = link.text();

        for (var i = 0; i < level; ++i) {
            text = '  ' + text;
        }

        selector.append($('<option/>', {
            'value': link.attr('href'),
            'html': text
        }));

        var nested = item.children('ul');

        if (nested.length > 0) {
            nested.children('li').each(function () {
                work($(this), level + 1);
            });
        }
    }

    navItems.each(function () {
        work($(this), 0);
    });
})

$(function () {
    // Inject line breaks and spaces into the code sections
    $(".lang-csharp").each(function () {
        var text = $(this).html();
        text = text.replace(/, /g, ",
	&#09");
        text = text.replace(ATTR1, '<');
        $(this).html(text);
    });

    // Add text to empty links
    $("p > a").each(function () {
        var link = $(this).attr('href')
        if ($(this).text() === "" && $(this).children().attr("src") === "") {
            $(this).html(link)
        }
    });
})

function httpGetAsync(targetUrl, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function httpGetAsyncFallbackOnFail(targetUrl, successCallback, failureCallback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                successCallback(xmlHttp.responseText);
            } else {
                failureCallback(xmlHttp.status)
            }
        }
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function populateOptions(selector, packageName) {
    var versionRequestUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"

    httpGetAsync(versionRequestUrl, function (responseText) {
        var versionselector = document.createElement("select")
        var cv = WINDOW_CONTENTS[6]

        versionselector.className = 'navbar-version-select'
        if (responseText) {
            options = responseText.match(/[^\r\n]+/g)
            for (var i in options) {
                $(versionselector).append('<option value="' + options[i] + '">' + options[i] + '</option>')
            }
        }

        if(cv === 'latest')
        {
            $(versionselector).selectedIndex = 0
        }
        else {
            $(versionselector).val(cv);
        }

        $(selector).append(versionselector)

        $(versionselector).change(function () {
            targetVersion = $(this).val()
            url = WINDOW_CONTENTS.slice()
            url[6] = targetVersion
            var targetUrl = url.join('/')
            httpGetAsyncFallbackOnFail(targetUrl, (unused) => window.location.href = url.join('/'),
                (failureStatus) => window.location.href = getPackageUrl(SELECTED_LANGUAGE, packageName, targetVersion))
        });

    })
}

function httpGetLatestAsync(targetUrl, latestVersions, packageName) {
    httpGetAsync(targetUrl, function (responseText) {
        if (responseText) {
            version = responseText.match(/[^\r\n]+/g)
            $(latestVersions).append('
' + version + '
')
        }
    })
}

function populateIndexList(selector, packageName) {
    var url = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"
    var latestGAUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-ga"
    var latestPreviewUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-preview"
    var latestVersions = document.createElement("ul")
    httpGetLatestAsync(latestGAUrl, latestVersions, packageName)
    httpGetLatestAsync(latestPreviewUrl, latestVersions, packageName)
    var publishedVersions = $('

')
    var collapsible = $('
   Other versions
')
    // Check whether it has display name tag.
    if ($(selector).next().is('h5')) {
        $(selector).next().after(latestVersions)
    } else {
        $(selector).after(latestVersions)
    }
    $(latestVersions).after(collapsible)
    $(collapsible).after(publishedVersions)
    // Add collapsible arrows on versioned docs.
    $(collapsible).on('click', function(event) {
        event.preventDefault();
        if (collapsible.hasClass('disable')) {
            return
        }
        $(this).toggleClass('down')
        if ($(this).hasClass('down')) {
            if (!$(selector).hasClass('loaded')){
                httpGetAsync(url, function (responseText) {
                    if (responseText) {
                        options = responseText.match(/[^\r\n]+/g)
                        for (var i in options) {
                            $(publishedVersions).append('
' + options[i] + '
')

                        }
                    }
                    else {
                        $(publishedVersions).append('
No discovered versions present in blob storage.
')
                    }
                    $(selector).addClass("loaded")
                })
            }
            $(publishedVersions).show()
        } else {
            $(publishedVersions).hide()
        }
    });
}

function getPackageUrl(language, package, version) {
    return "https://azuresdkdocs.blob.core.windows.net/$web/" + language + "/" + package + "/" + version + "/index.html"
}

// Populate Versions
$(function () {
    if (WINDOW_CONTENTS.length < 7 && WINDOW_CONTENTS[WINDOW_CONTENTS.length - 1] != 'index.html') {
        console.log("Run PopulateList")

        $('h4').each(function () {
            var pkgName = $(this).text().replace(PACKAGE_REGEX, PACKAGE_REPLACEMENT)
            populateIndexList($(this), pkgName)
        })
    }

    if (WINDOW_CONTENTS.length > 7) {
        var pkgName = WINDOW_CONTENTS[5]
        populateOptions($('#navbar'), pkgName)
    }
})
<commit_msg>Sync eng/common directory with azure-sdk-tools for PR 1396 (#18856)<commit_after>// Use container fluid
var containers = $(".container");
containers.removeClass("container");
containers.addClass("container-fluid");

WINDOW_CONTENTS = window.location.href.split('/')
var SELECTED_LANGUAGE = ''
var PACKAGE_REGEX = ''
var PACKAGE_REPLACEMENT = ''

ATTR1 = '[System.ComponentModel.EditorBrowsable]\n<'

// Navbar Hamburger
$(function () {
    $(".navbar-toggle").click(function () {
        $(this).toggleClass("change");
    })
})

// Select list to replace affix on small screens
$(function () {
    var navItems = $(".sideaffix .level1 > li");

    if (navItems.length == 0) {
        return;
    }

    var selector = $("<select/>");
    selector.addClass("form-control visible-sm visible-xs");
    var form = $("<form/>");
    form.append(selector);
    form.prependTo("article");

    selector.change(function () {
        window.location = $(this).find("option:selected").val();
    })

    function work(item, level) {
        var link = item.children('a');

        var text = link.text();

        for (var i = 0; i < level; ++i) {
            text = '  ' + text;
        }

        selector.append($('<option/>', {
            'value': link.attr('href'),
            'html': text
        }));

        var nested = item.children('ul');

        if (nested.length > 0) {
            nested.children('li').each(function () {
                work($(this), level + 1);
            });
        }
    }

    navItems.each(function () {
        work($(this), 0);
    });
})

$(function () {
    // Inject line breaks and spaces into the code sections
    $(".lang-csharp").each(function () {
        var text = $(this).html();
        text = text.replace(/, /g, ",
	&#09");
        text = text.replace(ATTR1, '<');
        $(this).html(text);
    });

    // Add text to empty links
    $("p > a").each(function () {
        var link = $(this).attr('href')
        if ($(this).text() === "" && $(this).children().attr("src") === "") {
            $(this).html(link)
        }
    });
})

function httpGetAsync(targetUrl, callback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
            callback(xmlHttp.responseText);
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function httpGetAsyncFallbackOnFail(targetUrl, successCallback, failureCallback) {
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4) {
            if (xmlHttp.status == 200) {
                successCallback(xmlHttp.responseText);
            } else {
                failureCallback(xmlHttp.status)
            }
        }
    }
    xmlHttp.open("GET", targetUrl, true); // true for asynchronous
    xmlHttp.send(null);
}

function populateOptions(selector, packageName) {
    var versionRequestUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"

    httpGetAsync(versionRequestUrl, function (responseText) {
        var versionselector = document.createElement("select")
        var cv = WINDOW_CONTENTS[6]

        versionselector.className = 'navbar-version-select'
        if (responseText) {
            options = responseText.match(/[^\r\n]+/g)
            for (var i in options) {
                $(versionselector).append('<option value="' + options[i] + '">' + options[i] + '</option>')
            }
        }

        if(cv === 'latest')
        {
            $(versionselector).selectedIndex = 0
        }
        else {
            $(versionselector).val(cv);
        }

        $(selector).append(versionselector)

        $(versionselector).change(function () {
            targetVersion = $(this).val()
            url = WINDOW_CONTENTS.slice()
            url[6] = targetVersion
            var targetUrl = url.join('/')
            httpGetAsyncFallbackOnFail(targetUrl, (unused) => window.location.href = url.join('/'),
                (failureStatus) => window.location.href = getPackageUrl(SELECTED_LANGUAGE, packageName, targetVersion))
        });

    })
}

function httpGetLatestAsync(targetUrl, latestVersions, packageName) {
    httpGetAsync(targetUrl, function (responseText) {
        if (responseText) {
            version = responseText.match(/[^\r\n]+/g)
            $(latestVersions).append('
' + version + '
')
        }
    })
}

function loadedOtherVersions(url, latestVersions, publishedVersions, selector, collapsible, packageName) {
    var hasAdded = function (currentVersion) {
        return $(publishedVersions).children('li').filter(function() {
            return $(this).text() === currentVersion
        }).length || $(latestVersions).children('li').filter(function() {
            return $(this).text() === currentVersion
        }).length
    }
    httpGetAsync(url, function (responseText) {
        if (responseText) {
            options = responseText.match(/[^\r\n]+/g)
            for (var i in options) {
                if (!hasAdded(options[i])) {
                    $(publishedVersions).append('
' + options[i] + '
')
                }
            }
        }
        else {
            $(publishedVersions).append('
No discovered versions present in blob storage.
')
        }
        $(selector).addClass("loaded")
        if ($(publishedVersions).children('li').length < 1) {
            $(collapsible).remove()
        }
    })
}

function populateIndexList(selector, packageName) {
    var url = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/versions"
    var latestGAUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-ga"
    var latestPreviewUrl = "https://azuresdkdocs.blob.core.windows.net/$web/" + SELECTED_LANGUAGE + "/" + packageName + "/versioning/latest-preview"
    var latestVersions = document.createElement("ul")
    httpGetLatestAsync(latestGAUrl, latestVersions, packageName)
    httpGetLatestAsync(latestPreviewUrl, latestVersions, packageName)
    var publishedVersions = $('

')
    var collapsible = $('
   Other versions
')
    // Check whether it has display name tag.
    if ($(selector).next().is('h5')) {
        $(selector).next().after(latestVersions)
    } else {
        $(selector).after(latestVersions)
    }
    $(latestVersions).after(collapsible)
    $(collapsible).after(publishedVersions)

    // Add collapsible arrows on versioned docs.
    $(collapsible).on('click', function(event) {
        event.preventDefault();
        if (collapsible.hasClass('disable')) {
            return
        }
        $(this).toggleClass('down')
        if ($(this).hasClass('down')) {
            if (!$(selector).hasClass('loaded')){
                loadedOtherVersions(url, latestVersions, publishedVersions, selector, collapsible, packageName)
            }
            $(publishedVersions).show()
        } else {
            $(publishedVersions).hide()
        }
    });
}

function getPackageUrl(language, package, version) {
    return "https://azuresdkdocs.blob.core.windows.net/$web/" + language + "/" + package + "/" + version + "/index.html"
}

// Populate Versions
$(function () {
    if (WINDOW_CONTENTS.length < 7 && WINDOW_CONTENTS[WINDOW_CONTENTS.length - 1] != 'index.html') {
        console.log("Run PopulateList")

        $('h4').each(function () {
            var pkgName = $(this).text().replace(PACKAGE_REGEX, PACKAGE_REPLACEMENT)
            populateIndexList($(this), pkgName)
        })
    }

    if (WINDOW_CONTENTS.length > 7) {
        var pkgName = WINDOW_CONTENTS[5]
        populateOptions($('#navbar'), pkgName)
    }
})
<|endoftext|>


<commit_before>
var url = require('url');
var util = require('util');

var kaltura = module.exports = require('../KalturaManager');

/**
 * @service cuePoints
 */
var KalturaCuePointsManager = function(){
	this.cuePoints = {};
	this.interval = null;
	this.lastUpdatedAt = null;

	this.initClient(KalturaConfig.config.client);
};
util.inherits(KalturaCuePointsManager, kaltura.KalturaManager);

/**
 * @type handle to setInterval
 */
KalturaCuePointsManager.prototype.interval = null;

/**
 * @type object
 *
 * key: entry id
 * value: object
 *  - finishCallback: function called when entry is not required anymore and restorable action could be unstored
 *  - cuePoints: object (key: cue-point id, value: KalturaCuePoint)
 */
KalturaCuePointsManager.prototype.cuePoints = null;

/**
 * @type int timestamd in seconds, used to fetch cue-points that changed in last few seconds
 */
KalturaCuePointsManager.prototype.lastUpdatedAt = null;

/**
 * @param entryId
 */
KalturaCuePointsManager.prototype.verifyEntryRequired = function(entryId){
	var entryRequiredKey = KalturaCache.getEntryRequired(entryId);
	var oldestSegmentTimeKey = KalturaCache.getOldestSegmentTime(entryId);
	var cuePointsKey = KalturaCache.getCuePoints(entryId);

	var This = this;
	var deleteCuePoint = function(){
		This.cuePoints[entryId].finishCallback();
		delete This.cuePoints[entryId];
		KalturaCache.del(cuePointsKey);
	};

	KalturaCache.get(entryRequiredKey, function(data){
		if(!data)
			deleteCuePoint();
	}, deleteCuePoint);

	if(This.cuePoints[entryId] && This.cuePoints[entryId].cuePoints){
		KalturaCache.get(oldestSegmentTimeKey, function(oldestSegmentTime){
			if(oldestSegmentTime){
				var changed = false;
				for(var cuePointId in This.cuePoints[entryId].cuePoints){
					var cuePoint = This.cuePoints[entryId].cuePoints[cuePointId];
					if((cuePoint.startTime && oldestSegmentTime.offset > (cuePoint.startTime + cuePoint.duration)) ||
						(cuePoint.triggeredAt*1000 && oldestSegmentTime.timestamp > (cuePoint.triggeredAt*1000 + cuePoint.duration))){
						KalturaLogger.log('Deleting handled cue point from cache: ' + cuePointId);
						delete This.cuePoints[entryId].cuePoints[cuePointId];
						changed = true;
					}
				}
				if(changed)
					KalturaCache.set(cuePointsKey, This.cuePoints[entryId].cuePoints, KalturaConfig.config.cache.cuePoint);
			}
		}, function(err){});
	}
};

/**
 * @param cuePointsList KalturaCuePointListResponse
 * @param filter KalturaCuePointFilter
 * @param pager KalturaFilterPager
 */
KalturaCuePointsManager.prototype.handleCuePointsList = function(cuePointsList, filter, pager){
	if(!this.run){
		return;
	}

	if(cuePointsList.objectType == 'KalturaAPIException'){
		KalturaLogger.error('Client [cuePoint.list][' + cuePointsList.code + ']: ' + cuePointsList.message);
	}
	else{
		var This = this;

		if(cuePointsList.objects.length == pager.pageSize){
			pager.pageIndex++;
			this.client.cuePoint.listAction(function(nextCuePointsList){
				This.handleCuePointsList(nextCuePointsList, filter, pager);
			}, filter, pager);
		}

		for(var i = 0; i < cuePointsList.objects.length; i++){
			var cuePoint = cuePointsList.objects[i];
			var entryId = cuePoint.entryId;
			if(!this.cuePoints[entryId]){
				continue;
			}
			this.lastUpdatedAt = Math.max(this.lastUpdatedAt, cuePoint.updatedAt);

			this.cuePoints[entryId].cuePoints[cuePoint.id] = cuePoint;

			var cuePointsKey = KalturaCache.getCuePoints(entryId);
			KalturaCache.set(cuePointsKey, this.cuePoints[entryId].cuePoints, KalturaConfig.config.cache.cuePoint);
		}
	}
};

/**
 * List cue-points for all entries, executed periodically
 */
KalturaCuePointsManager.prototype.loop = function(){
	if(!this.sessionReady)
		return;

	var entryIds = [];
	for(var entryId in this.cuePoints){
		entryIds.push(entryId);
		this.verifyEntryRequired(entryId);
	}

	if(!entryIds.length){
		clearInterval(this.interval);
		return;
	}

	var filter = new kaltura.client.objects.KalturaAdCuePointFilter();
	filter.entryIdIn = entryIds.join(',');
	filter.statusEqual = kaltura.client.enums.KalturaCuePointStatus.READY;
	if(this.lastUpdatedAt)
		filter.updatedAtGreaterThanOrEqual = this.lastUpdatedAt;

	var pager = new kaltura.client.objects.KalturaFilterPager();
	pager.pageSize = 500;

	var This = this;
	this.client.cuePoint.listAction(function(cuePointsList){
		This.handleCuePointsList(cuePointsList, filter, pager);
	}, filter, pager);
};

/**
 * Add entry to be watched
 *
 * @action cuePoints.watch
 *
 * @param entryId
 */
KalturaCuePointsManager.prototype.watch = function(request, response, params){
	params = this.parsePlayServerParams(response, params, ['entryId', 'partnerId']);
	if(!params)
		return;

	response.dir(params);

	if(this.cuePoints[params.entryId]){
		response.writeHead(200);
		response.end('Entry [' + params.entryId + '] already watched');
		return;
	}
	else{
		this.callRestorableAction('cuePoints', 'watchEntry', params);
	}

	response.writeHead(200);
	response.end('OK');
};

/**
 * Restorable action, add entry to be watched
 *
 * @param params.entryId
 * @param finishCallback function to be called when this entry watch is not needed anymore
 */
KalturaCuePointsManager.prototype.watchEntry = function(params, finishCallback){
	KalturaLogger.dir(params);

	this.cuePoints[params.entryId] = {
		finishCallback: finishCallback,
		cuePoints: {}
	};

	if(!this.interval){
		var This = this;
		this.interval = setInterval(function(){
			if(!This.run){
				clearInterval(This.interval);
				return;
			}

			This.loop();
		}, 10000);
	}

	this.loop();
};

module.exports.KalturaCuePointsManager = KalturaCuePointsManager;
<commit_msg>Few bug fixes around cue points not being retrieved after a while 1. Clearing interval did not set the class variable to null, thus once interval was cleared for a process it would not be re-initiated until a server restart was made. 2. Fix race condition: delete handled cue points only if entry is still required.<commit_after>
var url = require('url');
var util = require('util');

var kaltura = module.exports = require('../KalturaManager');

/**
 * @service cuePoints
 */
var KalturaCuePointsManager = function(){
	this.cuePoints = {};
	this.interval = null;
	this.lastUpdatedAt = null;

	this.initClient(KalturaConfig.config.client);
};
util.inherits(KalturaCuePointsManager, kaltura.KalturaManager);

/**
 * @type handle to setInterval
 */
KalturaCuePointsManager.prototype.interval = null;

/**
 * @type object
 *
 * key: entry id
 * value: object
 *  - finishCallback: function called when entry is not required anymore and restorable action could be unstored
 *  - cuePoints: object (key: cue-point id, value: KalturaCuePoint)
 */
KalturaCuePointsManager.prototype.cuePoints = null;

/**
 * @type int timestamd in seconds, used to fetch cue-points that changed in last few seconds
 */
KalturaCuePointsManager.prototype.lastUpdatedAt = null;

/**
 * @param entryId
 */
KalturaCuePointsManager.prototype.verifyEntryRequired = function(entryId){
	var entryRequiredKey = KalturaCache.getEntryRequired(entryId);
	var oldestSegmentTimeKey = KalturaCache.getOldestSegmentTime(entryId);
	var cuePointsKey = KalturaCache.getCuePoints(entryId);

	var This = this;
	var deleteCuePoint = function(){
		This.cuePoints[entryId].finishCallback();
		delete This.cuePoints[entryId];
		KalturaCache.del(cuePointsKey);
	};

	KalturaCache.get(entryRequiredKey, function(data){
		if(!data){
			KalturaLogger.log('Deleting cue points for entry ' + entryId);
			deleteCuePoint();
		}
		else{
			if(This.cuePoints[entryId] && This.cuePoints[entryId].cuePoints){
				KalturaCache.get(oldestSegmentTimeKey, function(oldestSegmentTime){
					if(oldestSegmentTime){
						var changed = false;
						for(var cuePointId in This.cuePoints[entryId].cuePoints){
							var cuePoint = This.cuePoints[entryId].cuePoints[cuePointId];
							if((cuePoint.startTime && oldestSegmentTime.offset > (cuePoint.startTime + cuePoint.duration)) ||
								(cuePoint.triggeredAt*1000 && oldestSegmentTime.timestamp > (cuePoint.triggeredAt*1000 + cuePoint.duration))){
								KalturaLogger.log('Deleting handled cue point from cache: ' + cuePointId);
								delete This.cuePoints[entryId].cuePoints[cuePointId];
								changed = true;
							}
						}
						if(changed)
							KalturaCache.set(cuePointsKey, This.cuePoints[entryId].cuePoints, KalturaConfig.config.cache.cuePoint);
					}
				}, function(err){});
			}
		}
	}, deleteCuePoint);
};

/**
 * @param cuePointsList KalturaCuePointListResponse
 * @param filter KalturaCuePointFilter
 * @param pager KalturaFilterPager
 */
KalturaCuePointsManager.prototype.handleCuePointsList = function(cuePointsList, filter, pager){
	if(!this.run){
		return;
	}

	if(cuePointsList.objectType == 'KalturaAPIException'){
		KalturaLogger.error('Client [cuePoint.list][' + cuePointsList.code + ']: ' + cuePointsList.message);
	}
	else{
		var This = this;

		if(cuePointsList.objects.length == pager.pageSize){
			pager.pageIndex++;
			this.client.cuePoint.listAction(function(nextCuePointsList){
				This.handleCuePointsList(nextCuePointsList, filter, pager);
			}, filter, pager);
		}

		for(var i = 0; i < cuePointsList.objects.length; i++){
			var cuePoint = cuePointsList.objects[i];
			var entryId = cuePoint.entryId;
			if(!this.cuePoints[entryId]){
				continue;
			}
			this.lastUpdatedAt = Math.max(this.lastUpdatedAt, cuePoint.updatedAt);

			this.cuePoints[entryId].cuePoints[cuePoint.id] = cuePoint;

			var cuePointsKey = KalturaCache.getCuePoints(entryId);
			KalturaCache.set(cuePointsKey, this.cuePoints[entryId].cuePoints, KalturaConfig.config.cache.cuePoint);
		}
	}
};

/**
 * List cue-points for all entries, executed periodically
 */
KalturaCuePointsManager.prototype.loop = function(){
	if(!this.sessionReady)
		return;

	var entryIds = [];
	for(var entryId in this.cuePoints){
		entryIds.push(entryId);
		this.verifyEntryRequired(entryId);
	}

	if(!entryIds.length){
		clearInterval(this.interval);
		KalturaLogger.log('No entries left to monitor, clearing cue points interval for pId ' + process.pid);
		this.interval = null;
		return;
	}

	var filter = new kaltura.client.objects.KalturaAdCuePointFilter();
	filter.entryIdIn = entryIds.join(',');
	filter.statusEqual = kaltura.client.enums.KalturaCuePointStatus.READY;
	if(this.lastUpdatedAt)
		filter.updatedAtGreaterThanOrEqual = this.lastUpdatedAt;

	var pager = new kaltura.client.objects.KalturaFilterPager();
	pager.pageSize = 500;

	var This = this;
	this.client.cuePoint.listAction(function(cuePointsList){
		This.handleCuePointsList(cuePointsList, filter, pager);
	}, filter, pager);
};

/**
 * Add entry to be watched
 *
 * @action cuePoints.watch
 *
 * @param entryId
 */
KalturaCuePointsManager.prototype.watch = function(request, response, params){
	params = this.parsePlayServerParams(response, params, ['entryId', 'partnerId']);
	if(!params)
		return;

	response.dir(params);

	if(this.cuePoints[params.entryId]){
		response.writeHead(200);
		response.end('Entry [' + params.entryId + '] already watched');
		return;
	}
	else{
		this.callRestorableAction('cuePoints', 'watchEntry', params);
	}

	response.writeHead(200);
	response.end('OK');
};

/**
 * Restorable action, add entry to be watched
 *
 * @param params.entryId
 * @param finishCallback function to be called when this entry watch is not needed anymore
 */
KalturaCuePointsManager.prototype.watchEntry = function(params, finishCallback){
	KalturaLogger.dir(params);

	this.cuePoints[params.entryId] = {
		finishCallback: finishCallback,
		cuePoints: {}
	};

	if(!this.interval){
		var This = this;
		this.interval = setInterval(function(){
			if(!This.run){
				clearInterval(This.interval);
				KalturaLogger.log('Run variable is false clearing cue points interval for pId ' + process.pid);
				This.interval = null;
				return;
			}

			This.loop();
		}, 10000);
	}

	this.loop();
};

module.exports.KalturaCuePointsManager = KalturaCuePointsManager;
<|endoftext|>


<commit_before>const _ = require('lodash/fp')
const jsonRpc = require('../../common/json-rpc')

const BN = require('../../../bn')
const E = require('../../../error')
const logger = require('../../../logger')
const { utils: coinUtils } = require('@lamassu/coins')

const cryptoRec = coinUtils.getCryptoCurrency('BTC')
const unitScale = cryptoRec.unitScale

const rpcConfig = jsonRpc.rpcConfig(cryptoRec)

const SUPPORTS_BATCHING = true

function fetch (method, params) {
  return jsonRpc.fetch(rpcConfig, method, params)
}

function errorHandle (e) {
  const err = JSON.parse(e.message)
  switch (err.code) {
    case -4:
      return loadWallet()
    case -5:
      return logger.error(`${err}`)
    case -6:
      throw new E.InsufficientFundsError()
    case -18:
      return createWallet()
    default:
      throw e
  }
}

function checkCryptoCode (cryptoCode) {
  if (cryptoCode !== 'BTC') return Promise.reject(new Error('Unsupported crypto: ' + cryptoCode))
  return Promise.resolve()
}

function createWallet () {
  return fetch('createwallet', ['wallet'])
    .catch(errorHandle)
}

function loadWallet () {
  return fetch('loadwallet', ['wallet', true])
    .catch(errorHandle)
}

function accountBalance (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getwalletinfo'))
    .then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

function accountUnconfirmedBalance (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getwalletinfo'))
    .then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

// We want a balance that includes all spends (0 conf) but only deposits that
// have at least 1 confirmation. getbalance does this for us automatically.
function balance (account, cryptoCode, settings, operatorId) {
  return accountBalance(cryptoCode)
}

function estimateFee () {
  return fetch('estimatesmartfee', [6, 'unset'])
    .then(result => BN(result.feerate))
    .catch(() => {})
}

function calculateFeeDiscount (feeMultiplier) {
  // 0 makes bitcoind do automatic fee selection
  const AUTOMATIC_FEE = 0
  if (!feeMultiplier || feeMultiplier.eq(1)) return AUTOMATIC_FEE
  return estimateFee()
    .then(estimatedFee => {
      if (!estimatedFee) return AUTOMATIC_FEE
      const newFee = estimatedFee.times(feeMultiplier)
      if (newFee.lt(0.00001) || newFee.gt(0.1)) return AUTOMATIC_FEE
      return newFee
    })
}

function sendCoins (account, tx, settings, operatorId, feeMultiplier) {
  const { toAddress, cryptoAtoms, cryptoCode } = tx
  const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)

  return checkCryptoCode(cryptoCode)
    .then(() => calculateFeeDiscount(feeMultiplier))
    .then(newFee => fetch('settxfee', [newFee]))
    .then(() => fetch('sendtoaddress', [toAddress, coins]))
    .then((txId) => fetch('gettransaction', [txId]))
    .then((res) => _.pick(['fee', 'txid'], res))
    .then((pickedObj) => {
      return {
        fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
        txid: pickedObj.txid
      }
    })
    .catch(errorHandle)
}

function sendCoinsBatch (account, txs, cryptoCode, feeMultiplier) {
  return checkCryptoCode(cryptoCode)
    .then(() => calculateFeeDiscount(feeMultiplier))
    .then(newFee => fetch('settxfee', [newFee]))
    .then(() => _.reduce((acc, value) => ({
      ...acc,
      [value.toAddress]: _.isNil(acc[value.toAddress])
        ? BN(value.cryptoAtoms).shiftedBy(-unitScale).toFixed(8)
        : BN(acc[value.toAddress]).plus(BN(value.cryptoAtoms).shiftedBy(-unitScale).toFixed(8))
    }), {}, txs))
    .then((obj) => fetch('sendmany', ['', obj]))
    .then((txId) => fetch('gettransaction', [txId]))
    .then((res) => _.pick(['fee', 'txid'], res))
    .then((pickedObj) => ({
      fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
      txid: pickedObj.txid
    }))
    .catch(errorHandle)
}

function newAddress (account, info, tx, settings, operatorId) {
  return checkCryptoCode(info.cryptoCode)
    .then(() => fetch('getnewaddress'))
    .catch(errorHandle)
}

function addressBalance (address, confs) {
  return fetch('getreceivedbyaddress', [address, confs])
    .then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

function confirmedBalance (address, cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => addressBalance(address, 1))
}

function pendingBalance (address, cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => addressBalance(address, 0))
}

function getStatus (account, tx, requested, settings, operatorId) {
  const { toAddress, cryptoCode } = tx
  return checkCryptoCode(cryptoCode)
    .then(() => confirmedBalance(toAddress, cryptoCode))
    .then(confirmed => {
      if (confirmed.gte(requested)) return { receivedCryptoAtoms: confirmed, status: 'confirmed' }

      return pendingBalance(toAddress, cryptoCode)
        .then(pending => {
          if (pending.gte(requested)) return { receivedCryptoAtoms: pending, status: 'authorized' }
          if (pending.gt(0)) return { receivedCryptoAtoms: pending, status: 'insufficientFunds' }
          return { receivedCryptoAtoms: pending, status: 'notSeen' }
        })
    })
}

function newFunding (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode)
    .then(() => {
      const promises = [
        accountUnconfirmedBalance(cryptoCode),
        accountBalance(cryptoCode),
        newAddress(account, { cryptoCode })
      ]

      return Promise.all(promises)
    })
    .then(([fundingPendingBalance, fundingConfirmedBalance, fundingAddress]) => ({
      fundingPendingBalance,
      fundingConfirmedBalance,
      fundingAddress
    }))
    .catch(console.log)
}

function cryptoNetwork (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode)
    .then(() => parseInt(rpcConfig.port, 10) === 18332 ? 'test' : 'main')
}

function fetchRBF (txId) {
  return fetch('getmempoolentry', [txId])
    .then((res) => {
      return [txId, res['bip125-replaceable']]
    })
    .catch(err => {
      errorHandle(err)
      return [txId, true]
    })
}

function checkBlockchainStatus (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getblockchaininfo'))
    .then(res => !!res['initialblockdownload'] ? 'syncing' : 'ready')
}

module.exports = {
  balance,
  sendCoins,
  newAddress,
  getStatus,
  newFunding,
  cryptoNetwork,
  fetchRBF,
  estimateFee,
  sendCoinsBatch,
  checkBlockchainStatus,
  SUPPORTS_BATCHING
}
<commit_msg>fix: remove log<commit_after>const _ = require('lodash/fp')
const jsonRpc = require('../../common/json-rpc')

const BN = require('../../../bn')
const E = require('../../../error')
const logger = require('../../../logger')
const { utils: coinUtils } = require('@lamassu/coins')

const cryptoRec = coinUtils.getCryptoCurrency('BTC')
const unitScale = cryptoRec.unitScale

const rpcConfig = jsonRpc.rpcConfig(cryptoRec)

const SUPPORTS_BATCHING = true

function fetch (method, params) {
  return jsonRpc.fetch(rpcConfig, method, params)
}

function errorHandle (e) {
  const err = JSON.parse(e.message)
  switch (err.code) {
    case -4:
      return loadWallet()
    case -5:
      return logger.error(`${err}`)
    case -6:
      throw new E.InsufficientFundsError()
    case -18:
      return createWallet()
    default:
      throw e
  }
}

function checkCryptoCode (cryptoCode) {
  if (cryptoCode !== 'BTC') return Promise.reject(new Error('Unsupported crypto: ' + cryptoCode))
  return Promise.resolve()
}

function createWallet () {
  return fetch('createwallet', ['wallet'])
    .catch(errorHandle)
}

function loadWallet () {
  return fetch('loadwallet', ['wallet', true])
    .catch(errorHandle)
}

function accountBalance (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getwalletinfo'))
    .then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

function accountUnconfirmedBalance (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getwalletinfo'))
    .then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

// We want a balance that includes all spends (0 conf) but only deposits that
// have at least 1 confirmation. getbalance does this for us automatically.
function balance (account, cryptoCode, settings, operatorId) {
  return accountBalance(cryptoCode)
}

function estimateFee () {
  return fetch('estimatesmartfee', [6, 'unset'])
    .then(result => BN(result.feerate))
    .catch(() => {})
}

function calculateFeeDiscount (feeMultiplier) {
  // 0 makes bitcoind do automatic fee selection
  const AUTOMATIC_FEE = 0
  if (!feeMultiplier || feeMultiplier.eq(1)) return AUTOMATIC_FEE
  return estimateFee()
    .then(estimatedFee => {
      if (!estimatedFee) return AUTOMATIC_FEE
      const newFee = estimatedFee.times(feeMultiplier)
      if (newFee.lt(0.00001) || newFee.gt(0.1)) return AUTOMATIC_FEE
      return newFee
    })
}

function sendCoins (account, tx, settings, operatorId, feeMultiplier) {
  const { toAddress, cryptoAtoms, cryptoCode } = tx
  const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)

  return checkCryptoCode(cryptoCode)
    .then(() => calculateFeeDiscount(feeMultiplier))
    .then(newFee => fetch('settxfee', [newFee]))
    .then(() => fetch('sendtoaddress', [toAddress, coins]))
    .then((txId) => fetch('gettransaction', [txId]))
    .then((res) => _.pick(['fee', 'txid'], res))
    .then((pickedObj) => {
      return {
        fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
        txid: pickedObj.txid
      }
    })
    .catch(errorHandle)
}

function sendCoinsBatch (account, txs, cryptoCode, feeMultiplier) {
  return checkCryptoCode(cryptoCode)
    .then(() => calculateFeeDiscount(feeMultiplier))
    .then(newFee => fetch('settxfee', [newFee]))
    .then(() => _.reduce((acc, value) => ({
      ...acc,
      [value.toAddress]: _.isNil(acc[value.toAddress])
        ? BN(value.cryptoAtoms).shiftedBy(-unitScale).toFixed(8)
        : BN(acc[value.toAddress]).plus(BN(value.cryptoAtoms).shiftedBy(-unitScale).toFixed(8))
    }), {}, txs))
    .then((obj) => fetch('sendmany', ['', obj]))
    .then((txId) => fetch('gettransaction', [txId]))
    .then((res) => _.pick(['fee', 'txid'], res))
    .then((pickedObj) => ({
      fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
      txid: pickedObj.txid
    }))
    .catch(errorHandle)
}

function newAddress (account, info, tx, settings, operatorId) {
  return checkCryptoCode(info.cryptoCode)
    .then(() => fetch('getnewaddress'))
    .catch(errorHandle)
}

function addressBalance (address, confs) {
  return fetch('getreceivedbyaddress', [address, confs])
    .then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
    .catch(errorHandle)
}

function confirmedBalance (address, cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => addressBalance(address, 1))
}

function pendingBalance (address, cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => addressBalance(address, 0))
}

function getStatus (account, tx, requested, settings, operatorId) {
  const { toAddress, cryptoCode } = tx
  return checkCryptoCode(cryptoCode)
    .then(() => confirmedBalance(toAddress, cryptoCode))
    .then(confirmed => {
      if (confirmed.gte(requested)) return { receivedCryptoAtoms: confirmed, status: 'confirmed' }

      return pendingBalance(toAddress, cryptoCode)
        .then(pending => {
          if (pending.gte(requested)) return { receivedCryptoAtoms: pending, status: 'authorized' }
          if (pending.gt(0)) return { receivedCryptoAtoms: pending, status: 'insufficientFunds' }
          return { receivedCryptoAtoms: pending, status: 'notSeen' }
        })
    })
}

function newFunding (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode)
    .then(() => {
      const promises = [
        accountUnconfirmedBalance(cryptoCode),
        accountBalance(cryptoCode),
        newAddress(account, { cryptoCode })
      ]

      return Promise.all(promises)
    })
    .then(([fundingPendingBalance, fundingConfirmedBalance, fundingAddress]) => ({
      fundingPendingBalance,
      fundingConfirmedBalance,
      fundingAddress
    }))
    .catch(errorHandle)
}

function cryptoNetwork (account, cryptoCode, settings, operatorId) {
  return checkCryptoCode(cryptoCode)
    .then(() => parseInt(rpcConfig.port, 10) === 18332 ? 'test' : 'main')
}

function fetchRBF (txId) {
  return fetch('getmempoolentry', [txId])
    .then((res) => {
      return [txId, res['bip125-replaceable']]
    })
    .catch(err => {
      errorHandle(err)
      return [txId, true]
    })
}

function checkBlockchainStatus (cryptoCode) {
  return checkCryptoCode(cryptoCode)
    .then(() => fetch('getblockchaininfo'))
    .then(res => !!res['initialblockdownload'] ? 'syncing' : 'ready')
}

module.exports = {
  balance,
  sendCoins,
  newAddress,
  getStatus,
  newFunding,
  cryptoNetwork,
  fetchRBF,
  estimateFee,
  sendCoinsBatch,
  checkBlockchainStatus,
  SUPPORTS_BATCHING
}
<|endoftext|>


<commit_before>"use strict";

var lastTime = 0;
var vendors = ['webkit', 'moz'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x)
{
    window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
    window.cancelAnimationFrame =
        window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame)
{
    window.requestAnimationFrame = function (callback)
    {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16 - currTime + lastTime);
        var id = window.setTimeout(function ()
            {
                callback(currTime + timeToCall);
            },
            timeToCall
        );
        lastTime = currTime + timeToCall;
        return id;
    };
}

if (!window.cancelAnimationFrame)
{
    window.cancelAnimationFrame = function (id)
    {
        clearTimeout(id);
    };
}

export default {
    request: window.requestAnimationFrame.bind(window),
    cancel: window.cancelAnimationFrame.bind(window)
};
<commit_msg>Remove requestAnimationFrame polyfill<commit_after><|endoftext|>


<commit_before>/*global require, exports*/
var util = require('util'),
    _ = require('underscore'),
    JavaScript = require('../assets/JavaScript'),
    uglifyJs = JavaScript.uglifyJs,
    uglifyAst = JavaScript.uglifyAst,
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Relation = require('./Relation');

function JavaScriptGetStaticUrl(config) {
    Relation.call(this, config);
}

util.inherits(JavaScriptGetStaticUrl, Relation);

extendWithGettersAndSetters(JavaScriptGetStaticUrl.prototype, {
    inline: function () {
        Relation.prototype.inline.call(this);
        var newNode;
        if (this.omitFunctionCall) {
            newNode = this.to.toAst();
        } else {
            if (this.node instanceof uglifyJs.AST_Call) {
                this.node.args = [this.to.toAst()];
            } else {
                newNode = new uglifyJs.AST_Call({
                    expression: new uglifyJs.AST_SymbolRef({
                        name: 'GETSTATICURL'
                    }),
                    args: [this.to.toAst()]
                });
            }
        }
        if (newNode) {
            uglifyAst.replaceDescendantNode(this.parentNode, this.node, newNode);
            this.node = newNode;
        }
        this.from.markDirty();
        return this;
    },

    attach: function (asset, position, adjacentRelation) {
        throw new Error("Not implemented");
    },

    detach: function () {
        throw new Error("Not implemented");
    }
});

module.exports = JavaScriptGetStaticUrl;
<commit_msg>Lint JavaScriptGetStaticUrl relation<commit_after>var util = require('util'),
    JavaScript = require('../assets/JavaScript'),
    uglifyJs = JavaScript.uglifyJs,
    uglifyAst = JavaScript.uglifyAst,
    extendWithGettersAndSetters = require('../util/extendWithGettersAndSetters'),
    Relation = require('./Relation');

function JavaScriptGetStaticUrl(config) {
    Relation.call(this, config);
}

util.inherits(JavaScriptGetStaticUrl, Relation);

extendWithGettersAndSetters(JavaScriptGetStaticUrl.prototype, {
    inline: function () {
        Relation.prototype.inline.call(this);
        var newNode;
        if (this.omitFunctionCall) {
            newNode = this.to.toAst();
        } else {
            if (this.node instanceof uglifyJs.AST_Call) {
                this.node.args = [this.to.toAst()];
            } else {
                newNode = new uglifyJs.AST_Call({
                    expression: new uglifyJs.AST_SymbolRef({
                        name: 'GETSTATICURL'
                    }),
                    args: [this.to.toAst()]
                });
            }
        }
        if (newNode) {
            uglifyAst.replaceDescendantNode(this.parentNode, this.node, newNode);
            this.node = newNode;
        }
        this.from.markDirty();
        return this;
    },

    attach: function () {
        throw new Error('Not implemented');
    },

    detach: function () {
        throw new Error('Not implemented');
    }
});

module.exports = JavaScriptGetStaticUrl;
<|endoftext|>


<commit_before>'use strict'
const parseStatic = require('../../../static')
const props = parseStatic.property
const elems = parseStatic.element
const fragment = require('./fragment')

exports.static = function renderElementStatic (target) {
  // make a cloneNode shim...
  var node
  if (target.isStatic === true && target._cachedNode) {
    node = target._cachedNode.cloneNode(true)
    if (target._cachedNode._index) {
      node._index = target._cachedNode._index
    }
    if (target._cachedNode._last) {
      node._last = target._cachedNode._last
    }
  } else {
    if (target._cachedNode) {
      node = target._cachedNode.cloneNode(false)
      if (target._cachedNode._propsStaticParsed) {
        node._propsStaticParsed = true
      }
    } else {
      const nodeType = target.tag
      if (nodeType === 'fragment') {
        console.error('not handeling static fragments yet')
      } else {
        node = document.createElement(nodeType)
        props(target, node)
        target._cachedNode = node
      }
    }
    elems(target, node)
  }
  return node
}

exports.state = function renderElement (target, type, stamp, subs, tree, id, pnode) {
  var node
  // @todo: this copies unwanted styles / props -- need to add an extra clonenode for this
  if (target._cachedNode) {
    node = target._cachedNode.cloneNode(false)
    tree._[id] = node
    if (target._cachedNode._last) {
      node._last = target._cachedNode._last
    }
    if (target._cachedNode._index) {
      node._index = target._cachedNode._index
    }
  } else {
    const nodeType = target.tag
    if (nodeType === 'fragment') {
      return fragment(target, pnode, id, tree)
    } else {
      node = document.createElement(nodeType)
      const staticProps = target.keys('staticProps')
      if (staticProps) {
        target._cachedNode = node
        props(target, node)
        if (hasStateProperties(target)) {
          node = target._cachedNode.cloneNode(false)
        }
      }
    }
    tree._[id] = node
  }
  elems(target, node)
  return node
}

function hasStateProperties (target) {
  const keys = target.keys()
  const len = keys.length
  for (let i = 0; i < len; i++) {
    let check = target[keys[i]]
    if (!check.isElement && !check.isStatic) {
      return true
    }
  }
}
<commit_msg>added fix for static clones<commit_after>'use strict'
const parseStatic = require('../../../static')
const props = parseStatic.property
const elems = parseStatic.element
const fragment = require('./fragment')

exports.static = function renderElementStatic (target) {
  // make a cloneNode shim...
  var node
  if (target.isStatic === true && target._cachedNode && target.hasOwnProperty('_cachedNode')) {
    node = target._cachedNode.cloneNode(true)
    if (target._cachedNode._index) {
      node._index = target._cachedNode._index
    }
    if (target._cachedNode._last) {
      node._last = target._cachedNode._last
    }
  } else {
    if (target._cachedNode && target.hasOwnProperty('_cachedNode')) {
      node = target._cachedNode.cloneNode(false)
      if (target._cachedNode._propsStaticParsed) {
        node._propsStaticParsed = true
      }
    } else {
      const nodeType = target.tag
      if (nodeType === 'fragment') {
        console.error('not handeling static fragments yet')
      } else {
        node = document.createElement(nodeType)
        props(target, node)
        target._cachedNode = node
      }
    }
    elems(target, node)
  }
  return node
}

exports.state = function renderElement (target, type, stamp, subs, tree, id, pnode) {
  var node
  // @todo: this copies unwanted styles / props -- need to add an extra clonenode for this
  if (target._cachedNode) {
    node = target._cachedNode.cloneNode(false)
    tree._[id] = node
    if (target._cachedNode._last) {
      node._last = target._cachedNode._last
    }
    if (target._cachedNode._index) {
      node._index = target._cachedNode._index
    }
  } else {
    const nodeType = target.tag
    if (nodeType === 'fragment') {
      return fragment(target, pnode, id, tree)
    } else {
      node = document.createElement(nodeType)
      const staticProps = target.keys('staticProps')
      if (staticProps) {
        target._cachedNode = node
        props(target, node)
        if (hasStateProperties(target)) {
          node = target._cachedNode.cloneNode(false)
        }
      }
    }
    tree._[id] = node
  }
  elems(target, node)
  return node
}

function hasStateProperties (target) {
  const keys = target.keys()
  const len = keys.length
  for (let i = 0; i < len; i++) {
    let check = target[keys[i]]
    if (!check.isElement && !check.isStatic) {
      return true
    }
  }
}
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../../util/utils');
var sio = require('socket.io');

var Acceptor = function(opts, cb){
  EventEmitter.call(this);
  this.cacheMsg = opts.cacheMsg;
  this.interval = opts.interval;  // flush interval in ms
  this._interval = null;          // interval object
  this.sockets = {};
  this.msgQueues = {};
  this.cb = cb;
};
util.inherits(Acceptor, EventEmitter);

var pro = Acceptor.prototype;

pro.listen = function(port) {
  //check status
  if(!!this.inited) {
    utils.invokeCallback(self.cb, new Error('already inited.'));
    return;
  }
  this.inited = true;

  var self = this;

  this.server = sio.listen(port);

  this.server.set('log level', 0);

  this.server.server.on('error', function(err) {
    self.emit('error', err);
  });

  this.server.sockets.on('connection', function(socket) {
    self.sockets[socket.id] = socket;

    socket.on('message', function(pkg) {
      try {
        if(pkg instanceof Array) {
          processMsgs(socket, self, pkg);
        } else {
          processMsg(socket, self, pkg);
        }
      } catch(e) {
        // socke.io would broken if uncaugth the exception
      }
    });

    socket.on('disconnect', function(reason) {
      delete self.sockets[socket.id];
      delete self.msgQueues[socket.id];
    });
  });

  if(this.cacheMsg) {
    this._interval = setInterval(function() {
      flush(self);
    }, this.interval);
  }
};

pro.close = function() {
  if(!!this.closed) {
    return;
  }
  this.closed = true;
  if(this._interval) {
    clearInterval(this._interval);
    this._interval = null;
  }
  try {
    this.server.server.close();
  } catch(err){
  }
  this.emit('closed');
};

var cloneError = function(origin) {
  // copy the stack infos for Error instance json result is empty
  var res = {
    msg: origin.msg,
    stack: origin.stack
  };
  return res;
};

var processMsg = function(socket, acceptor, pkg) {
  acceptor.cb.call(null, pkg.msg, function() {
    var args = Array.prototype.slice.call(arguments, 0);
    for(var i=0, l=args.length; i<l; i++) {
      if(args[i] instanceof Error) {
        args[i] = cloneError(args[i]);
      }
    }
    var resp = {id: pkg.id, resp: Array.prototype.slice.call(args, 0)};
    if(acceptor.cacheMsg) {
      enqueue(socket, acceptor, resp);
    } else {
      socket.emit('message', resp);
    }
  });
};

var processMsgs = function(socket, acceptor, pkgs) {
  for(var i=0, l=pkgs.length; i<l; i++) {
    processMsg(socket, acceptor, pkgs[i]);
  }
};

var enqueue = function(socket, acceptor, msg) {
  var queue = acceptor.msgQueues[socket.id];
  if(!queue) {
    queue = acceptor.msgQueues[socket.id] = [];
  }
  queue.push(msg);
};

var flush = function(acceptor) {
  var sockets = acceptor.sockets, queues = acceptor.msgQueues, queue, socket;
  for(var socketId in queues) {
    socket = sockets[socketId];
    if(!socket) {
      // clear pending messages if the socket not exist any more
      delete queues[socketId];
      continue;
    }
    queue = queues[socketId];
    if(!queue.length) {
      continue;
    }
    socket.emit('message', queue);
    queues[socketId] = [];
  }
};

/**
 * create acceptor
 *
 * @param opts init params
 * @param cb(msg, cb) callback function that would be invoked when new message arrives
 */
module.exports.create = function(opts, cb) {
  return new Acceptor(opts || {}, cb);
};
<commit_msg>fix bug: use "this" instead of "self"<commit_after>var EventEmitter = require('events').EventEmitter;
var util = require('util');
var utils = require('../../util/utils');
var sio = require('socket.io');

var Acceptor = function(opts, cb){
  EventEmitter.call(this);
  this.cacheMsg = opts.cacheMsg;
  this.interval = opts.interval;  // flush interval in ms
  this._interval = null;          // interval object
  this.sockets = {};
  this.msgQueues = {};
  this.cb = cb;
};
util.inherits(Acceptor, EventEmitter);

var pro = Acceptor.prototype;

pro.listen = function(port) {
  //check status
  if(!!this.inited) {
    utils.invokeCallback(this.cb, new Error('already inited.'));
    return;
  }
  this.inited = true;

  var self = this;

  this.server = sio.listen(port);

  this.server.set('log level', 0);

  this.server.server.on('error', function(err) {
    self.emit('error', err);
  });

  this.server.sockets.on('connection', function(socket) {
    self.sockets[socket.id] = socket;

    socket.on('message', function(pkg) {
      try {
        if(pkg instanceof Array) {
          processMsgs(socket, self, pkg);
        } else {
          processMsg(socket, self, pkg);
        }
      } catch(e) {
        // socke.io would broken if uncaugth the exception
      }
    });

    socket.on('disconnect', function(reason) {
      delete self.sockets[socket.id];
      delete self.msgQueues[socket.id];
    });
  });

  if(this.cacheMsg) {
    this._interval = setInterval(function() {
      flush(self);
    }, this.interval);
  }
};

pro.close = function() {
  if(!!this.closed) {
    return;
  }
  this.closed = true;
  if(this._interval) {
    clearInterval(this._interval);
    this._interval = null;
  }
  try {
    this.server.server.close();
  } catch(err){
  }
  this.emit('closed');
};

var cloneError = function(origin) {
  // copy the stack infos for Error instance json result is empty
  var res = {
    msg: origin.msg,
    stack: origin.stack
  };
  return res;
};

var processMsg = function(socket, acceptor, pkg) {
  acceptor.cb.call(null, pkg.msg, function() {
    var args = Array.prototype.slice.call(arguments, 0);
    for(var i=0, l=args.length; i<l; i++) {
      if(args[i] instanceof Error) {
        args[i] = cloneError(args[i]);
      }
    }
    var resp = {id: pkg.id, resp: Array.prototype.slice.call(args, 0)};
    if(acceptor.cacheMsg) {
      enqueue(socket, acceptor, resp);
    } else {
      socket.emit('message', resp);
    }
  });
};

var processMsgs = function(socket, acceptor, pkgs) {
  for(var i=0, l=pkgs.length; i<l; i++) {
    processMsg(socket, acceptor, pkgs[i]);
  }
};

var enqueue = function(socket, acceptor, msg) {
  var queue = acceptor.msgQueues[socket.id];
  if(!queue) {
    queue = acceptor.msgQueues[socket.id] = [];
  }
  queue.push(msg);
};

var flush = function(acceptor) {
  var sockets = acceptor.sockets, queues = acceptor.msgQueues, queue, socket;
  for(var socketId in queues) {
    socket = sockets[socketId];
    if(!socket) {
      // clear pending messages if the socket not exist any more
      delete queues[socketId];
      continue;
    }
    queue = queues[socketId];
    if(!queue.length) {
      continue;
    }
    socket.emit('message', queue);
    queues[socketId] = [];
  }
};

/**
 * create acceptor
 *
 * @param opts init params
 * @param cb(msg, cb) callback function that would be invoked when new message arrives
 */
module.exports.create = function(opts, cb) {
  return new Acceptor(opts || {}, cb);
};
<|endoftext|>