<commit_before>/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import {shadyDataForNode} from './shady-data.js';

export const settings = window['ShadyDOM'] || {};

settings.hasNativeShadowDOM = Boolean(Element.prototype.attachShadow && Node.prototype.getRootNode);

const desc = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild');

settings.hasDescriptors = Boolean(desc && desc.configurable && desc.get);
settings.inUse = settings['force'] || !settings.hasNativeShadowDOM;
settings.noPatch = settings['noPatch'] || false;
settings.preferPerformance = settings['preferPerformance'];

// Default to using native accessors (instead of treewalker) only for
// IE/Edge where they are faster.
const IS_IE = navigator.userAgent.match('Trident');
settings.IS_IE = IS_IE;

const IS_EDGE = navigator.userAgent.match('Edge');

if (settings.useNativeAccessors === undefined) {
  settings.useNativeAccessors = settings.hasDescriptors && (IS_IE || IS_EDGE);
}

export const isTrackingLogicalChildNodes = (node) => {
  const nodeData = shadyDataForNode(node);
  return (nodeData && nodeData.firstChild !== undefined);
}

export const isShadyRoot = (obj) => {
  return Boolean(obj._localName === 'ShadyRoot');
}

export const ownerShadyRootForNode = (node) => {
  let root = node[SHADY_PREFIX + 'getRootNode']();
  if (isShadyRoot(root)) {
    return root;
  }
}

export const hasShadowRootWithSlot = (node) => {
  const nodeData = shadyDataForNode(node);
  let root = nodeData && nodeData.root;
  return (root && root._hasInsertionPoint());
}

let p = Element.prototype;
let matches = p.matches || p.matchesSelector ||
  p.mozMatchesSelector || p.msMatchesSelector ||
  p.oMatchesSelector || p.webkitMatchesSelector;

export const matchesSelector = (element, selector) => {
  return matches.call(element, selector);
}

export const mixin = (target, source) => {
  for (var i in source) {
    target[i] = source[i];
  }
  return target;
}

// NOTE, prefer MutationObserver over Promise for microtask timing
// for consistency x-platform.
let twiddle = document.createTextNode('');
let content = 0;
let queue = [];
new MutationObserver(() => {
  while (queue.length) {
    // catch errors in user code...
    try {
      queue.shift()();
    } catch(e) {
      // enqueue another record and throw
      twiddle.textContent = content++;
      throw(e);
    }
  }
}).observe(twiddle, {characterData: true});

// use MutationObserver to get microtask async timing.
export const microtask = (callback) => {
  queue.push(callback);
  twiddle.textContent = content++;
}

export const hasDocumentContains = Boolean(document.contains);

export const contains = (container, node) => {
  while (node) {
    if (node == container) {
      return true;
    }
    node = node[SHADY_PREFIX + 'parentNode'];
  }
  return false;
}

const getNodeHTMLCollectionName = (node) =>
    node.getAttribute('id') || node.getAttribute('name');

const isValidHTMLCollectionName = (name) => name !== 'length' && isNaN(name);

export const createPolyfilledHTMLCollection = (nodes) => {
  // Note: loop in reverse so that the first named item matches the named property
  for (let l = nodes.length - 1; l >= 0; l--) {
    const node = nodes[l];
    const name = getNodeHTMLCollectionName(node);

    if (name && isValidHTMLCollectionName(name)) {
      nodes[name] = node;
    }
  }
  nodes.item = function(index) {
    return nodes[index];
  }
  nodes.namedItem = function(name) {
    if (isValidHTMLCollectionName(name) && nodes[name]) {
      return nodes[name];
    }

    for (const node of nodes) {
      const nodeName = getNodeHTMLCollectionName(node);

      if (nodeName == name) {
        return node;
      }
    }

    return null;
  };
  return nodes;
}

export const NATIVE_PREFIX = '__shady_native_';
export const SHADY_PREFIX = '__shady_';

// patch a group of accessors on an object only if it exists or if the `force`
// argument is true.
/**
 * @param {!Object} obj
 * @param {!Object} descriptors
 * @param {boolean=} force
 */
export const patchProperties = (proto, descriptors, prefix = '') => {
  for (let p in descriptors) {
    const newDescriptor = descriptors[p];
    newDescriptor.configurable = true;
    const name = prefix + p;
    // NOTE: we prefer writing directly because some browsers
    // have descriptors that are writable but not configurable (e.g.
    // `appendChild` on older browsers)
    if (newDescriptor.value) {
      proto[name] = newDescriptor.value;
    } else {
      // NOTE: this can throw if 'force' is used so catch the error.
      try {
        Object.defineProperty(proto, name, newDescriptor);
      } catch(e) {
        // this error is harmless so we just trap it.
      }
    }
  }
}

export const NativeHTMLElement =
    (window['customElements'] && window['customElements']['nativeHTMLElement']) ||
    HTMLElement;

// note, this is not a perfect polyfill since it doesn't include symbols
export const getOwnPropertyDescriptors = (obj) => {
  const descriptors = {};
  Object.getOwnPropertyNames(obj).forEach((name) => {
    descriptors[name] = Object.getOwnPropertyDescriptor(obj, name);
  });
  return descriptors;
};
<commit_msg>remove cruft<commit_after>/**
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
import {shadyDataForNode} from './shady-data.js';

export const settings = window['ShadyDOM'] || {};

settings.hasNativeShadowDOM = Boolean(Element.prototype.attachShadow && Node.prototype.getRootNode);

const desc = Object.getOwnPropertyDescriptor(Node.prototype, 'firstChild');

settings.hasDescriptors = Boolean(desc && desc.configurable && desc.get);
settings.inUse = settings['force'] || !settings.hasNativeShadowDOM;
settings.noPatch = settings['noPatch'] || false;
settings.preferPerformance = settings['preferPerformance'];

export const isTrackingLogicalChildNodes = (node) => {
  const nodeData = shadyDataForNode(node);
  return (nodeData && nodeData.firstChild !== undefined);
}

export const isShadyRoot = (obj) => {
  return Boolean(obj._localName === 'ShadyRoot');
}

export const ownerShadyRootForNode = (node) => {
  let root = node[SHADY_PREFIX + 'getRootNode']();
  if (isShadyRoot(root)) {
    return root;
  }
}

export const hasShadowRootWithSlot = (node) => {
  const nodeData = shadyDataForNode(node);
  let root = nodeData && nodeData.root;
  return (root && root._hasInsertionPoint());
}

let p = Element.prototype;
let matches = p.matches || p.matchesSelector ||
  p.mozMatchesSelector || p.msMatchesSelector ||
  p.oMatchesSelector || p.webkitMatchesSelector;

export const matchesSelector = (element, selector) => {
  return matches.call(element, selector);
}

export const mixin = (target, source) => {
  for (var i in source) {
    target[i] = source[i];
  }
  return target;
}

// NOTE, prefer MutationObserver over Promise for microtask timing
// for consistency x-platform.
let twiddle = document.createTextNode('');
let content = 0;
let queue = [];
new MutationObserver(() => {
  while (queue.length) {
    // catch errors in user code...
    try {
      queue.shift()();
    } catch(e) {
      // enqueue another record and throw
      twiddle.textContent = content++;
      throw(e);
    }
  }
}).observe(twiddle, {characterData: true});

// use MutationObserver to get microtask async timing.
export const microtask = (callback) => {
  queue.push(callback);
  twiddle.textContent = content++;
}

export const hasDocumentContains = Boolean(document.contains);

export const contains = (container, node) => {
  while (node) {
    if (node == container) {
      return true;
    }
    node = node[SHADY_PREFIX + 'parentNode'];
  }
  return false;
}

const getNodeHTMLCollectionName = (node) =>
    node.getAttribute('id') || node.getAttribute('name');

const isValidHTMLCollectionName = (name) => name !== 'length' && isNaN(name);

export const createPolyfilledHTMLCollection = (nodes) => {
  // Note: loop in reverse so that the first named item matches the named property
  for (let l = nodes.length - 1; l >= 0; l--) {
    const node = nodes[l];
    const name = getNodeHTMLCollectionName(node);

    if (name && isValidHTMLCollectionName(name)) {
      nodes[name] = node;
    }
  }
  nodes.item = function(index) {
    return nodes[index];
  }
  nodes.namedItem = function(name) {
    if (isValidHTMLCollectionName(name) && nodes[name]) {
      return nodes[name];
    }

    for (const node of nodes) {
      const nodeName = getNodeHTMLCollectionName(node);

      if (nodeName == name) {
        return node;
      }
    }

    return null;
  };
  return nodes;
}

export const NATIVE_PREFIX = '__shady_native_';
export const SHADY_PREFIX = '__shady_';

// patch a group of accessors on an object only if it exists or if the `force`
// argument is true.
/**
 * @param {!Object} obj
 * @param {!Object} descriptors
 * @param {boolean=} force
 */
export const patchProperties = (proto, descriptors, prefix = '') => {
  for (let p in descriptors) {
    const newDescriptor = descriptors[p];
    newDescriptor.configurable = true;
    const name = prefix + p;
    // NOTE: we prefer writing directly because some browsers
    // have descriptors that are writable but not configurable (e.g.
    // `appendChild` on older browsers)
    if (newDescriptor.value) {
      proto[name] = newDescriptor.value;
    } else {
      // NOTE: this can throw if 'force' is used so catch the error.
      try {
        Object.defineProperty(proto, name, newDescriptor);
      } catch(e) {
        // this error is harmless so we just trap it.
      }
    }
  }
}

export const NativeHTMLElement =
    (window['customElements'] && window['customElements']['nativeHTMLElement']) ||
    HTMLElement;

// note, this is not a perfect polyfill since it doesn't include symbols
export const getOwnPropertyDescriptors = (obj) => {
  const descriptors = {};
  Object.getOwnPropertyNames(obj).forEach((name) => {
    descriptors[name] = Object.getOwnPropertyDescriptor(obj, name);
  });
  return descriptors;
};
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};
<commit_msg>window.location er in<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);

        var targetUrl = "http://www.following-and-fishing.eu/app/";
        alert('ik ben er');
        window.location.replace = targetUrl;

    }
};
<|endoftext|>


<commit_before>'use babel';

/**
 * Tries to get a property from nested objects, but stops if
 * any property on the path isn't an object.
 *
 * You can use this for example if you want to get `foo.bar.baz`
 * but are not sure if foo.bar` allways exists.
 * In that case you could use `getDeepPropSave(foo, 'bar', 'baz')`.
 *
 * @param   {*}        obj
 * @param   {String[]} path
 * @returns *
 */
export function getDeepPropSave(obj, ...path) {
    let lastEL = obj;
    path.forEach(key => {
        if (typeof lastEL !== 'object') {
            return undefined;
        }
        lastEL = lastEL[key];
    });
    return lastEL;
}

export const attrRegExp = (() => {
    let cache = {};

    return function attrRegExp(name) {
        if (cache[name]) {
            return cache[name];
        } else {
            const regExp = new RegExp(`${name}="([^"]*)"`);
            cache[name] = regExp;
            return regExp;
        }
    };
})();

/**
 * Finds all attributes in a XML tag like text
 *
 * @param   {string}   text
 * @param   {string[]} attributesNames
 * @returns {Object} an object which that maps the attribute names to there values
 */
export function extractAttributes(text) {
    const attributes = {};
    const attrMatch = text.match(/[a-zA-Z0-9_\-]+="[^"]*"/g);
    if (attrMatch) {
        attrMatch.forEach(attrStr => {
            const [, name, value] = attrStr.match(/([a-zA-Z0-9_\-]+)="([^"]*)"/);
            attributes[name] = value;
        });
    }
    return attributes;
}
<commit_msg>Fix type in JSDoc<commit_after>'use babel';

/**
 * Tries to get a property from nested objects, but stops if
 * any property on the path isn't an object.
 *
 * You can use this for example if you want to get `foo.bar.baz`
 * but are not sure if foo.bar` allways exists.
 * In that case you could use `getDeepPropSave(foo, 'bar', 'baz')`.
 *
 * @param   {*}        obj
 * @param   {string[]} path
 * @returns *
 */
export function getDeepPropSave(obj, ...path) {
    let lastEL = obj;
    path.forEach(key => {
        if (typeof lastEL !== 'object') {
            return undefined;
        }
        lastEL = lastEL[key];
    });
    return lastEL;
}

export const attrRegExp = (() => {
    let cache = {};

    return function attrRegExp(name) {
        if (cache[name]) {
            return cache[name];
        } else {
            const regExp = new RegExp(`${name}="([^"]*)"`);
            cache[name] = regExp;
            return regExp;
        }
    };
})();

/**
 * Finds all attributes in a XML tag like text
 *
 * @param   {string}   text
 * @param   {string[]} attributesNames
 * @returns {Object} an object which that maps the attribute names to there values
 */
export function extractAttributes(text) {
    const attributes = {};
    const attrMatch = text.match(/[a-zA-Z0-9_\-]+="[^"]*"/g);
    if (attrMatch) {
        attrMatch.forEach(attrStr => {
            const [, name, value] = attrStr.match(/([a-zA-Z0-9_\-]+)="([^"]*)"/);
            attributes[name] = value;
        });
    }
    return attributes;
}
<|endoftext|>


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

/**
 * @fileoverview Externs for Jasmine.
 *
 * TODO: Remaining Spy properties and anything else missing.
 *
 * @see http://pivotal.github.com/jasmine/
 * @externs
 */

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

/**
 * @param {string} name
 * @return {!jasmine.Spy} spy
 */
jasmine.createSpy = function(name) {};

/**
 * @param {string} baseName
 * @param {Array} methodNames
 */
jasmine.createSpyObj = function(baseName, methodNames) {};

/** @constructor */
jasmine.TimeProvider = function() {};

/**
 * @param {Function} cb
 * @param {number} time
 * @return {number}
 */
jasmine.TimeProvider.prototype.setTimeout = function(cb, time) {};

/**
 * @param {Function} cb
 * @param {number} time
 * @return {number}
 */
jasmine.TimeProvider.prototype.setInterval = function(cb, time) {};

/**
 * @param {number} id
 */
jasmine.TimeProvider.prototype.clearTimeout = function(id) {};

/**
 * @param {number} id
 */
jasmine.TimeProvider.prototype.clearInterval = function(id) {};

/**
 * @type {number}
 */
jasmine.TimeProvider.prototype.nowMillis;

/** @constructor */
jasmine.Clock = function() {};

/** @type {!jasmine.TimeProvider} */
jasmine.Clock.real;

/** @type {!jasmine.TimeProvider} */
jasmine.Clock.installed;

/** @return {void} */
jasmine.Clock.useMock = function() {};

/** @param {number} ms */
jasmine.Clock.tick = function(ms) {};

/** @type {number} */
jasmine.Clock.prototype.nowMillis;

/** @constructor */
jasmine.Matchers = function() {};

/** @type {jasmine.Matchers} */
jasmine.Matchers.prototype.not;

/** @type {*} */
jasmine.Matchers.prototype.actual;

/** @param {*} value */
jasmine.Matchers.prototype.toBe = function(value) {};

/** @return {void} */
jasmine.Matchers.prototype.toBeDefined = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeFalsy = function() {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeGreaterThan = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeLessThan = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeCloseTo = function(value, precision) {};

/** @return {void} */
jasmine.Matchers.prototype.toBeNull = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeTruthy = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeUndefined = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeNaN = function() {};

/** @param {*} value */
jasmine.Matchers.prototype.toContain = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toEqual = function(value) {};

/** @return {void} */
jasmine.Matchers.prototype.toHaveBeenCalled = function() {};

/** @param {...*} var_args */
jasmine.Matchers.prototype.toHaveBeenCalledWith = function(var_args) {};

/** @param {(string|RegExp)} pattern */
jasmine.Matchers.prototype.toMatch = function(pattern) {};

/** @param {Error=} opt_expected */
jasmine.Matchers.prototype.toThrow = function(opt_expected) {};

/**
 * @param {!Object} clazz
 * @return {!jasmine.Matchers}
 */
jasmine.any = function(clazz) {};

/**
 * @param {!Object} sample
 * @return {!jasmine.Matchers}
 */
jasmine.objectContaining = function(sample) {};

/** @constructor */
jasmine.Spec = function() {};

/** @type {undefined|function(): string} */
jasmine.Spec.prototype.message;

/**
 * @param {function(this:jasmine.Spec)} after
 */
jasmine.Spec.prototype.after = function(after) {};

/** @param {Error|string} e */
jasmine.Spec.prototype.fail = function(e) {};

/**
 * @param {function()=} opt_onComplete
 */
jasmine.Spec.prototype.finish = function(opt_onComplete) {};

/**
 * @param {Object} matchers
 */
jasmine.Spec.prototype.addMatchers = function(matchers) {};

/**
 * @constructor
 * @extends {Function}
 */
jasmine.Spy = function() {};

/**
 * @param {!Function} fn
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andCallFake = function(fn) {};

/** @return {!jasmine.Spy} */
jasmine.Spy.prototype.andCallThrough = function() {};

/**
 * @param {*} value
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andReturn = function(value) {};

/**
 * @param {!Error} exception
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andThrow = function(exception) {};

/**
 * @return {void}
 */
jasmine.Spy.prototype.reset = function() {};

/** @type {number} */
jasmine.Spy.prototype.callCount;

/** @type {!Array.<!Object>} */
jasmine.Spy.prototype.calls;

/** @type {*} */
jasmine.Spy.prototype.mostRecentCall;

/** @type {!Array} */
jasmine.Spy.prototype.mostRecentCall.args;

/** @constructor */
jasmine.Suite = function() {};

/**
 * @param {function()=} opt_onComplete
 */
jasmine.Suite.prototype.finish = function(opt_onComplete) {};

/**
 * @param {function(this:jasmine.Spec)} beforeEachFunction
 */
jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) {};

/**
 * @param {function(this:jasmine.Spec)} afterEachFunction
 */
jasmine.Suite.prototype.afterEach = function(afterEachFunction) {};

/** @constructor */
jasmine.JsApiReporter = function() {};

/** @type {!Array.<string>} */
jasmine.JsApiReporter.prototype.messages;

/** @type {boolean} */
jasmine.JsApiReporter.prototype.finished;

/** @return {!Array.<{id:string,name:string,type:string,children:!Array}>} id */
jasmine.JsApiReporter.prototype.suites = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isInitialized = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isFinished = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isSuccess = function() {};

/** @return {string} */
jasmine.JsApiReporter.prototype.getReport = function() {};

/** @return {number} */
jasmine.JsApiReporter.prototype.getRunTime = function() {};

/** @param {Object} runner */
jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) {};

/** @return {Object} runner */
jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {};

/**
 * @param {string} id
 * @return {{messages:Array,result:string}}
 */
jasmine.JsApiReporter.prototype.resultsForSpec = function(id) {};

/** @constructor */
jasmine.Env = function() {};

/** @type {jasmine.Spec} */
jasmine.Env.prototype.currentSpec;

/** @return {void} */
jasmine.Env.prototype.execute = function() {};

/** @param {jasmine.JsApiReporter} reporter */
jasmine.Env.prototype.addReporter = function(reporter) {};

/** @param {function(this:jasmine.Spec)} handler */
jasmine.Env.prototype.afterEach = function(handler) {};

/** @param {function(this:jasmine.Spec)} handler */
jasmine.Env.prototype.beforeEach = function(handler) {};

/**
 * @return {!jasmine.Env}
 */
jasmine.getEnv = function() {};

/** @param {function(this:jasmine.Spec)} handler */
function afterEach(handler) {}

/** @param {function(this:jasmine.Spec)} handler */
function beforeEach(handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Suite)} handler
 */
function describe(description, handler) {}

/**
 * @param {*} expectedValue
 * @return {jasmine.Matchers} matcher
 */
function expect(expectedValue) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(Function|Array.<(string,Function)>)} var_args
 */
function inject(var_args) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function it(description, handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function iit(description, handler) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(string|Function|Array.<(string,Function)>)} var_args
 * @suppress {checkTypes}
 */
function module(var_args) {}

/** @param {function()} handler */
function runs(handler) {}

/**
 * @param {Object} spiedOnObject
 * @param {string} methodName
 * @return {jasmine.Spy} spy
 */
function spyOn(spiedOnObject, methodName) {}

/** @param {number} timeout */
function waits(timeout) {}

/**
 * @param {function(): boolean} handler
 * @param {string=} opt_message
 * @param {number=} opt_timeout
 */
function waitsFor(handler, opt_message, opt_timeout) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function(this:jasmine.Suite)} handler
 */
function xdescribe(description, handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function xit(description, handler) {}
<commit_msg>Predefs update<commit_after>/*
 * Copyright 2013 The Closure Compiler Authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Externs for Jasmine.
 *
 * TODO: Remaining Spy properties and anything else missing.
 *
 * @see http://pivotal.github.com/jasmine/
 * @externs
 */

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

/**
 * @param {string} name
 * @return {!jasmine.Spy} spy
 */
jasmine.createSpy = function(name) {};

/**
 * @param {string} baseName
 * @param {Array} methodNames
 */
jasmine.createSpyObj = function(baseName, methodNames) {};

/** @constructor */
jasmine.TimeProvider = function() {};

/**
 * @param {Function} cb
 * @param {number} time
 * @return {number}
 */
jasmine.TimeProvider.prototype.setTimeout = function(cb, time) {};

/**
 * @param {Function} cb
 * @param {number} time
 * @return {number}
 */
jasmine.TimeProvider.prototype.setInterval = function(cb, time) {};

/**
 * @param {number} id
 */
jasmine.TimeProvider.prototype.clearTimeout = function(id) {};

/**
 * @param {number} id
 */
jasmine.TimeProvider.prototype.clearInterval = function(id) {};

/**
 * @type {number}
 */
jasmine.TimeProvider.prototype.nowMillis;

/** @constructor */
jasmine.Clock = function() {};

/** @type {!jasmine.TimeProvider} */
jasmine.Clock.real;

/** @type {!jasmine.TimeProvider} */
jasmine.Clock.installed;

/** @return {void} */
jasmine.Clock.useMock = function() {};

/** @param {number} ms */
jasmine.Clock.tick = function(ms) {};

/** @type {number} */
jasmine.Clock.prototype.nowMillis;

/** @constructor */
jasmine.Matchers = function() {};

/** @type {jasmine.Matchers} */
jasmine.Matchers.prototype.not;

/** @type {*} */
jasmine.Matchers.prototype.actual;

/** @param {*} value */
jasmine.Matchers.prototype.toBe = function(value) {};

/** @return {void} */
jasmine.Matchers.prototype.toBeDefined = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeFalsy = function() {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeGreaterThan = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeLessThan = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toBeCloseTo = function(value, precision) {};

/** @return {void} */
jasmine.Matchers.prototype.toBeNull = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeTruthy = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeUndefined = function() {};

/** @return {void} */
jasmine.Matchers.prototype.toBeNaN = function() {};

/** @param {*} value */
jasmine.Matchers.prototype.toContain = function(value) {};

/** @param {*} value */
jasmine.Matchers.prototype.toEqual = function(value) {};

/** @return {void} */
jasmine.Matchers.prototype.toHaveBeenCalled = function() {};

/** @param {...*} var_args */
jasmine.Matchers.prototype.toHaveBeenCalledWith = function(var_args) {};

/** @param {(string|RegExp)} pattern */
jasmine.Matchers.prototype.toMatch = function(pattern) {};

/** @param {Error=} opt_expected */
jasmine.Matchers.prototype.toThrow = function(opt_expected) {};

/**
 * @param {Object} value
 * @return {string}
 */
jasmine.pp = function(value) {};

/**
 * @param {!Object} clazz
 * @return {!jasmine.Matchers}
 */
jasmine.any = function(clazz) {};

/**
 * @param {!Object} sample
 * @return {!jasmine.Matchers}
 */
jasmine.objectContaining = function(sample) {};

/** @constructor */
jasmine.Spec = function() {};

/** @type {undefined|function(): string} */
jasmine.Spec.prototype.message;

/**
 * @param {function(this:jasmine.Spec)} after
 */
jasmine.Spec.prototype.after = function(after) {};

/** @param {Error|string} e */
jasmine.Spec.prototype.fail = function(e) {};

/**
 * @param {function()=} opt_onComplete
 */
jasmine.Spec.prototype.finish = function(opt_onComplete) {};

/**
 * @param {Object} matchers
 */
jasmine.Spec.prototype.addMatchers = function(matchers) {};

/**
 * @constructor
 * @extends {Function}
 */
jasmine.Spy = function() {};

/**
 * @param {!Function} fn
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andCallFake = function(fn) {};

/** @return {!jasmine.Spy} */
jasmine.Spy.prototype.andCallThrough = function() {};

/**
 * @param {*} value
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andReturn = function(value) {};

/**
 * @param {!Error} exception
 * @return {!jasmine.Spy}
 */
jasmine.Spy.prototype.andThrow = function(exception) {};

/**
 * @return {void}
 */
jasmine.Spy.prototype.reset = function() {};

/** @type {number} */
jasmine.Spy.prototype.callCount;

/** @type {!Array.<!Object>} */
jasmine.Spy.prototype.calls;

/** @type {*} */
jasmine.Spy.prototype.mostRecentCall;

/** @type {!Array} */
jasmine.Spy.prototype.mostRecentCall.args;

/** @constructor */
jasmine.Suite = function() {};

/**
 * @param {function()=} opt_onComplete
 */
jasmine.Suite.prototype.finish = function(opt_onComplete) {};

/**
 * @param {function(this:jasmine.Spec)} beforeEachFunction
 */
jasmine.Suite.prototype.beforeEach = function(beforeEachFunction) {};

/**
 * @param {function(this:jasmine.Spec)} afterEachFunction
 */
jasmine.Suite.prototype.afterEach = function(afterEachFunction) {};

/** @constructor */
jasmine.JsApiReporter = function() {};

/** @type {!Array.<string>} */
jasmine.JsApiReporter.prototype.messages;

/** @type {boolean} */
jasmine.JsApiReporter.prototype.finished;

/** @return {!Array.<{id:string,name:string,type:string,children:!Array}>} id */
jasmine.JsApiReporter.prototype.suites = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isInitialized = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isFinished = function() {};

/** @return {boolean} */
jasmine.JsApiReporter.prototype.isSuccess = function() {};

/** @return {string} */
jasmine.JsApiReporter.prototype.getReport = function() {};

/** @return {number} */
jasmine.JsApiReporter.prototype.getRunTime = function() {};

/** @param {Object} runner */
jasmine.JsApiReporter.prototype.reportRunnerStarting = function(runner) {};

/** @return {Object} runner */
jasmine.JsApiReporter.prototype.reportRunnerResults = function(runner) {};

/**
 * @param {string} id
 * @return {{messages:Array,result:string}}
 */
jasmine.JsApiReporter.prototype.resultsForSpec = function(id) {};

/** @constructor */
jasmine.Env = function() {};

/** @type {jasmine.Spec} */
jasmine.Env.prototype.currentSpec;

/** @return {void} */
jasmine.Env.prototype.execute = function() {};

/** @param {jasmine.JsApiReporter} reporter */
jasmine.Env.prototype.addReporter = function(reporter) {};

/** @param {function(this:jasmine.Spec)} handler */
jasmine.Env.prototype.afterEach = function(handler) {};

/** @param {function(this:jasmine.Spec)} handler */
jasmine.Env.prototype.beforeEach = function(handler) {};

/**
 * @return {!jasmine.Env}
 */
jasmine.getEnv = function() {};

/** @param {function(this:jasmine.Spec)} handler */
function afterEach(handler) {}

/** @param {function(this:jasmine.Spec)} handler */
function beforeEach(handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Suite)} handler
 */
function describe(description, handler) {}

/**
 * @param {*} expectedValue
 * @return {jasmine.Matchers} matcher
 */
function expect(expectedValue) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(Function|Array.<(string,Function)>)} var_args
 */
function inject(var_args) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function it(description, handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function iit(description, handler) {}

/**
 * Provided by angular-mocks.js.
 * @param {...(string|Function|Array.<(string,Function)>)} var_args
 * @suppress {checkTypes}
 */
function module(var_args) {}

/** @param {function()} handler */
function runs(handler) {}

/**
 * @param {Object} spiedOnObject
 * @param {string} methodName
 * @return {jasmine.Spy} spy
 */
function spyOn(spiedOnObject, methodName) {}

/** @param {number} timeout */
function waits(timeout) {}

/**
 * @param {function(): boolean} handler
 * @param {string=} opt_message
 * @param {number=} opt_timeout
 */
function waitsFor(handler, opt_message, opt_timeout) {}

/**
 * @nosideeffects
 * @param {string} description
 * @param {function(this:jasmine.Suite)} handler
 */
function xdescribe(description, handler) {}

/**
 * @param {string} description
 * @param {function(this:jasmine.Spec)} handler
 */
function xit(description, handler) {}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    initialize: function() {
        this.bind();
    },
    bind: function() {
        document.addEventListener('deviceready', this.deviceready, false);
    },
    deviceready: function() {
        // This is an event handler function, which means the scope is the event.
        // So, we must explicitly called `app.report()` instead of `this.report()`.
        app.report('deviceready');
    },
    report: function(id) {
        // Report the event in the console
        console.log("Report: " + id);

        // Toggle the state from "pending" to "complete" for the reported ID.
        // Accomplished by adding .hide to the pending element and removing
        // .hide from the complete element.
        document.querySelector('#' + id + ' .pending').className += ' hide';
        var completeElem = document.querySelector('#' + id + ' .complete');
        completeElem.className = completeElem.className.split('hide').join('');
        //testing out lawnchair.js
        $(function(e) {
            var beers = Lawnchair({name:'beers'},function(e){
                console.log('storage open');
            });
            // uncomment to clear the database
            //beers.nuke();
            beers.all(function(arrBeers){
                for(var i = 0; i<arrBeers.length;i++)
                {
                    console.log(arrBeers.length);
                    var listdiv = document.createElement('li');
                        listdiv.setAttribute('id','listdiv');
                        listdiv.innerHTML = arrBeers[i].value.name;
                    $('#beer_list').append(listdiv);
                }
                $('#beer_list').listview("refresh");
            });
            function reload_list(){
                beers.all(function(arrBeers){
                    $('#beer_list').empty();
                    for(var i = 0; i<arrBeers.length;i++)
                    {
                        console.log(arrBeers.length);
                        var listdiv = document.createElement('li');
                            listdiv.setAttribute('id','listdiv');
                            listdiv.innerHTML = JSON.stringify(arrBeers[i].value);
                        $('#beer_list').append(listdiv);
                    }
                    $('#beer_list').listview("refresh");
                });
            }
            $('#reload_list').click(function(e){
                reload_list();
            });

            $('#count').click(function(e){
                beers.all(function(arrBeers){
                    $('#status').innerHTML(arrBeers.length+" items in the database");
                });
            });
            $('#save').click(function(e){
                var nm = $("#entry_name").val();
                var desc = $("#entry_description").val();
                var cur_key = "";
                if(nm != "" && desc != ""){
                    beers.all(function(arrBeers){
                        cur_key = arrBeers.length.toString();
                    });
                    var obj1 = {"name":nm,"description":desc};
                    beers.save({key:cur_key,value:obj1});
                }
            });
            $('#retrieve').click(function(e){
                var cur_key = "0";
                beers.all(function(arrBeers){
                    cur_key = arrBeers.length.toString();
                });
                beers.get(cur_key,function(obj){
                    var resul = JSON.stringify(obj);
                    console.log(resul);
                    alert(resul);
                });
            });
            function initTimestamp(){
                //sets the time stamp to a year before now
                var d = new Date();
                d.setFullYear(d.getFullYear() - 1);
                obj = {};
                //validate that this would actually work
                obj["time"] = Math.round(d.valueOf() / 1000).toString();
                obj["cur_state"] = "FINISHED";
                beers.save({key:"timestamp", value:obj});
            }
            function checkLatest(){
                // the object im using will be:
                // "timestamp":{"time":"INT_TIME_AS_STRING", "cur_state":"STARTED/DOWNLOADING/FINISHED"}
                var last_update_time = "0";
                beers.get("timestamp",function(thisobj){
                    console.log(JSON.stringify(thisobj));
                    var obj = {};
                        obj = thisobj.value;
                        obj["cur_state"] = "STARTED";
                    last_update_time = obj["time"]
                    //check for null somehow
                    //initTimestamp() if not there
                    //done with the null case
                    beers.save({key:thisobj.key,value:obj});
                });
                var url = latest_articles_path(last_update_time);
                get_latest_from_url(url, function(jsondata){
                    //should be a json array atm
                    $.each(jsondata, function(index, data) {
                        var article = data;
                        add_article_to_db(data);
                    });
                });
            }
            function add_article_to_db(article_as_json){
                beers.save({key:article_as_json["_id"],value:article_as_json});
            }
            function latest_articles_path(timestamp_as_int){
                return "http://www.extempengine.com/articles/latest?int_time="+timestamp_as_int
            }
            function get_latest_from_url(url, callback_function){
                //wrap with callback due to same origin BS
                url = wrap_with_bs(url);
                jQuery.getJSON(url, function(data){
                    var retval = JSON.stringify(data));
                    console.log("via getJSON > "+retval);
                    callback_function(data);
                });
            }
            function wrap_with_bs(url){
                if (url.indexOf("?") == -1) {
                    url = url + "&callback=?";
                } else {
                    url = url + "?callback=?";
                }
                return url;
            }
            var article_url = "http://extempengine.com/papers/505e656464c4b70002000002/articles/505e6569a0f8a40002000038.js";
            function servercallback(data){
                console.log("callback "+JSON.stringify(data));
                beers.save({key:data._id,value:data});
            }
            $('#get_from_server').click(function(e) {
                console.log("starting article search");
                jQuery.getJSON(article_url+"?callback=?", function(data){
                    console.log("callback "+JSON.stringify(data));
                    add_article_to_db(data);
                });
                console.log("jquery getjson was just initiated search");
            });
            $('#initTimestamp').click(function(e) {
                initTimestamp();
            });
            $('#modify').click(function(e) {
                beers.get("1",function(thisobj){
                    console.log(thisobj);
                    var obj = {};
                        obj = thisobj.value;
                        obj.name = "Modified Value";
                    beers.save({key:thisobj.key,value:obj});
                });
            });
        }); // end lawnchair shit
    }
};
<commit_msg>minimum<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    initialize: function() {
        this.bind();
    },
    bind: function() {
        document.addEventListener('deviceready', this.deviceready, false);
    },
    deviceready: function() {
        // This is an event handler function, which means the scope is the event.
        // So, we must explicitly called `app.report()` instead of `this.report()`.
        app.report('deviceready');
    },
    report: function(id) {
        // Report the event in the console
        console.log("Report: " + id);

        // Toggle the state from "pending" to "complete" for the reported ID.
        // Accomplished by adding .hide to the pending element and removing
        // .hide from the complete element.
        document.querySelector('#' + id + ' .pending').className += ' hide';
        var completeElem = document.querySelector('#' + id + ' .complete');
        completeElem.className = completeElem.className.split('hide').join('');
        //testing out lawnchair.js
        $(function(e) {
            var beers = Lawnchair({name:'beers'},function(e){
                console.log('storage open');
            });
            // uncomment to clear the database
            //beers.nuke();
            beers.all(function(arrBeers){
                for(var i = 0; i<arrBeers.length;i++)
                {
                    console.log(arrBeers.length);
                    var listdiv = document.createElement('li');
                        listdiv.setAttribute('id','listdiv');
                        listdiv.innerHTML = arrBeers[i].value.name;
                    $('#beer_list').append(listdiv);
                }
                $('#beer_list').listview("refresh");
            });
            function reload_list(){
                beers.all(function(arrBeers){
                    $('#beer_list').empty();
                    for(var i = 0; i<arrBeers.length;i++)
                    {
                        console.log(arrBeers.length);
                        var listdiv = document.createElement('li');
                            listdiv.setAttribute('id','listdiv');
                            listdiv.innerHTML = JSON.stringify(arrBeers[i].value);
                        $('#beer_list').append(listdiv);
                    }
                    $('#beer_list').listview("refresh");
                });
            }
            $('#reload_list').click(function(e){
                reload_list();
            });

            $('#count').click(function(e){
                beers.all(function(arrBeers){
                    $('#status').innerHTML(arrBeers.length+" items in the database");
                });
            });
            $('#save').click(function(e){
                var nm = $("#entry_name").val();
                var desc = $("#entry_description").val();
                var cur_key = "";
                if(nm != "" && desc != ""){
                    beers.all(function(arrBeers){
                        cur_key = arrBeers.length.toString();
                    });
                    var obj1 = {"name":nm,"description":desc};
                    beers.save({key:cur_key,value:obj1});
                }
            });
            $('#retrieve').click(function(e){
                var cur_key = "0";
                beers.all(function(arrBeers){
                    cur_key = arrBeers.length.toString();
                });
                beers.get(cur_key,function(obj){
                    var resul = JSON.stringify(obj);
                    console.log(resul);
                    alert(resul);
                });
            });
            // function initTimestamp(){
            //     //sets the time stamp to a year before now
            //     var d = new Date();
            //     d.setFullYear(d.getFullYear() - 1);
            //     obj = {};
            //     //validate that this would actually work
            //     obj["time"] = Math.round(d.valueOf() / 1000).toString();
            //     obj["cur_state"] = "FINISHED";
            //     beers.save({key:"timestamp", value:obj});
            // }
            // function checkLatest(){
            //     // the object im using will be:
            //     // "timestamp":{"time":"INT_TIME_AS_STRING", "cur_state":"STARTED/DOWNLOADING/FINISHED"}
            //     var last_update_time = "0";
            //     beers.get("timestamp",function(thisobj){
            //         console.log(JSON.stringify(thisobj));
            //         var obj = {};
            //             obj = thisobj.value;
            //             obj["cur_state"] = "STARTED";
            //         last_update_time = obj["time"]
            //         //check for null somehow
            //         //initTimestamp() if not there
            //         //done with the null case
            //         beers.save({key:thisobj.key,value:obj});
            //     });
            //     var url = latest_articles_path(last_update_time);
            //     get_latest_from_url(url, function(jsondata){
            //         //should be a json array atm
            //         $.each(jsondata, function(index, data) {
            //             var article = data;
            //             add_article_to_db(data);
            //         });
            //     });
            // }
            // function latest_articles_path(timestamp_as_int){
            //     return "http://www.extempengine.com/articles/latest?int_time="+timestamp_as_int
            // }
            // function get_latest_from_url(url, callback_function){
            //     //wrap with callback due to same origin BS
            //     url = wrap_with_bs(url);
            //     jQuery.getJSON(url, function(data){
            //         var retval = JSON.stringify(data));
            //         console.log("via getJSON > "+retval);
            //         callback_function(data);
            //     });
            // }
            // function wrap_with_bs(url){
            //     if (url.indexOf("?") == -1) {
            //         url = url + "&callback=?";
            //     } else {
            //         url = url + "?callback=?";
            //     }
            //     return url;
            // }
            function add_article_to_db(article_as_json){
                beers.save({key:article_as_json["_id"],value:article_as_json});
            }
            var article_url = "http://extempengine.com/papers/505e656464c4b70002000002/articles/505e6569a0f8a40002000038.js";
            $('#get_from_server').click(function(e) {
                console.log("starting article search");
                jQuery.getJSON(article_url+"?callback=?", function(data){
                    console.log("callback "+JSON.stringify(data));
                    add_article_to_db(data);
                });
                console.log("jquery getjson was just initiated search");
            });
            // $('#initTimestamp').click(function(e) {
            //     initTimestamp();
            // });
            $('#modify').click(function(e) {
                beers.get("1",function(thisobj){
                    console.log(thisobj);
                    var obj = {};
                        obj = thisobj.value;
                        obj.name = "Modified Value";
                    beers.save({key:thisobj.key,value:obj});
                });
            });
        }); // end lawnchair shit
    }
};
<|endoftext|>


<commit_before>export const isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
}

export const isObject = function (arg) {
    return Object.prototype.toString.call(arg) === '[object Object]';
}

export const evalWithContextData =  function (key, object, db) {
    // In this (way, we can pass object and use inside the eval string
    return eval(key)
}

export const fieldArrayCalcLength = function (config, fixedArrayLength) {
    let length
    if (config.fixedLength) {
        length = config.length - fixedArrayLength
    } else {
        length = Math.floor((Math.random() * config.length) + 1)
    }
    return length
}

export const iamLastParent = function(obj) {
    let last = false
    if (isObject(obj)) {
        let ks = Object.keys(obj)

        for (let i = 0; i < ks.length; i++) {
            let k = ks[i]
            last = iamLastChild(obj, k)
            if (!last){
                break
            }
        }
    } else {
        last = true
    }
    return last
}

export const iamLastChild = function (parent, k) {
    if (isArray(parent[k])) {
        let last = false

        if (parent[k].length === 0){
            return true
        }

        for (let i = 0; i < parent[k].length; i++) {
            let el = parent[k][i]
            last = !isObject(el)
            if (last){
                break
            }
        }
        return last
    } else {
        return !isObject(parent[k])
    }
}

export const isConditional = function (str) {
    let arr = str.split(',')
    return arr.length > 1
}

export const cleanVirtuals = function (paths, object, options) {

    //clean specific paths
    let objectCleaner = function *(path, obj, options) {
        let lvls = path.split(options.symbol)
        let dest = obj

        if (!lvls || lvls.length === 0) { return }
        if (!obj) { return }

        for (var i = 0; i< lvls.length; i++) {
            let field = lvls[i]
            if (i === lvls.length - 1 && dest[field]) {
                if (Object.getOwnPropertyNames(dest[field]).length < 1) {
                    delete dest[field]
                    break
                }
            } else {
                dest = dest[field]
            }
        }
        lvls.pop()

        if (lvls.length > 0){
            yield *objectCleaner(lvls.join(options.symbol), obj, options)
        } else {
            return
        }
    }

    let forEachPath = function *(path, object, options) {
        let lvls = path.split(options.symbol)
        let dest = object

        for (var i = 0; i < lvls.length; i++) {
            let field = lvls[i]
            if (i === lvls.length - 1) {
                // delete specific path
                delete dest[field]
                //clean specific path
                yield *objectCleaner(path, object, options)
            } else {
                dest = dest[field]
            }
        }
    }

    let forPaths = function *(paths, object, options) {
        for (var i = 0; i < paths.length; i++) {
            let path = paths[i]
            yield *forEachPath(path, object, options)
        }
    }

    let it = forPaths(paths, object, options);
    for (const res of it) { }

    return object
}

export const calculateKey = function(k){
    if (!isConditional(k)){
        return k
    } else {
        let key = k.split(',')
        return key[0]
    }
}

export const conditionalField = function (acc, k, result, object){
    if (!isConditional(k)){
        acc[k] = result
    } else {
        let key = k.split(',')
        if (evalWithContextData(key[0], object)){
            acc[key[1]] = result
        }
    }
    return
}
<commit_msg>Update utils.js<commit_after>export const isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
}

export const isObject = function (arg) {
    return Object.prototype.toString.call(arg) === '[object Object]';
}

export const evalWithContextData =  function (key, object, db) {
    // In this (way, we can pass object and use inside the eval string
    return eval(key)
}

export const fieldArrayCalcLength = function (config, fixedArrayLength, schema) {
    let length
    if (typeof config.length === 'function') {
        length = config.length.call(schema);
    } else if (config.fixedLength) {
        length = config.length - fixedArrayLength
    } else {
        length = Math.floor((Math.random() * config.length) + 1)
    }
    return length
}

export const iamLastParent = function(obj) {
    let last = false
    if (isObject(obj)) {
        let ks = Object.keys(obj)

        for (let i = 0; i < ks.length; i++) {
            let k = ks[i]
            last = iamLastChild(obj, k)
            if (!last){
                break
            }
        }
    } else {
        last = true
    }
    return last
}

export const iamLastChild = function (parent, k) {
    if (isArray(parent[k])) {
        let last = false

        if (parent[k].length === 0){
            return true
        }

        for (let i = 0; i < parent[k].length; i++) {
            let el = parent[k][i]
            last = !isObject(el)
            if (last){
                break
            }
        }
        return last
    } else {
        return !isObject(parent[k])
    }
}

export const isConditional = function (str) {
    let arr = str.split(',')
    return arr.length > 1
}

export const cleanVirtuals = function (paths, object, options) {

    //clean specific paths
    let objectCleaner = function *(path, obj, options) {
        let lvls = path.split(options.symbol)
        let dest = obj

        if (!lvls || lvls.length === 0) { return }
        if (!obj) { return }

        for (var i = 0; i< lvls.length; i++) {
            let field = lvls[i]
            if (i === lvls.length - 1 && dest[field]) {
                if (Object.getOwnPropertyNames(dest[field]).length < 1) {
                    delete dest[field]
                    break
                }
            } else {
                dest = dest[field]
            }
        }
        lvls.pop()

        if (lvls.length > 0){
            yield *objectCleaner(lvls.join(options.symbol), obj, options)
        } else {
            return
        }
    }

    let forEachPath = function *(path, object, options) {
        let lvls = path.split(options.symbol)
        let dest = object

        for (var i = 0; i < lvls.length; i++) {
            let field = lvls[i]
            if (i === lvls.length - 1) {
                // delete specific path
                delete dest[field]
                //clean specific path
                yield *objectCleaner(path, object, options)
            } else {
                dest = dest[field]
            }
        }
    }

    let forPaths = function *(paths, object, options) {
        for (var i = 0; i < paths.length; i++) {
            let path = paths[i]
            yield *forEachPath(path, object, options)
        }
    }

    let it = forPaths(paths, object, options);
    for (const res of it) { }

    return object
}

export const calculateKey = function(k){
    if (!isConditional(k)){
        return k
    } else {
        let key = k.split(',')
        return key[0]
    }
}

export const conditionalField = function (acc, k, result, object){
    if (!isConditional(k)){
        acc[k] = result
    } else {
        let key = k.split(',')
        if (evalWithContextData(key[0], object)){
            acc[key[1]] = result
        }
    }
    return
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var app = {
	// Application Constructor
	initialize : function() {
			this.bindEvents();

	},
	// Bind Event Listeners
	//
	// Bind any events that are required on startup. Common events are:
	// 'load', 'deviceready', 'offline', and 'online'.
	bindEvents : function() {
		document.addEventListener('deviceready', this.onDeviceReady, false);
	},
	// deviceready Event Handler
	//
	// The scope of 'this' is the event. In order to call the 'receivedEvent'
	// function, we must explicity call 'app.receivedEvent(...);'
	onDeviceReady : function() {
		app.receivedEvent('deviceready');

		//var ref = window.open('http://blrbr.co', '_blank', 'toolbar=no,location=no');
		//var ref = window.open('http://blrbrdev.azurewebsites.net', '_blank', 'toolbar=no,location=no');
	        //var ref = window.open('http://blrbrspadev.azurewebsites.net', '_blank', 'toolbar=no,location=no');

		// //ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
		// ref.addEventListener('loadstart', function(event) {
			// //alert('stop: ' + event.url);
//
			// if (event.url.indexOf('Blrb/Create') != -1) {
				// ref.close();
//
				// window.location = "create.html?" + event.url.split('?')[1];
			// }
//
		// });
		// ref.addEventListener('loaderror', function(event) {
			// alert('error: ' + event.message);
		// });
		// ref.addEventListener('exit', function(event) {
		// });

		// StatusBar.hide();
		// navigator.splashscreen.hide();
	},
	// Update DOM on a Received Event
	receivedEvent : function(id) {
		var parentElement = document.getElementById(id);
		var listeningElement = parentElement.querySelector('.listening');
		var receivedElement = parentElement.querySelector('.received');

		listeningElement.setAttribute('style', 'display:none;');
		receivedElement.setAttribute('style', 'display:block;');

		console.log('Received Event: ' + id);
	}
};

var login=function() {
					var ref = window.open('http://blrbrdev.azurewebsites.net/blrb/me', '_blank', 'toolbar=no,location=no');
	  							ref.addEventListener('loadstart', function(event) {
	  				alert("hey");

			if (event.url.indexOf('Blrb/Create') != -1) {
				ref.close();
			window.location = "create.html?" + event.url.split('?')[1];
			}

var segs=event.url.split("/");
	if (segs[3] == "") {
				ref.close();
				window.location = "index.html";
			}

		});
		ref.addEventListener('loaderror', function(event) {
			alert('error: ' + event.message);
		});
		ref.addEventListener('exit', function(event) {
		});

	  				};

var channel=function() {
					var ref = window.open('http://blrbrdev.azurewebsites.net/firstblrbever', '_blank', 'toolbar=no,location=no');
	  					ref.addEventListener('loadstart', function(event) {
			alert('stop: ' + event.url);
alert(event.url.split("/").length);

alert(segs[3]);

			if (event.url.indexOf('Blrb/Create') != -1) {
				ref.close();

				window.location = "create.html?" + event.url.split('?')[1];
			}

var segs=event.url.split("/");
	if (segs[3] == "") {
				ref.close();

				window.location = "index.html";
			}

		});
		ref.addEventListener('loaderror', function(event) {
			alert('error: ' + event.message);
		});
		ref.addEventListener('exit', function(event) {
		});

	  				};
<commit_msg>fghgf<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var app = {
	// Application Constructor
	initialize : function() {
			this.bindEvents();

	},
	// Bind Event Listeners
	//
	// Bind any events that are required on startup. Common events are:
	// 'load', 'deviceready', 'offline', and 'online'.
	bindEvents : function() {
		document.addEventListener('deviceready', this.onDeviceReady, false);
	},
	// deviceready Event Handler
	//
	// The scope of 'this' is the event. In order to call the 'receivedEvent'
	// function, we must explicity call 'app.receivedEvent(...);'
	onDeviceReady : function() {
		app.receivedEvent('deviceready');

		//var ref = window.open('http://blrbr.co', '_blank', 'toolbar=no,location=no');
		//var ref = window.open('http://blrbrdev.azurewebsites.net', '_blank', 'toolbar=no,location=no');
	        //var ref = window.open('http://blrbrspadev.azurewebsites.net', '_blank', 'toolbar=no,location=no');

		// //ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
		// ref.addEventListener('loadstart', function(event) {
			// //alert('stop: ' + event.url);
//
			// if (event.url.indexOf('Blrb/Create') != -1) {
				// ref.close();
//
				// window.location = "create.html?" + event.url.split('?')[1];
			// }
//
		// });
		// ref.addEventListener('loaderror', function(event) {
			// alert('error: ' + event.message);
		// });
		// ref.addEventListener('exit', function(event) {
		// });

		// StatusBar.hide();
		// navigator.splashscreen.hide();
	},
	// Update DOM on a Received Event
	receivedEvent : function(id) {
		var parentElement = document.getElementById(id);
		var listeningElement = parentElement.querySelector('.listening');
		var receivedElement = parentElement.querySelector('.received');

		listeningElement.setAttribute('style', 'display:none;');
		receivedElement.setAttribute('style', 'display:block;');

		console.log('Received Event: ' + id);
	}
};

var login=function() {
					var ref = window.open('http://blrbrdev.azurewebsites.net/blrb/me', '_blank', 'toolbar=no,location=no');
	  							ref.addEventListener('loadstart', function(event) {
	  				alert("hey");
	  					alert(localStorage.route);
		if(localStorage.route=="blrb/me")
		{
			var route=localStorage.route;
			localStorage.route=null;
			login();

		}
			if (event.url.indexOf('Blrb/Create') != -1) {
				ref.close();
			window.location = "create.html?" + event.url.split('?')[1];
			}

var segs=event.url.split("/");
	if (segs[3] == "") {
				ref.close();
				window.location = "index.html";
			}

		});
		ref.addEventListener('loaderror', function(event) {
			alert('error: ' + event.message);
		});
		ref.addEventListener('exit', function(event) {
		});

	  				};

var channel=function() {
					var ref = window.open('http://blrbrdev.azurewebsites.net/firstblrbever', '_blank', 'toolbar=no,location=no');
	  					ref.addEventListener('loadstart', function(event) {
			alert('stop: ' + event.url);
alert(event.url.split("/").length);

alert(segs[3]);

			if (event.url.indexOf('Blrb/Create') != -1) {
				ref.close();

				window.location = "create.html?" + event.url.split('?')[1];
			}

var segs=event.url.split("/");
	if (segs[3] == "") {
				ref.close();

				window.location = "index.html";
			}

		});
		ref.addEventListener('loaderror', function(event) {
			alert('error: ' + event.message);
		});
		ref.addEventListener('exit', function(event) {
		});

	  				};
<|endoftext|>


<commit_before>define([
    'require',
    './core/store',
    './logging'
], function(require) {
    // XXX: not nice
    var mapal = require('./core/store'),
        getLogger = require('./logging').getLogger;

    var extractParameters = function(params, sources) {
        var tmp,
            j,
            paramObjs = {};
        if (params.length > 0) {
            var p = params.slice(1).split('!');
            for (var i = p.length-1; i >= 0; i--) {
                // support injection parameters in other patterns
                if (p[i][0] == '#') {
                    var param, effect;

                    if (p[i].indexOf('.') > 0) {
                        tmp = p[i].split('.');
                        param = tmp[0];
                        effect = tmp[1];
                    } else {
                        param = p[i];
                        effect = undefined;
                    }
                    var source = [sources.pop()];
                    // XXX: $a and url were also not defined in the old context
                    // We need automated tests
                    mapal.injection.load($a, url, param.slice(1), source);
                } else if (p[i].indexOf('=') > 0) {
                    j = p[i].indexOf('=');
                    paramObjs[p[i].slice(0, j)] = p[i].slice(j+1);
                } else {
                    paramObjs[p[i]] = true;
                }
            }
        }
        return paramObjs;
    };

    // input = "a!b=1 2!c=x"
    // --> options = {a: true, b: '1 2', c: 'x'}
    var parseOptions = function(input) {
        var params = input.split("!"),
            options = {}, name, value, index;

        for (var i=0; i<params.length; i++) {
            index = params[i].indexOf("=");
            if (index === -1) {
                name = params[i];
                value = true;
            } else {
                name = params[i].slice(0, index);
                value = params[i].slice(index+1);
            }
            options[name] = value;
        }
        return options;
    };

    var log_init = function(name, method) {
        var log_wrapper = function($el) {
            var log = getLogger(name);
            log.debug('Initialising:', $el);
            var ret = method.apply(this, arguments);
            if (ret === false) {
                log.debug('skipped', $el);
            } else {
                log.debug('initialised:', $el);
            }
            return ret;
        };
        return log_wrapper;
    };

    var set_initialised_class = function(method, pattern) {
        var cls = pattern.initialised_class;
        if (!cls) return method;
        var initialised_class_wrapper = function($el) {
            var ret = method.apply(this, arguments);
            if (ret !== false) $el.addClass(cls);
            return ret;
        };
        return initialised_class_wrapper;
    };

    // run a method on an element only once
    var once = function(key, method) {
        var once_wrapper = function($el) {
            var initialised = $el.data(key);
            if (initialised) return undefined;
            var ret = method.apply(this, arguments);
            if (ret !== false) $el.data(key, true);
            return ret;
        };
        return once_wrapper;
    };

    // work on elements single file
    var turnstiled = function(method) {
        var turnstile = function($el) {
            var rest = Array.prototype.slice.call(arguments, 1);
            $el.each(function() {
                var $this = $(this);
                return method.apply($this, [$this].concat(rest));
            });
        };
        return turnstile;
    };

    // return a pimpéd pattern
    // - init only once
    // - put multiple elements through a turnstile
    var pimp_pattern = function(pname, pattern) {
        var pimped = {};
        for (var mname in pattern) {
            var method = pattern[mname];
            if (mname === "init") {
                method = log_init(pname, method);
                method = set_initialised_class(method, pattern);
                method = once(pname + '-' + mname, method);
            }
            if (typeof method === "function") method = turnstiled(method);
            pimped[mname] = method;
        }
        return pimped;
    };

    var jquery_plugin = function(name, pattern) {
        var plugin = function(method) {
            if (!method || typeof method === "object") {
                pattern.init.apply(this, [this].concat(arguments));
            } else if (pattern[method]) {
                pattern[method].apply(
                    this,
                    [this].concat(Array.prototype.slice.call(arguments, 1))
                );
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.' + name);
            }
            return this;
        };
        return plugin;
    };

    // XXX: need to understand require magic to make this work here
    // require paths are local to where it is called, we would need to
    // pass the path of the module that called load_modules
    var load_modules = function(prefix, names, suffix) {
        prefix = prefix || '';
        suffix = suffix || '';
        var modules = names.reduce(function(acc, name) {
            acc[name] = require(prefix + name + suffix);
            return acc;
        }, {});
        return modules;
    };

    function _renumberAttribute(el, attr, i) {
        var $el = $(el),
            buf = $el.attr(attr);
        if (buf) {
            $el.attr(attr, buf.replace(/[0-9]+/, i));
        }
    }

    function _renumberEl() {
	_renumberAttribute(this, "for", i);
	_renumberAttribute(this, "id", i);
	_renumberAttribute(this, "name", i);
    }

    function renumber($container, selector) {
        var $entries = $container.find(selector ? selector : "fieldset,tr,dd"),
            entry, i;

        for (i=0; i<$entries.length; i++) {
            entry = $entries.get(i);
            _renumberAttribute(entry, "id", i);
            $("label, :input", entry).each(_renumberEl);
        }
    }

    function hasContent($el) {
        if ($el.is(":input")) {
            return $el.val();
        } else {
            return $el.text().replace(/\s*/g, "") || $el.find("img,object,video,audio").length;
        }
    }

    //     Underscore.js 1.3.1
    //     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
    //     Underscore is freely distributable under the MIT license.
    //     Portions of Underscore are inspired or borrowed from Prototype,
    //     Oliver Steele's Functional, and John Resig's Micro-Templating.
    //     For all details and documentation:
    //     http://documentcloud.github.com/underscore
    //
    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds.
    var debounce = function(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    var utils = {
        extractParameters: extractParameters,
        parseOptions: parseOptions,
        //load_modules: load_modules,
        // pattern pimping - own module?
        set_initialised_class: set_initialised_class,
        once: once,
        turnstiled: turnstiled,
        pimp_pattern: pimp_pattern,
        jquery_plugin: jquery_plugin,
        debounce: debounce,
	renumber: renumber,
	hasContent: hasContent
    };

    return utils;
});
<commit_msg>add XXX comment<commit_after>define([
    'require',
    './core/store',
    './logging'
], function(require) {
    // XXX: not nice
    var mapal = require('./core/store'), // XXX Should this be core/init ?
        getLogger = require('./logging').getLogger;

    var extractParameters = function(params, sources) {
        var tmp,
            j,
            paramObjs = {};
        if (params.length > 0) {
            var p = params.slice(1).split('!');
            for (var i = p.length-1; i >= 0; i--) {
                // support injection parameters in other patterns
                if (p[i][0] == '#') {
                    var param, effect;

                    if (p[i].indexOf('.') > 0) {
                        tmp = p[i].split('.');
                        param = tmp[0];
                        effect = tmp[1];
                    } else {
                        param = p[i];
                        effect = undefined;
                    }
                    var source = [sources.pop()];
                    // XXX: $a and url were also not defined in the old context
                    // We need automated tests
                    mapal.injection.load($a, url, param.slice(1), source);
                } else if (p[i].indexOf('=') > 0) {
                    j = p[i].indexOf('=');
                    paramObjs[p[i].slice(0, j)] = p[i].slice(j+1);
                } else {
                    paramObjs[p[i]] = true;
                }
            }
        }
        return paramObjs;
    };

    // input = "a!b=1 2!c=x"
    // --> options = {a: true, b: '1 2', c: 'x'}
    var parseOptions = function(input) {
        var params = input.split("!"),
            options = {}, name, value, index;

        for (var i=0; i<params.length; i++) {
            index = params[i].indexOf("=");
            if (index === -1) {
                name = params[i];
                value = true;
            } else {
                name = params[i].slice(0, index);
                value = params[i].slice(index+1);
            }
            options[name] = value;
        }
        return options;
    };

    var log_init = function(name, method) {
        var log_wrapper = function($el) {
            var log = getLogger(name);
            log.debug('Initialising:', $el);
            var ret = method.apply(this, arguments);
            if (ret === false) {
                log.debug('skipped', $el);
            } else {
                log.debug('initialised:', $el);
            }
            return ret;
        };
        return log_wrapper;
    };

    var set_initialised_class = function(method, pattern) {
        var cls = pattern.initialised_class;
        if (!cls) return method;
        var initialised_class_wrapper = function($el) {
            var ret = method.apply(this, arguments);
            if (ret !== false) $el.addClass(cls);
            return ret;
        };
        return initialised_class_wrapper;
    };

    // run a method on an element only once
    var once = function(key, method) {
        var once_wrapper = function($el) {
            var initialised = $el.data(key);
            if (initialised) return undefined;
            var ret = method.apply(this, arguments);
            if (ret !== false) $el.data(key, true);
            return ret;
        };
        return once_wrapper;
    };

    // work on elements single file
    var turnstiled = function(method) {
        var turnstile = function($el) {
            var rest = Array.prototype.slice.call(arguments, 1);
            $el.each(function() {
                var $this = $(this);
                return method.apply($this, [$this].concat(rest));
            });
        };
        return turnstile;
    };

    // return a pimpéd pattern
    // - init only once
    // - put multiple elements through a turnstile
    var pimp_pattern = function(pname, pattern) {
        var pimped = {};
        for (var mname in pattern) {
            var method = pattern[mname];
            if (mname === "init") {
                method = log_init(pname, method);
                method = set_initialised_class(method, pattern);
                method = once(pname + '-' + mname, method);
            }
            if (typeof method === "function") method = turnstiled(method);
            pimped[mname] = method;
        }
        return pimped;
    };

    var jquery_plugin = function(name, pattern) {
        var plugin = function(method) {
            if (!method || typeof method === "object") {
                pattern.init.apply(this, [this].concat(arguments));
            } else if (pattern[method]) {
                pattern[method].apply(
                    this,
                    [this].concat(Array.prototype.slice.call(arguments, 1))
                );
            } else {
                $.error('Method ' + method + ' does not exist on jQuery.' + name);
            }
            return this;
        };
        return plugin;
    };

    // XXX: need to understand require magic to make this work here
    // require paths are local to where it is called, we would need to
    // pass the path of the module that called load_modules
    var load_modules = function(prefix, names, suffix) {
        prefix = prefix || '';
        suffix = suffix || '';
        var modules = names.reduce(function(acc, name) {
            acc[name] = require(prefix + name + suffix);
            return acc;
        }, {});
        return modules;
    };

    function _renumberAttribute(el, attr, i) {
        var $el = $(el),
            buf = $el.attr(attr);
        if (buf) {
            $el.attr(attr, buf.replace(/[0-9]+/, i));
        }
    }

    function _renumberEl() {
	_renumberAttribute(this, "for", i);
	_renumberAttribute(this, "id", i);
	_renumberAttribute(this, "name", i);
    }

    function renumber($container, selector) {
        var $entries = $container.find(selector ? selector : "fieldset,tr,dd"),
            entry, i;

        for (i=0; i<$entries.length; i++) {
            entry = $entries.get(i);
            _renumberAttribute(entry, "id", i);
            $("label, :input", entry).each(_renumberEl);
        }
    }

    function hasContent($el) {
        if ($el.is(":input")) {
            return $el.val();
        } else {
            return $el.text().replace(/\s*/g, "") || $el.find("img,object,video,audio").length;
        }
    }

    //     Underscore.js 1.3.1
    //     (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
    //     Underscore is freely distributable under the MIT license.
    //     Portions of Underscore are inspired or borrowed from Prototype,
    //     Oliver Steele's Functional, and John Resig's Micro-Templating.
    //     For all details and documentation:
    //     http://documentcloud.github.com/underscore
    //
    // Returns a function, that, as long as it continues to be invoked, will not
    // be triggered. The function will be called after it stops being called for
    // N milliseconds.
    var debounce = function(func, wait) {
        var timeout;
        return function() {
            var context = this, args = arguments;
            var later = function() {
                timeout = null;
                func.apply(context, args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    };

    var utils = {
        extractParameters: extractParameters,
        parseOptions: parseOptions,
        //load_modules: load_modules,
        // pattern pimping - own module?
        set_initialised_class: set_initialised_class,
        once: once,
        turnstiled: turnstiled,
        pimp_pattern: pimp_pattern,
        jquery_plugin: jquery_plugin,
        debounce: debounce,
	renumber: renumber,
	hasContent: hasContent
    };

    return utils;
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import cx from 'classnames';

import templateHelper from '../../utils/templateHelper/templateHelper';
import noop from '../../utils/noop';
import Icon from '../Icon/Icon';
import ScreenReadable from '../ScreenReadable/ScreenReadable';
import css from './SocialLinks.css';

const emptyArr = [];

export const defaultPlatforms = [{
  name: 'facebook',
  shareUrl: templateHelper`https://www.facebook.com/sharer/sharer.php?u=${'uri'}`,
}, {
  name: 'twitter',
  shareUrl: templateHelper`https://twitter.com/intent/tweet?text=${'twitterTweet'}&url=${'uri'}&via=${'twitterVia'}`,
}, {
  name: 'pintrest',
  shareUrl: templateHelper`https://www.pinterest.com/pin/create/button/?url=${'uri'}`,
}];

const SocialLinks = (props) => {
  const {
    uri,
    twitterTweet,
    twitterVia,
    accessibilityLabel,
    platforms,
    className,
    variant,
    linkClassName,
    onClick,
  } = props;

  const encodedUri = encodeURI(uri);
  const encodedTwitterTweet = encodeURI(twitterTweet).replace('#', '%23');
  const encodedVia = encodeURI(twitterVia);

  return (

      { platforms
          .map(platform => (
            <div
              className={ css.linkItem }
              key={ `${platform.name}-${encodedUri}` }
            >
               { onClick(e, { platform, encodedUri }); } }
                target="_blank"
                rel="noopener noreferrer"
              >
                <Icon name={ platform.name } />
                <ScreenReadable>{ accessibilityLabel } { platform.name }</ScreenReadable>

          ))
      }

  );
};

SocialLinks.propTypes = {
  uri: PropTypes.string.isRequired,
  twitterTweet: PropTypes.string,
  twitterVia: PropTypes.string,
  accessibilityLabel: PropTypes.string,
  platforms: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.string,
    shareUrl: PropTypes.func,
  })),
  className: PropTypes.string,
  variant: PropTypes.oneOf(['light', 'dark']),
  linkClassName: PropTypes.string,
  onClick: PropTypes.func,
};

SocialLinks.defaultProps = {
  excludes: emptyArr,
  accessibilityLabel: 'Share on',
  platforms: defaultPlatforms,
  variant: 'light',
  onClick: noop,
};

export default SocialLinks;
<commit_msg>Prevent SocialLinks component from producing a tweet with `undefined` in it<commit_after>import React, { PropTypes } from 'react';
import cx from 'classnames';

import templateHelper from '../../utils/templateHelper/templateHelper';
import noop from '../../utils/noop';
import Icon from '../Icon/Icon';
import ScreenReadable from '../ScreenReadable/ScreenReadable';
import css from './SocialLinks.css';

const emptyArr = [];

export const defaultPlatforms = [{
  name: 'facebook',
  shareUrl: templateHelper`https://www.facebook.com/sharer/sharer.php?u=${'uri'}`,
}, {
  name: 'twitter',
  shareUrl: templateHelper`https://twitter.com/intent/tweet?text=${'twitterTweet'}&url=${'uri'}&via=${'twitterVia'}`,
}, {
  name: 'pintrest',
  shareUrl: templateHelper`https://www.pinterest.com/pin/create/button/?url=${'uri'}`,
}];

const SocialLinks = (props) => {
  const {
    uri,
    twitterTweet,
    twitterVia,
    accessibilityLabel,
    platforms,
    className,
    variant,
    linkClassName,
    onClick,
  } = props;

  const encodedUri = encodeURI(uri);
  const encodedTwitterTweet = encodeURI(twitterTweet).replace('#', '%23');
  const encodedVia = encodeURI(twitterVia);

  return (

      { platforms
          .map(platform => (
            <div
              className={ css.linkItem }
              key={ `${platform.name}-${encodedUri}` }
            >
               { onClick(e, { platform, encodedUri }); } }
                target="_blank"
                rel="noopener noreferrer"
              >
                <Icon name={ platform.name } />
                <ScreenReadable>{ accessibilityLabel } { platform.name }</ScreenReadable>

          ))
      }

  );
};

SocialLinks.propTypes = {
  uri: PropTypes.string.isRequired,
  twitterTweet: PropTypes.string,
  twitterVia: PropTypes.string,
  accessibilityLabel: PropTypes.string,
  platforms: PropTypes.arrayOf(PropTypes.shape({
    name: PropTypes.string,
    shareUrl: PropTypes.func,
  })),
  className: PropTypes.string,
  variant: PropTypes.oneOf(['light', 'dark']),
  linkClassName: PropTypes.string,
  onClick: PropTypes.func,
};

SocialLinks.defaultProps = {
  excludes: emptyArr,
  accessibilityLabel: 'Share on',
  platforms: defaultPlatforms,
  variant: 'light',
  onClick: noop,
  twitterTweet: '',
  twitterVia: '',
};

export default SocialLinks;
<|endoftext|>