<commit_before>// this test case mimics about 80 precent of the code used to build the
// config.xml file from the following file (meteor/tools/cordova/builder.js)
// and it exercies all the funcitons used from the xmlbuilder2 api
Tinytest.add("xmlbuilder - config.xml file generation", function (test) {
    const expectedResult = `<?xml version="1.0"?><widget id="com.meteor.xmlbuilder_test" version="0.0.1" android-versionCode="28" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"><name>XmlBuilderTest</name><description>This is a Meteor test case</description><author href="http://cordova.io" email="dev@cordova.apache.org">Meteor Developer</author><preference name="webviewbounce" value="false"/><preference name="DisallowOverscroll" value="true"/><universal-links><host name="localhost:3000"/></universal-links><content src="http://localhost:3000/"/><allow-intent href="tel:*"/><allow-intent href="geo:*"/><allow-intent href="mailto:*"/><allow-intent href="sms:*"/><allow-intent href="market:*"/><allow-intent href="itms:*"/><allow-intent href="itms-apps:*"/><allow-navigation href="http://localhost"/><platform name="ios"/><platform name="android"/></widget>`;

    const accessRules = {
        'tel:*': { type: 'intent' },
        'geo:*': { type: 'intent' },
        'mailto:*': { type: 'intent' },
        'sms:*': { type: 'intent' },
        'market:*': { type: 'intent' },
        'itms:*': { type: 'intent' },
        'itms-apps:*': { type: 'intent' },
        'http://localhost': { type: 'navigation' }
    };

    const metadata = {
        id: 'com.meteor.xmlbuilder_test',
        version: '0.0.1',
        author: 'Meteor Developer',
        contentUrl: `http://localhost:3000/`
    };

    const additionalConfiguration = {
        global: {
            'webviewbounce': false,
            'DisallowOverscroll': true
        },
        platform: {
            ios: {},
            android: {}
        }
    };

    const custom = [`<universal-links><host name="localhost:3000"/></universal-links>`];
    let config = XmlBuilder.create({ version: '1.0' }).ele('widget');

    // Set the root attributes
    _.each({
        id: metadata.id,
        version: metadata.version,
        'android-versionCode': '28',
        'ios-CFBundleVersion': null,
        xmlns: 'http://www.w3.org/ns/widgets',
        'xmlns:cdv': 'http://cordova.apache.org/ns/1.0'
    }, (value, key) => {
        if (value) {
            config.att(key, value);
        }
    });

    // Set the metadata
    config.ele('name').txt('XmlBuilderTest');
    config.ele('description').txt('This is a Meteor test case');
    config.ele('author', {
        href: 'http://cordova.io',
        email: 'dev@cordova.apache.org'
    }).txt(metadata.author);

    // Set the additional global configuration preferences
    _.each(additionalConfiguration.global, (value, key) => {
        config.ele('preference', {
            name: key,
            value: value.toString()
        });
    });

    // Set custom tags into widget element
    _.each(custom, elementSet => {
        const tag = config.ele(elementSet);
    });

    config.ele('content', { src: metadata.contentUrl });

    // Copy all the access rules
    _.each(accessRules, (options, pattern) => {
        const type = options.type;
        options = _.omit(options, 'type');

        if (type === 'intent') {
            config.ele('allow-intent', { href: pattern });
        } else if (type === 'navigation') {
            config.ele('allow-navigation', _.extend({ href: pattern }, options));
        } else {
            config.ele('access', _.extend({ origin: pattern }, options));
        }
    });

    const platformElement = {
        ios: config.ele('platform', { name: 'ios' }),
        android: config.ele('platform', { name: 'android' })
    }

    // Set the additional platform-specific configuration preferences
    _.each(additionalConfiguration.platform, (prefs, platform) => {
        _.each(prefs, (value, key) => {
            platformElement[platform].ele('preference', {
                name: key,
                value: value.toString()
            });
        });
    });

    const formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

Tinytest.add("xmlbuilder - create() funciton", function (test) {
    const expectedResult = '<?xml version="1.0"?><widget/>';

    let widgetNode = XmlBuilder.create({ version: '1.0' }).ele('widget');
    let formattedXmlConfig = widgetNode.end();
    test.equal(formattedXmlConfig, expectedResult);

    widgetNode = XmlBuilder.create().ele('widget');
    formattedXmlConfig = widgetNode.end();
    test.equal(formattedXmlConfig, expectedResult);

});

Tinytest.add("xmlbuilder - att() function", function (test) {
    const expectedResult = '<?xml version="1.0"?><widget key="test"/>';

    let config = XmlBuilder.create().ele('widget');
    config.att({ key: 'test' });
    let formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

Tinytest.add("xmlbuilder - ele() function", function (test) {
    let expectedResult = '<?xml version="1.0"?><widget><name>XmlBuilderTest</name></widget>';
    let config = XmlBuilder.create().ele('widget');
    config.ele('name').txt('XmlBuilderTest');

    const formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

<commit_msg>bug fix - spelling errors in the test file<commit_after>// this test case mimics about 80 precent of the code used to build the
// config.xml file from the following file (meteor/tools/cordova/builder.js)
// and it exercises all the funcitons used from the xmlbuilder2 api
Tinytest.add("xmlbuilder - config.xml file generation", function (test) {
    const expectedResult = `<?xml version="1.0"?><widget id="com.meteor.xmlbuilder_test" version="0.0.1" android-versionCode="28" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"><name>XmlBuilderTest</name><description>This is a Meteor test case</description><author href="http://cordova.io" email="dev@cordova.apache.org">Meteor Developer</author><preference name="webviewbounce" value="false"/><preference name="DisallowOverscroll" value="true"/><universal-links><host name="localhost:3000"/></universal-links><content src="http://localhost:3000/"/><allow-intent href="tel:*"/><allow-intent href="geo:*"/><allow-intent href="mailto:*"/><allow-intent href="sms:*"/><allow-intent href="market:*"/><allow-intent href="itms:*"/><allow-intent href="itms-apps:*"/><allow-navigation href="http://localhost"/><platform name="ios"/><platform name="android"/></widget>`;

    const accessRules = {
        'tel:*': { type: 'intent' },
        'geo:*': { type: 'intent' },
        'mailto:*': { type: 'intent' },
        'sms:*': { type: 'intent' },
        'market:*': { type: 'intent' },
        'itms:*': { type: 'intent' },
        'itms-apps:*': { type: 'intent' },
        'http://localhost': { type: 'navigation' }
    };

    const metadata = {
        id: 'com.meteor.xmlbuilder_test',
        version: '0.0.1',
        author: 'Meteor Developer',
        contentUrl: `http://localhost:3000/`
    };

    const additionalConfiguration = {
        global: {
            'webviewbounce': false,
            'DisallowOverscroll': true
        },
        platform: {
            ios: {},
            android: {}
        }
    };

    const custom = [`<universal-links><host name="localhost:3000"/></universal-links>`];
    let config = XmlBuilder.create({ version: '1.0' }).ele('widget');

    // Set the root attributes
    _.each({
        id: metadata.id,
        version: metadata.version,
        'android-versionCode': '28',
        'ios-CFBundleVersion': null,
        xmlns: 'http://www.w3.org/ns/widgets',
        'xmlns:cdv': 'http://cordova.apache.org/ns/1.0'
    }, (value, key) => {
        if (value) {
            config.att(key, value);
        }
    });

    // Set the metadata
    config.ele('name').txt('XmlBuilderTest');
    config.ele('description').txt('This is a Meteor test case');
    config.ele('author', {
        href: 'http://cordova.io',
        email: 'dev@cordova.apache.org'
    }).txt(metadata.author);

    // Set the additional global configuration preferences
    _.each(additionalConfiguration.global, (value, key) => {
        config.ele('preference', {
            name: key,
            value: value.toString()
        });
    });

    // Set custom tags into widget element
    _.each(custom, elementSet => {
        const tag = config.ele(elementSet);
    });

    config.ele('content', { src: metadata.contentUrl });

    // Copy all the access rules
    _.each(accessRules, (options, pattern) => {
        const type = options.type;
        options = _.omit(options, 'type');

        if (type === 'intent') {
            config.ele('allow-intent', { href: pattern });
        } else if (type === 'navigation') {
            config.ele('allow-navigation', _.extend({ href: pattern }, options));
        } else {
            config.ele('access', _.extend({ origin: pattern }, options));
        }
    });

    const platformElement = {
        ios: config.ele('platform', { name: 'ios' }),
        android: config.ele('platform', { name: 'android' })
    }

    // Set the additional platform-specific configuration preferences
    _.each(additionalConfiguration.platform, (prefs, platform) => {
        _.each(prefs, (value, key) => {
            platformElement[platform].ele('preference', {
                name: key,
                value: value.toString()
            });
        });
    });

    const formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

Tinytest.add("xmlbuilder - create() function", function (test) {
    const expectedResult = '<?xml version="1.0"?><widget/>';

    let widgetNode = XmlBuilder.create({ version: '1.0' }).ele('widget');
    let formattedXmlConfig = widgetNode.end();
    test.equal(formattedXmlConfig, expectedResult);

    widgetNode = XmlBuilder.create().ele('widget');
    formattedXmlConfig = widgetNode.end();
    test.equal(formattedXmlConfig, expectedResult);

});

Tinytest.add("xmlbuilder - att() function", function (test) {
    const expectedResult = '<?xml version="1.0"?><widget key="test"/>';

    let config = XmlBuilder.create().ele('widget');
    config.att({ key: 'test' });
    let formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

Tinytest.add("xmlbuilder - ele() function", function (test) {
    let expectedResult = '<?xml version="1.0"?><widget><name>XmlBuilderTest</name></widget>';
    let config = XmlBuilder.create().ele('widget');
    config.ele('name').txt('XmlBuilderTest');

    const formattedXmlConfig = config.end();
    test.equal(formattedXmlConfig, expectedResult);
});

<|endoftext|>


<commit_before>define(['angular', 'app'],function (angular) {
  'use strict';

  /**
   * @ngdoc service
   * @name ngSeed.services:ResourceFactory
   * @param {String} resourceName The name of the resource.
   * @description
   *
   * Generates a factory function that uses ngResource
   * to talk to a REST resource that can be directly used
   * with factory.
   *
   * Example of use with factory:
   * ```js
   * services
   *   .factory('ResourceService', ResourceFactory('resource'));
   * ```
   */
  function ResourceFactory ( resourceName ) {

    /**
     * @ngdoc function
     * @name ngSeed.services:ResourceFactory:builder
     * @description
     *
     * Generates an HTTP Resource.
     *
     * @param {$resource} $resource ngResource
     * @param {$httpOptions} $httpOptions The HTTP Options object.
     *
     * @return {resource} The actual resource for resourceName.
     */
    var builder = function ( $resource, $httpOptions ) {
      var url = httpOptions.domain+'/'+resourceName+'/:id';
      var defaults = {};
      var actions =  {
        'get':    {method:'GET', withCredentials: $httpOptions.withCredentials},
        'query':  {method:'GET', isArray:true, withCredentials: $httpOptions.withCredentials},
        'save':   {method:'POST', withCredentials: $httpOptions.withCredentials},
        'create': {method:'POST', withCredentials: $httpOptions.withCredentials},
        'update': {method:'PUT', withCredentials: $httpOptions.withCredentials},
        'remove': {method:'DELETE', withCredentials: $httpOptions.withCredentials},
        'destroy':{method:'DELETE', withCredentials: $httpOptions.withCredentials},
        'delete': {method:'DELETE', withCredentials: $httpOptions.withCredentials}
      };
      return $resource(url, defaults, actions);
    };

    return ['$resource', '$httpOptions', builder];
  };

  angular
  .module('app.services')
  .service('$resourceFactory',function () {
    return function (resourceName) {
      angular
      .module('app.resources')
      .factory(resourceName,ResourceFactory(resourceName));
    }
  });
});<commit_msg>fix(typo): adds $ to httpOptions inside the builder function.<commit_after>define(['angular', 'app'],function (angular) {
  'use strict';

  /**
   * @ngdoc service
   * @name ngSeed.services:ResourceFactory
   * @param {String} resourceName The name of the resource.
   * @description
   *
   * Generates a factory function that uses ngResource
   * to talk to a REST resource that can be directly used
   * with factory.
   *
   * Example of use with factory:
   * ```js
   * services
   *   .factory('ResourceService', ResourceFactory('resource'));
   * ```
   */
  function ResourceFactory ( resourceName ) {

    /**
     * @ngdoc function
     * @name ngSeed.services:ResourceFactory:builder
     * @description
     *
     * Generates an HTTP Resource.
     *
     * @param {$resource} $resource ngResource
     * @param {$httpOptions} $httpOptions The HTTP Options object.
     *
     * @return {resource} The actual resource for resourceName.
     */
    var builder = function ( $resource, $httpOptions ) {
      var url = $httpOptions.domain+'/'+resourceName+'/:id';
      var defaults = {};
      var actions =  {
        'get':    {method:'GET'},
        'query':  {method:'GET', isArray:true},
        'save':   {method:'PUT'},
        'create': {method:'POST'},
        'destroy':{method:'DELETE'},
      };
      return $resource(url, defaults, actions);
    };

    return ['$resource', '$httpOptions', builder];
  };

  angular
  .module('app.services')
  .service('$resourceFactory',function () {
    return function (resourceName) {
      angular
      .module('app.resources')
      .factory(resourceName,ResourceFactory(resourceName));
    }
  });
});<|endoftext|>


<commit_before>/* Copyright 2011 the Melange 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/" + melange.config.app_version + "/js/";

  // Melange CSS URL prefix
  var mcss = "/soc/content/" + melange.config.app_version + "/css/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    "/tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.counter = [
    tpjs + "jquery/jquery-counter.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.raty = [
    tpjs + "jquery/jquery.raty.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.datepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.datepicker.js"
  ];

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.button = [
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.button.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqueryui.dialog = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.dialog.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile(mcss + "v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.fmatter.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    s.cookie,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.datepicker,
    null,
    mpjs + "melange.datetimepicker.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    new $m.cssFile(mcss + "v2/gsoc/others.css"),
    null,
    s.jqueryui.dialog,
    s.jqueryui.button,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js",
    null,
    function () {
      if (window.melange_list_queue !== undefined && window.melange_list_queue instanceof Array) {
        jQuery.each(window.melange_list_queue, function (index, function_to_call) {
          function_to_call();
        });
      }
    }
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];
    // Temporary queue with CSS paths strings.
    var _cssqueue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      }
      else if (temp_val instanceof $m.cssFile) {
        if (jQuery.inArray(temp_val.css, _cssqueue) === -1) {
          _queue.push(temp_val);
          _cssqueue.push(temp_val.css);
        }
      }
      else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<commit_msg>Add JS dependencies list to the newly added JS files for action buttons.<commit_after>/* Copyright 2011 the Melange 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/" + melange.config.app_version + "/js/";

  // Melange CSS URL prefix
  var mcss = "/soc/content/" + melange.config.app_version + "/css/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "https://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    "/tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.counter = [
    tpjs + "jquery/jquery-counter.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.raty = [
    tpjs + "jquery/jquery.raty.js"
  ];

  s.cluetip = [
    tpjs + "jquery/jquery.cluetip.js"
   ];

  s.dimensions = [
    tpjs + "jquery/jquery.dimensions.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile(mcss + "jquery-ui/jquery.ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.datepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.datepicker.js"
  ];

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.button = [
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.button.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqueryui.dialog = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.dialog.js"
  ];

  s.jqueryui.checkboxes = [
    tpjs + "jquery.ui-checkboxes.js";
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile(mcss + "v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.fmatter.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    s.cookie,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.datepicker,
    null,
    mpjs + "melange.datetimepicker.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    new $m.cssFile(mcss + "v2/gsoc/others.css"),
    null,
    s.jqueryui.dialog,
    s.jqueryui.button,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js",
    null,
    function () {
      if (window.melange_list_queue !== undefined && window.melange_list_queue instanceof Array) {
        jQuery.each(window.melange_list_queue, function (index, function_to_call) {
          function_to_call();
        });
      }
    }
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];
    // Temporary queue with CSS paths strings.
    var _cssqueue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      }
      else if (temp_val instanceof $m.cssFile) {
        if (jQuery.inArray(temp_val.css, _cssqueue) === -1) {
          _queue.push(temp_val);
          _cssqueue.push(temp_val.css);
        }
      }
      else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<|endoftext|>


<commit_before>var fs = require("fs"),
	express = require("express"),
	app = express(),
	marked = require("marked"),
	mustache = require("mustache"),
	template = fs.readFileSync("./themes/basic/main.html", { "encoding": "utf-8" }),
	archives,
	drafts,
	get_config = function () {
		var config;
		try {
			config = fs.readFileSync("config.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `config.json`. Please run `setup.js`.")
		}
		return config ? JSON.parse(config) : {};
	},
	get_context = function () {
		var context;
		try {
			context = fs.readFileSync("context.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `context.json`. Please run `setup.js`.")
		}
		return context ? JSON.parse(context) : {};
	},
	tripled_variables = ["css", "content", "profile_image"],
	config = get_config(),
	context = get_context();

// By inserting a space in each triplet of braces, this prevents an error with the CSS and Mustache template.
template = template.replace(/\}\}\}/g, "}} }");

// Because Scriptogram only ever uses double-braced variables, replace these with triple-braced.
tripled_variables.forEach(function (v, i, a) {
	template = template.replace(new RegExp("\{\{(" + v + ")\}\}", "g"), "{{{$1}}}");
});

app.use("/themes", express.static('themes'));

app.use(function (req, res, next) {

	var archive_location = config.archives || "";

	fs.readdir(archive_location, function (err, files) {
		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			archives = files.filter(function (e, i, a) {
				return (e.match(/^\d{12}/));
			});
			context = get_context();
			archives.forEach(function(v, i, a) {
				var current_post = {},
					post_file = "",
					tags_file = "",
					post_title = "";

				try {
					post_file = fs.readFileSync(archive_location + v  + "/" + v + ".md", { "encoding": "utf-8" }),
					tags_file = fs.readFileSync(archive_location + v  + "/" + "tags.txt", { "encoding": "utf-8" });
				} catch (e) {
					console.log("Could not find `" + v + ".md`. May be an issue with the `archives` property in `config.json`.")
				}

				post_title = post_file.match(/^[\s\n\r\t]*\#[\s\t]*([^\n]*)\n*/) || "";
				current_post["title"] =  post_title[1] || "";
				current_post["content"] = marked(post_title[0] ? post_file.replace(post_title[0], "") : "");

				current_post["if_tags"] = true;
				current_post["tags"] = [{ "name": "test" }];

				if (context.hasOwnProperty("posts")) {
					context.posts.push(current_post);
				}

			});

			// TODO: sort out synchronicity
			next();
		}
	});
});

app.use("/draft", function (req, res, next) {
	fs.readdir(config.drafts || "", function (err, files) {
		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			drafts = files.filter(function (e, i, a) {
				return true;
			});
			next();
		}
	});
});

app.get("/", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	next();
});

app.use("/preview", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(mustache.render(template, context));
	next();
});

app.get("/draft", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	res.write(JSON.stringify(drafts, null, "\t") || " ");
	next();
});

app.use(function (req, res, next) {
	res.end();
});

app.listen(1337);<commit_msg>Fixed tagging in preview of each post.<commit_after>var fs = require("fs"),
	express = require("express"),
	app = express(),
	marked = require("marked"),
	mustache = require("mustache"),
	template = fs.readFileSync("./themes/basic/main.html", { "encoding": "utf-8" }),
	archives,
	drafts,
	get_config = function () {
		var config;
		try {
			config = fs.readFileSync("config.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `config.json`. Please run `setup.js`.")
		}
		return config ? JSON.parse(config) : {};
	},
	get_context = function () {
		var context;
		try {
			context = fs.readFileSync("context.json", { "encoding": "utf-8" });
		} catch (e) {
			console.log("ERROR", "Could not find `context.json`. Please run `setup.js`.")
		}
		return context ? JSON.parse(context) : {};
	},
	tripled_variables = ["css", "content", "profile_image"],
	config = get_config(),
	context = get_context();

// By inserting a space in each triplet of braces, this prevents an error with the CSS and Mustache template.
template = template.replace(/\}\}\}/g, "}} }");

// Because Scriptogram only ever uses double-braced variables, replace these with triple-braced.
tripled_variables.forEach(function (v, i, a) {
	template = template.replace(new RegExp("\{\{(" + v + ")\}\}", "g"), "{{{$1}}}");
});

app.use("/themes", express.static('themes'));

app.use(function (req, res, next) {

	var archive_location = config.archives || "";

	fs.readdir(archive_location, function (err, files) {
		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			archives = files.filter(function (e, i, a) {
				return (e.match(/^\d{12}/));
			});
			context = get_context();
			archives.forEach(function(v, i, a) {
				var current_post = {},
					post_file = "",
					tags_file = "",
					post_title = "";

				try {
					post_file = fs.readFileSync(archive_location + v  + "/" + v + ".md", { "encoding": "utf-8" }),
					tags_file = fs.readFileSync(archive_location + v  + "/" + "tags.txt", { "encoding": "utf-8" });
				} catch (e) {
					console.log("Could not find `" + v + ".md`. May be an issue with the `archives` property in `config.json`.")
				}

				post_title = post_file.match(/^[\s\n\r\t]*\#[\s\t]*([^\n]*)\n*/) || "";
				current_post["title"] =  post_title[1] || "";
				current_post["content"] = marked(post_title[0] ? post_file.replace(post_title[0], "") : "");

				current_post["if_tags"] = true;
				current_post["tags"] = [];
				tags_file.split(/\n/g).forEach(function (v, i, a) {
					current_post.tags.push({ "name": v });
				});

				if (context.hasOwnProperty("posts")) {
					context.posts.push(current_post);
				}

			});

			// TODO: sort out synchronicity
			next();
		}
	});
});

app.use("/draft", function (req, res, next) {
	fs.readdir(config.drafts || "", function (err, files) {
		if (err) {
			res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
		} else {
			drafts = files.filter(function (e, i, a) {
				return true;
			});
			next();
		}
	});
});

app.get("/", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	next();
});

app.use("/preview", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(mustache.render(template, context));
	next();
});

app.get("/draft", function (req, res, next) {
	res.writeHead(200, "text/html");
	res.write(JSON.stringify(archives, null, "\t"));
	res.write(JSON.stringify(drafts, null, "\t") || " ");
	next();
});

app.use(function (req, res, next) {
	res.end();
});

app.listen(1337);<|endoftext|>


<commit_before>/* Copyright 2011 the Melange 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/js/" + melange.config.app_version + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    tpjs + "tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.autocomplete = [
    new $m.cssFile("/soc/content/css/jquery-autocomplete-090304.css"),
    tpjs + "jquery/jquery-autocomplete.js"
  ];

  s.thickbox = [
    tpjs + "jquery/jquery-thickbox.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui = [
      new $m.cssFile("/soc/content/css/ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui = [
      new $m.cssFile("/soc/content/css/ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqgrid = [
    s.jqueryui,
    null,
    new $m.cssFile("/soc/content/css/v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui,
    null,
    tpjs + "jquery-ui.datetimepicker.js",
    null,
    mpjs + "datetimepicker.js",
    null,
    mpjs + "datetime-loader.js"
  ];

  s.melange.menu = [
    s.cookie,
    null,
    mpjs + "menu.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    null,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js"
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      } else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<commit_msg>Add jQuery UI autocomplete and melange autocomplete dependencies.<commit_after>/* Copyright 2011 the Melange 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.
 */
/**
 * @author Mario Ferraro
 */
(function () {
  /** @lends melange.dependency */

  if (window.melange === undefined) {
    throw new Error("Melange not loaded");
  }

  var melange = window.melange;

  /** Package that handles melange JS dependencies
    * Doesn't list jQuery, JSON, melange and melange.dependency
    * in any chain as they're dependencies of this own script,
    * and they will be then loaded anyway.
    * @name melange.dependency
    * @namespace melange.depencency
    * @borrows melange.logging.debugDecorator.log as log
    */
  melange.dependency = window.melange.dependency = function () {
    return new melange.dependency();
  };

  /** Shortcut to current package.
    * @private
    */
  var $m = melange.logging.debugDecorator(melange.dependency);

  melange.error.createErrors([
  ]);

  $m.templateWithContext = function (script_template, context) {
    this.script_template = script_template;
    this.context = context;
  };

  $m.cssFile = function (css) {
    this.css = css;
  };

  var script_dependencies_chains = {};

  var s = script_dependencies_chains;

  // Third party JS URL prefix
  var tpjs = "/js/" + melange.config.app_version + "/";

  // Melange packages URL prefix
  var mpjs = "/soc/content/js/" + melange.config.app_version + "/";

  if (melange.config.google_api_key !== undefined) {
    s.google = [
      "http://www.google.com/jsapi?key=" + melange.config.google_api_key
    ];
  }
  else {
    s.google = [
      "http://www.google.com/jsapi"
    ];
  }

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jquery = [
      tpjs + "jquery/jquery-1.5.js"
    ];
  }
  else {
    s.jquery = [
      "http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"
    ];
  }

  s.json = [
    tpjs + "json/json2.js"
  ];

  s.tinymce = [
    tpjs + "tiny_mce/tiny_mce.js"
  ];

  s.purr = [
    tpjs + "jquery/jquery-purr.js"
  ];

  s.spin = [
    tpjs + "jquery/jquery-spin-1.1.1.js"
  ];

  s.bgiframe = [
    tpjs + "jquery/jquery-bgiframe.js"
  ];

  s.ajaxQueue = [
    tpjs + "jquery/jquery-ajaxQueue.js"
  ];

  s.thickbox = [
    tpjs + "jquery/jquery-thickbox.js"
  ];

  s.progressbar = [
    tpjs + "jquery/jquery-progressbar.js"
  ];

  s.uniform = [
    tpjs + "jquery/jquery-uniform.js"
  ];

  s.jqueryui = {}

  if (melange.config.is_local !== undefined && melange.config.is_local === true) {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/ui.all.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }
  else {
    s.jqueryui.core = [
      new $m.cssFile("/soc/content/css/ui.merged.css"),
      tpjs + "jquery/jquery-ui.core.js"
    ];
  }

  s.jqueryui.position = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.position.js"
  ];

  s.jqueryui.widget = [
    s.jqueryui.core,
    null,
    tpjs + "jquery/jquery-ui.widget.js"
  ];

  s.jqueryui.autocomplete = [
    s.jqueryui.position,
    s.jqueryui.widget,
    null,
    tpjs + "jquery/jquery-ui.autocomplete.js"
  ];

  s.jqgrid = [
    s.jqueryui.core,
    null,
    new $m.cssFile("/soc/content/css/v2/gsoc/ui.jqgrid.css"),
    tpjs + "jquery/jquery-jqgrid.locale-en.js",
    null,
    tpjs + "jquery/jquery-jqgrid.base.js",
    null,
    tpjs + "jquery/jquery-jqgrid.custom.js",
    tpjs + "jquery/jquery-jqgrid.setcolumns.js"
  ];

  s.jqgridediting = [
    s.jqgrid,
    null,
    tpjs + "jquery/jquery-jqgrid.common.js",
    tpjs + "jquery/jquery-jqgrid.formedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.searchFilter.js",
    tpjs + "jquery/jquery-jqgrid.inlinedit.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqDnR.js",
    null,
    tpjs + "jquery/jquery-jqgrid.jqModal.js"
  ];

  s.cookie = [
    tpjs + "jquery/jquery-cookie.js"
  ];

  s.jlinq = [
    tpjs + "jlinq/jLinq-2.2.1.js"
  ];

  /** Melange packages **/

  s.melange = {};

  s.melange.main = [
    s.google,
    null,
    mpjs + "melange.js"
  ];

  s.melange.datetimepicker = [
    s.jqueryui.core,
    null,
    tpjs + "jquery-ui.datetimepicker.js",
    null,
    mpjs + "datetimepicker.js",
    null,
    mpjs + "datetime-loader.js"
  ];

  s.melange.menu = [
    s.cookie,
    null,
    mpjs + "menu.js"
  ];

  s.melange.duplicates = [
    s.progressbar,
    null,
    mpjs + "duplicate-slots.js"
  ];

  s.melange.form = [
  ];

  s.melange.list = [
    s.jqgrid,
    s.jlinq,
    null,
    s.jqgridediting,
    null,
    mpjs + "melange.list.js"
  ];

  s.melange.tooltip = [
    s.purr,
    null
  ];

  s.melange.autocomplete = [
    s.jqueryui.autocomplete,
    null,
    mpjs + "melange.autocomplete.js"
  ];

  s.melange.graph = [
    s.google,
    null,
    mpjs + "melange.graph.js"
  ];

  s.melange.uploadform = [
    mpjs + "upload-form.js"
  ];

  s.melange.blog = [
    s.google,
    null,
    mpjs + "melange.blog.js"
  ];

  $m.s = s;

  var unpack = function (orig_array) {
    var array_to_return = [];
    for (var i = 0, len = orig_array.length; i < len; i++) {
      var current_element = orig_array[i];
      if (typeof current_element === 'object' && current_element instanceof
          Array) {
        var unpacks = unpack(current_element);
        array_to_return = array_to_return.concat(unpacks);
      }
      else {
        array_to_return.push(current_element);
      }
    }
    return array_to_return;
  };

  $m.loadScripts = function(requested_packages) {
    var _tempqueue = unpack(requested_packages);

    /* Remove duplicates from the queue, as allowDuplicates with LAB
     * fails randomly at least in Safari and Chrome
     */
    var _queue = [];

    for (var i = 0, len = _tempqueue.length; i < len; i++) {
      var temp_val = _tempqueue[i];
      if (typeof temp_val == "string") {
        if (jQuery.inArray(temp_val, _queue) === -1) {
          _queue.push(temp_val);
        }
      } else {
        _queue.push(temp_val);
      }
    }

    for (var i=0, len=_queue.length; i<len; i++) {
      if (typeof _queue[i] == "string") { // script string source found
          $LAB = $LAB.script(_queue[i]);
      }
      else if (!_queue[i]) { // null/false found
          $LAB = $LAB.wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.templateWithContext) {
          $LAB = $LAB.script(_queue[i].script_template).wait(
            function (context_to_send) {
              return function () {
                melange.templates.setContextToLast(context_to_send);
              }
            }(_queue[i].context)
          ).wait();
      }
      else if (typeof _queue[i] == "object" && _queue[i] instanceof $m.cssFile) {
        jQuery("<link>", {
          href: _queue[i].css,
          media: "screen",
          rel: "stylesheet",
          type: "text/css"
        }).appendTo("head");
      }
      else if (typeof _queue[i] == "function") { // inline function found
          $LAB = $LAB.wait(_queue[i]);
      }
    }
  };

}());
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    main.consumes = [
        "c9", "Previewer", "fs", "dialog.error", "commands", "tabManager"
    ];
    main.provides = ["preview.markdown"];
    return main;

    // @todo possible improvements: http://benweet.github.io/stackedit/#

    function main(options, imports, register) {
        var Previewer  = imports.Previewer;
        var c9         = imports.c9;
        var fs         = imports.fs;
        var commands   = imports.commands;
        var tabManager = imports.tabManager;
        var showError  = imports["dialog.error"].show;
        var dirname    = require("path").dirname;

        /***** Initialization *****/

        var plugin = new Previewer("Ajax.org", main.consumes, {
            caption  : "Markdown",
            index    : 200,
            selector : function(path){
                return path.match(/(?:\.md|\.markdown)$/i);
            }
        });
        var emit = plugin.getEmitter();

        var HTMLURL, previewOrigin;

        /***** Methods *****/

        /***** Lifecycle *****/

        plugin.on("load", function(){
            HTMLURL = (options.staticPrefix
                ? (options.local ? dirname(document.baseURI) + "/static" : options.staticPrefix)
                    + options.htmlPath
                : "/static/plugins/c9.ide.preview/previewers/markdown.html")
                    + "?host=" + (options.local ? "local" : location.origin);

            if (HTMLURL.charAt(0) == "/")
                HTMLURL = location.protocol + "//" + location.host + HTMLURL;

            previewOrigin = HTMLURL.match(/^(?:[^\/]|\/\/)*/)[0];
        });
        plugin.on("documentLoad", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var tab     = doc.tab;
            var editor  = e.editor;

            var iframe = document.createElement("iframe");

            // iframe.setAttribute("nwfaketop", true);
            iframe.setAttribute("nwdisable", true);

            iframe.style.width    = "100%";
            iframe.style.height   = "100%";
            iframe.style.border   = 0;
            iframe.style.backgroundColor = "rgba(255, 255, 255, 0.88)";

            if (options.local) {
                iframe.onload = function(){
                    plugin.activeSession.add(iframe.contentWindow.location.href);
                }
            }

            var onMessage = function(e) {
                if (c9.hosted && event.origin !== previewOrigin)
                    return;

                if (e.data.message == "exec") {
                    commands.exec(e.data.command);
                }
                else if (e.data.message == "focus") {
                    tabManager.focusTab(tab);
                }
                else if (e.data.message == "stream.document") {
                    session.source = e.source;

                    if (session.previewTab) {
                        var doc = session.previewTab.document;

                        session.source.postMessage({
                            type    : "document",
                            content : doc.value
                        }, "*");

                        if (!doc.hasValue())
                            doc.once("setValue", function(){
                                emit("update", { previewDocument: doc });
                            });
                    }
                    else {
                        fs.readFile(session.path, function(err, data){
                            if (err)
                                return showError(err.message);

                            session.source.postMessage({
                                type    : "document",
                                content : data
                            }, "*");
                        });
                    }

                    session.source.postMessage({
                        type : "keys",
                        keys : commands.getExceptionBindings()
                    }, "*");

                    tab.className.remove("loading");
                }
            };
            window.addEventListener("message", onMessage, false);
            session.addOther(function(){
                window.removeEventListener("message", onMessage, false);
            });

            // Set iframe
            session.iframe = iframe;

            // Load the markup renderer
            iframe.src = HTMLURL;

            session.editor = editor;
            editor.container.appendChild(session.iframe);
        });
        plugin.on("documentUnload", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var iframe  = session.iframe;
            iframe.parentNode.removeChild(iframe);

            if (session.onchange)
                session.pdoc.undoManager.off("change", session.onchange);

            doc.tab.className.remove("loading");
        });
        plugin.on("documentActivate", function(e){
            var session = e.doc.getSession();

            session.iframe.style.display = "block";
            session.editor.setLocation(session.path);
            session.editor.setButtonStyle("Markdown", "page_white.png");
        });
        plugin.on("documentDeactivate", function(e){
            var session = e.doc.getSession();
            session.iframe.style.display = "none";
        });
        plugin.on("navigate", function(e){
            var tab    = plugin.activeDocument.tab;
            var iframe = plugin.activeSession.iframe;
            var editor = plugin.activeSession.editor;

            tab.className.add("loading");

            tab.title    =
            tab.tooltip  = "[M] " + e.url;
            editor.setLocation(e.url);

            iframe.src = iframe.src;
        });
        plugin.on("update", function(e){
            var session = plugin.activeSession;
            if (!session.source) return; // Renderer is not loaded yet

            session.source.postMessage({
                type    : "document",
                content : e.previewDocument.value
            }, "*");
        });
        plugin.on("reload", function(){
            var iframe = plugin.activeSession.iframe;
            var tab    = plugin.activeDocument.tab;
            tab.className.add("loading");
            iframe.src = iframe.src;
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
        });

        /***** Register and define API *****/

        /**
         * Previewer for markdown content.
         **/
        plugin.freezePublicAPI({
        });

        register(null, {
            "preview.markdown": plugin
        });
    }
});<commit_msg>Propely fixes markdown preview<commit_after>define(function(require, exports, module) {
    main.consumes = [
        "c9", "Previewer", "fs", "dialog.error", "commands", "tabManager"
    ];
    main.provides = ["preview.markdown"];
    return main;

    // @todo possible improvements: http://benweet.github.io/stackedit/#

    function main(options, imports, register) {
        var Previewer  = imports.Previewer;
        var c9         = imports.c9;
        var fs         = imports.fs;
        var commands   = imports.commands;
        var tabManager = imports.tabManager;
        var showError  = imports["dialog.error"].show;
        var dirname    = require("path").dirname;

        /***** Initialization *****/

        var plugin = new Previewer("Ajax.org", main.consumes, {
            caption  : "Markdown",
            index    : 200,
            selector : function(path){
                return path.match(/(?:\.md|\.markdown)$/i);
            }
        });
        var emit = plugin.getEmitter();

        var HTMLURL, previewOrigin;

        /***** Methods *****/

        function getPreviewUrl(fn){
            if (options.local && document.baseURI.substr(0, 5) == "file:")
                return setTimeout(getPreviewUrl.bind(null, fn), 100);
            else if (HTMLURL)
                return fn(HTMLURL);

            HTMLURL = (options.staticPrefix
                ? (options.local ? dirname(document.baseURI) + "/static" : options.staticPrefix)
                    + options.htmlPath
                : "/static/plugins/c9.ide.preview/previewers/markdown.html")
                    + "?host=" + (options.local ? "local" : location.origin);

            if (HTMLURL.charAt(0) == "/")
                HTMLURL = location.protocol + "//" + location.host + HTMLURL;

            previewOrigin = HTMLURL.match(/^(?:[^\/]|\/\/)*/)[0];

            fn(HTMLURL);
        }

        /***** Lifecycle *****/

        plugin.on("load", function(){

        });
        plugin.on("documentLoad", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var tab     = doc.tab;
            var editor  = e.editor;

            var iframe = document.createElement("iframe");

            // iframe.setAttribute("nwfaketop", true);
            iframe.setAttribute("nwdisable", true);

            iframe.style.width    = "100%";
            iframe.style.height   = "100%";
            iframe.style.border   = 0;
            iframe.style.backgroundColor = "rgba(255, 255, 255, 0.88)";

            if (options.local) {
                iframe.onload = function(){
                    plugin.activeSession.add(iframe.contentWindow.location.href);
                }
            }

            var onMessage = function(e) {
                if (c9.hosted && event.origin !== previewOrigin)
                    return;

                if (e.data.message == "exec") {
                    commands.exec(e.data.command);
                }
                else if (e.data.message == "focus") {
                    tabManager.focusTab(tab);
                }
                else if (e.data.message == "stream.document") {
                    session.source = e.source;

                    if (session.previewTab) {
                        var doc = session.previewTab.document;

                        session.source.postMessage({
                            type    : "document",
                            content : doc.value
                        }, "*");

                        if (!doc.hasValue())
                            doc.once("setValue", function(){
                                emit("update", { previewDocument: doc });
                            });
                    }
                    else {
                        fs.readFile(session.path, function(err, data){
                            if (err)
                                return showError(err.message);

                            session.source.postMessage({
                                type    : "document",
                                content : data
                            }, "*");
                        });
                    }

                    session.source.postMessage({
                        type : "keys",
                        keys : commands.getExceptionBindings()
                    }, "*");

                    tab.className.remove("loading");
                }
            };
            window.addEventListener("message", onMessage, false);
            session.addOther(function(){
                window.removeEventListener("message", onMessage, false);
            });

            // Set iframe
            session.iframe = iframe;

            // Load the markup renderer
            getPreviewUrl(function(url){ iframe.src = url; });

            session.editor = editor;
            editor.container.appendChild(session.iframe);
        });
        plugin.on("documentUnload", function(e){
            var doc     = e.doc;
            var session = doc.getSession();
            var iframe  = session.iframe;
            iframe.parentNode.removeChild(iframe);

            if (session.onchange)
                session.pdoc.undoManager.off("change", session.onchange);

            doc.tab.className.remove("loading");
        });
        plugin.on("documentActivate", function(e){
            var session = e.doc.getSession();

            session.iframe.style.display = "block";
            session.editor.setLocation(session.path);
            session.editor.setButtonStyle("Markdown", "page_white.png");
        });
        plugin.on("documentDeactivate", function(e){
            var session = e.doc.getSession();
            session.iframe.style.display = "none";
        });
        plugin.on("navigate", function(e){
            var tab    = plugin.activeDocument.tab;
            var iframe = plugin.activeSession.iframe;
            var editor = plugin.activeSession.editor;

            tab.className.add("loading");

            tab.title    =
            tab.tooltip  = "[M] " + e.url;
            editor.setLocation(e.url);

            iframe.src = iframe.src;
        });
        plugin.on("update", function(e){
            var session = plugin.activeSession;
            if (!session.source) return; // Renderer is not loaded yet

            session.source.postMessage({
                type    : "document",
                content : e.previewDocument.value
            }, "*");
        });
        plugin.on("reload", function(){
            var iframe = plugin.activeSession.iframe;
            var tab    = plugin.activeDocument.tab;
            tab.className.add("loading");
            iframe.src = iframe.src;
        });
        plugin.on("enable", function(){

        });
        plugin.on("disable", function(){

        });
        plugin.on("unload", function(){
        });

        /***** Register and define API *****/

        /**
         * Previewer for markdown content.
         **/
        plugin.freezePublicAPI({
        });

        register(null, {
            "preview.markdown": plugin
        });
    }
});<|endoftext|>


<commit_before>module.exports = {
    server: {
        host: '0.0.0.0',
        port: 3000,
        shutdown: {
            delay: '5s'
        }
    },
    mongodb: {
        options: {
            db: {
                readPreference: 'secondaryPreferred',
                maxTimeMS: 30000
            },
            server: {
                poolSize: 5,
                autoReconnect: true,
                reconnectTries: 30,
                reconnectInterval: 1000,
                socketOptions: {
                    keepAlive: 5000,
                    connectTimeoutMS: 10000,
                    socketTimeoutMS: 30000,
                    noDelay: true
                }
            }
        }
    },
    redis: {
    },
    postgres: {
    },
<% if (setup.indexOf('basics') > -1) { %>
    service: {
        reload: {
            window: '60s'
        }
    },
    logger: {
        transport: 'bunyan',
        include: [
            'tracer',
            'timestamp',
            'level',
            'message',
            'error.message',
            'error.code',
            'error.stack',
            'request.url',
            'request.headers',
            'request.params',
            'request.method',
            'response.statusCode',
            'response.headers',
            'response.time',
            'process',
            'system',
            'package.name',
            'mongo',
            'service'
        ],
        exclude: [
            'password',
            'secret',
            'token',
            'request.headers.cookie',
            'dependencies',
            'devDependencies'
        ]
    }
<% } %>
}
<commit_msg>Configuration snippet configured for express<commit_after>module.exports = {
<% if (setup.indexOf('express') > -1) { %>
    server: {
        host: '0.0.0.0',
        port: 3000,
        shutdown: {
            delay: '5s'
        }
    },
<% } %>
    mongodb: {
        options: {
            db: {
                readPreference: 'secondaryPreferred',
                maxTimeMS: 30000
            },
            server: {
                poolSize: 5,
                autoReconnect: true,
                reconnectTries: 30,
                reconnectInterval: 1000,
                socketOptions: {
                    keepAlive: 5000,
                    connectTimeoutMS: 10000,
                    socketTimeoutMS: 30000,
                    noDelay: true
                }
            }
        }
    },
    redis: {
    },
    postgres: {
    },
<% if (setup.indexOf('basics') > -1) { %>
    service: {
        reload: {
            window: '60s'
        }
    },
    logger: {
        transport: 'bunyan',
        include: [
            'tracer',
            'timestamp',
            'level',
            'message',
            'error.message',
            'error.code',
            'error.stack',
            'request.url',
            'request.headers',
            'request.params',
            'request.method',
            'response.statusCode',
            'response.headers',
            'response.time',
            'process',
            'system',
            'package.name',
            'mongo',
            'service'
        ],
        exclude: [
            'password',
            'secret',
            'token',
            'request.headers.cookie',
            'dependencies',
            'devDependencies'
        ]
    }
<% } %>
}
<|endoftext|>


<commit_before>var util = require("./util")

/*
Callsite name management
*/

var idstack = [""]
function enterfn(id) { idstack.push(idstack[idstack.length-1] + ":" + id) }
function leavefn(id) { idstack.pop() }
//Return the current structural name, as determined by the interpreter stack and loop counters of the trace:
function currentName(trace){
    var id = idstack[idstack.length-1]
    var loopnum = trace.loopcounters[id] || 0
    trace.loopcounters[id] = loopnum + 1
	return id + "." + loopnum
}

/*
Variables generated by ERPs
*/
function RandomVariableRecord(name, erp, params, val, logprob, structural, conditioned)
{
	this.name = name
	this.erp = erp
	this.params = params
	this.val = val
	this.logprob = logprob
	this.active = false //this is true if var is touched by traceUpdate (for keeping track of unused vars after MH proposal)
	this.structural = structural
	this.conditioned = conditioned
}

RandomVariableRecord.prototype.copy = function copy()
{
	return new RandomVariableRecord(this.name, this.erp, this.params, this.val,
									this.logprob, this.structural, this.conditioned)
}

/*
Execution trace generated by a probabilistic program.
Tracks the random choices made and accumulates probabilities.
*/
function RandomExecutionTrace(computation, init)
{
	init = (init == undefined ? "rejection" : init)
	this.computation = computation
	this.vars = {}
	this.varlist = []
	this.currVarIndex = 0
	this.logprob = 0.0
	this.newlogprob = 0.0
	this.oldlogprob = 0.0
	this.loopcounters = {}
	this.conditionsSatisfied = false
	this.returnValue = null
    this.structureIsFixed = false
    this.enumerate = false //Enumeration mode sets new ERP calls to start of domain.

	if (init == "rejection") {
		while (!this.conditionsSatisfied)
		{
			this.reset()
		}
	} else if (init=="enumerate") {
        this.enumerate=true
        this.traceUpdate()
        this.enumerate=false
        while (!this.conditionsSatisfied) {
            if (!this.nextEnumState()) //try going to next state.
            {this.reset()} //if we didn't find a satsfying state, reset.
        }
    } else if (init=="lessdumb") {
        //if(this.enumerate) throw error("how did enumerate get turned on?")
        this.traceUpdate()
        var i=1, esteps=1
        while (!this.conditionsSatisfied || this.logprob === -Infinity) {
            if(i%esteps == 0) {
                //reset and initialize randomly:
                this.reset()
                //do more enumeration after every restart:
                esteps += 10
            } else {
                if (!this.nextEnumState()) //try going to next state.
                {this.reset()} //if we didn't find a satsfying state, reset.
            }
            i += 1
        }
    }
}

RandomExecutionTrace.prototype.reset = function reset()
{
    this.vars = {}
    this.varlist = []
    this.traceUpdate()
}

RandomExecutionTrace.prototype.deepcopy = function deepcopy()
{
	var newdb = new RandomExecutionTrace(this.computation, false)
	newdb.logprob = this.logprob
	newdb.oldlogprob = this.oldlogprob
	newdb.newlogprob = this.newlogprob
	newdb.conditionsSatisfied = this.conditionsSatisfied
	newdb.returnValue = this.returnValue

	for (var i = 0; i < this.varlist.length; i++)
	{
		var newvar = this.varlist[i].copy()
		newdb.varlist.push(newvar)
		newdb.vars[newvar.name] = newvar
	}

	return newdb
}

//RandomExecutionTrace.prototype.freeVarNames = function freeVarNames(structural, nonstructural)
//{
//	structural = (structural == undefined ? true : structural)
//	nonstructural = (nonstructural == undefined ? true : nonstructural)
//	var names = []
//	for (var i=0, rec; rec = this.varlist[i]; i++)
//	{
//		if ()
//        {names.push(rec.name)}
//    }
//	return names
//}
RandomExecutionTrace.prototype.freeVarNames = function freeVarNames(pred)
{
	pred = (pred == undefined ? function(r){return true} : pred)
	var names = []
	for (var i=0, rec; rec = this.varlist[i]; i++)
	{
		if (!rec.conditioned && pred(rec)) {names.push(rec.name)}
    }
	return names
}

/*
Names of variables that this trace has that the other does not
*/
RandomExecutionTrace.prototype.varDiff = function varDiff(other)
{
	var arr = []
	for (var name in this.vars)
	{
		if (!other.vars[name])
			arr.push(name)
	}
	return arr
}

/*
Difference in log probability between this trace and the other
due to variables that this one has that the other does not
*/
RandomExecutionTrace.prototype.lpDiff = function lpDiff(other)
{
	return this.varDiff(other)
		.map(function(name) {return this.vars[name].logprob}.bind(this))
		.reduce(function(a,b) {return a+b}, 0)
}

/*
The singleton trace object
*/
var trace = null

/*
Run computation and update this trace accordingly
*/
RandomExecutionTrace.prototype.traceUpdate = function traceUpdate(structureIsFixed)
{
    structureIsFixed = (structureIsFixed===undefined?false:structureIsFixed)

	var origtrace = trace
	trace = this

	this.logprob = 0.0
	this.newlogprob = 0.0
	this.genlogprob = 0.0
	this.loopcounters = {}
	this.conditionsSatisfied = true
	this.currVarIndex = 0
    this.structureIsFixed = structureIsFixed

	// If updating this trace can change the variable structure, then we
	// clear out the flat list of variables beforehand
	if (!structureIsFixed) {
        var oldvarlist = this.varlist
        this.varlist=[]
    }

	// Run the computation, creating/looking up random variables
	this.returnValue = this.computation()

	// Clean up
	this.loopcounters = {}

  this.oldlogprob = 0.0
  if (!structureIsFixed) {
    // Clear out any old random values that are no longer reachable
    for(var i=0,rec; rec = oldvarlist[i]; i++) {
      // before checking to see if the old random value is active,
      // make sure that it was not supplanted by a new value
      // (e.g., change of support)
      if( this.vars[rec.name] == rec && !rec.active) {
        this.oldlogprob += rec.logprob
        delete this.vars[rec.name]
      }
    }
  }

   //reset active record marks for next traceUpdate..
   for(var i=0, v; v=this.varlist[i]; i++) {v.active = false}

	// Reset the original singleton trace
	trace = origtrace
}

/*
Propose a random change to a random variable 'varname'
Returns a new sample trace from the computation and the
forward and reverse probabilities of this proposal
*/
RandomExecutionTrace.prototype.proposeChange = function proposeChange(varname)
{
	var nextTrace = this.deepcopy()
	var v = nextTrace.getRecord(varname)
	var propval = v.erp.proposal(v.val, v.params)
	var fwdPropLP = v.erp.logProposalProb(v.val, propval, v.params)
	var rvsPropLP = v.erp.logProposalProb(propval, v.val, v.params)
	v.val = propval
	v.logprob = v.erp.logprob(v.val, v.params)
    nextTrace.traceUpdate(!v.structural)
	fwdPropLP += nextTrace.newlogprob
	rvsPropLP += nextTrace.oldlogprob
	return [nextTrace, fwdPropLP, rvsPropLP]
}

/*
Looks up the value of a random variable.
Creates the variable if it does not already exist
*/
RandomExecutionTrace.prototype.lookup = function lookup(erp, params, isStructural, conditionedValue)
{
    var record = null
    var name = null

    // If structure of this trace is fixed get variable from flatlist, otherwise do slower structural lookup
    if (this.structureIsFixed) {
        record = this.varlist[this.currVarIndex]
    } else {
        name = currentName(this)
        record = this.vars[name]
        if (record) {
          if (record.erp !== erp) {
            record = null
          } else {
            if ( record.structural !== isStructural ||
                 // if this ERP compares supports but we fail the
                 // comparison, say that there's no record
                 (erp.compareSupport && !erp.compareSupport(params, record.params))
               ) {
              record = null;
            }
          }
        }
    }

	// If we didn't find the variable, create a new one
	if (!record)
	{
        if (this.enumerate && typeof erp.nextVal === 'function') { // If we are doing ennumeration init new vars to first val in domain:
            var val = erp.nextVal(null, params)
        } else {
            var val = (conditionedValue == undefined) ? erp.sample_impl(params) : conditionedValue
        }
		var ll = erp.logprob(val, params)
		this.newlogprob += ll
		if (conditionedValue == undefined) this.genlogprob += ll
		record = new RandomVariableRecord(name, erp, params, val, ll, isStructural, conditionedValue !== undefined)
		this.vars[name] = record
	}
	// Otherwise, reuse the variable we found, but check if its parameters/conditioning
	// status have changed
	else {
		record.conditioned = (conditionedValue != undefined)
		var hasChanges = false
		if (!util.arrayEquals(record.params, params))
		{
			record.params = params
			hasChanges = true
		}
		if (conditionedValue && conditionedValue != record.val)
		{
			record.val = conditionedValue
			record.conditioned = true
			hasChanges = true
		}
		if (hasChanges) {record.logprob = erp.logprob(record.val, record.params)}
    }

	// Finish up and return
    this.currVarIndex++
    this.logprob += record.logprob
    record.active = true
    if (!this.structureIsFixed){ this.varlist.push(record)}
    return record.val
}

// Simply retrieve the variable record associated with 'name'
RandomExecutionTrace.prototype.getRecord = function getRecord(name)
{
	return this.vars[name]
}

// Add a new factor into the log-likelihood of this trace
RandomExecutionTrace.prototype.addFactor = function addFactor(num)
{
	this.logprob += num
}

// Condition the trace on the value of a boolean expression
RandomExecutionTrace.prototype.conditionOn = function conditionOn(boolexpr)
{
	this.conditionsSatisfied &= boolexpr
}

//Next state for enumeration:
RandomExecutionTrace.prototype.nextEnumState = function nextEnumState() {
    this.enumerate=true
    var names = this.freeVarNames()

    var newval = null
    while (newval == null) {

        // if we are out of names it means we're done enumerating with no satisfying execution, return null.
        if (names.length == 0) {this.enumerate=false; return null}

        //otherwise get next var:
        var varname = names.pop()
        var v = this.getRecord(varname)

      if (!v) {
        continue
      }

        //if the domain is enumerable, go to next value:
        if (typeof v.erp.nextVal === 'function') {
            var newval = v.erp.nextVal(v.val, v.params)
            if (newval == null) {
                v.val = v.erp.nextVal(null, v.params) //get first in domain
            } else {
                v.val = newval
            }
            v.logprob = v.erp.logprob(v.val, v.params)
        }
    }
    this.traceUpdate()
    this.enumerate=false
    return this
}

// Exported functions for interacting with the global trace

function lookupVariableValue(erp, params, isStructural, conditionedValue)
{
	if (!trace)
	{
		return conditionedValue || erp.sample_impl(params)
	}
	else
	{
		return trace.lookup(erp, params, isStructural, conditionedValue)
	}
}

function newTrace(computation, init)
{
	return new RandomExecutionTrace(computation, init)
}

function factor(num)
{
	if (trace)
		trace.addFactor(num)
}

function condition(boolexpr)
{
	if (trace)
		trace.conditionOn(boolexpr)
}

module.exports =
{
	enterfn: enterfn,
	leavefn: leavefn,
//    setmaxid: setmaxid,
	lookupVariableValue: lookupVariableValue,
	newTrace: newTrace,
	factor: factor,
	condition: condition
}
<commit_msg>Decruft<commit_after>var util = require("./util")

/*
Callsite name management
*/

var idstack = [""]
function enterfn(id) { idstack.push(idstack[idstack.length-1] + ":" + id) }
function leavefn(id) { idstack.pop() }
//Return the current structural name, as determined by the interpreter stack and loop counters of the trace:
function currentName(trace){
    var id = idstack[idstack.length-1]
    var loopnum = trace.loopcounters[id] || 0
    trace.loopcounters[id] = loopnum + 1
	return id + "." + loopnum
}

/*
Variables generated by ERPs
*/
function RandomVariableRecord(name, erp, params, val, logprob, structural, conditioned)
{
	this.name = name
	this.erp = erp
	this.params = params
	this.val = val
	this.logprob = logprob
	this.active = false //this is true if var is touched by traceUpdate (for keeping track of unused vars after MH proposal)
	this.structural = structural
	this.conditioned = conditioned
}

RandomVariableRecord.prototype.copy = function copy()
{
	return new RandomVariableRecord(this.name, this.erp, this.params, this.val,
									this.logprob, this.structural, this.conditioned)
}

/*
Execution trace generated by a probabilistic program.
Tracks the random choices made and accumulates probabilities.
*/
function RandomExecutionTrace(computation, init)
{
	init = (init == undefined ? "rejection" : init)
	this.computation = computation
	this.vars = {}
	this.varlist = []
	this.currVarIndex = 0
	this.logprob = 0.0
	this.newlogprob = 0.0
	this.oldlogprob = 0.0
	this.loopcounters = {}
	this.conditionsSatisfied = false
	this.returnValue = null
    this.structureIsFixed = false
    this.enumerate = false //Enumeration mode sets new ERP calls to start of domain.

	if (init == "rejection") {
		while (!this.conditionsSatisfied)
		{
			this.reset()
		}
	} else if (init=="enumerate") {
        this.enumerate=true
        this.traceUpdate()
        this.enumerate=false
        while (!this.conditionsSatisfied) {
            if (!this.nextEnumState()) //try going to next state.
            {this.reset()} //if we didn't find a satsfying state, reset.
        }
    } else if (init=="lessdumb") {
        //if(this.enumerate) throw error("how did enumerate get turned on?")
        this.traceUpdate()
        var i=1, esteps=1
        while (!this.conditionsSatisfied || this.logprob === -Infinity) {
            if(i%esteps == 0) {
                //reset and initialize randomly:
                this.reset()
                //do more enumeration after every restart:
                esteps += 10
            } else {
                if (!this.nextEnumState()) //try going to next state.
                {this.reset()} //if we didn't find a satsfying state, reset.
            }
            i += 1
        }
    }
}

RandomExecutionTrace.prototype.reset = function reset()
{
    this.vars = {}
    this.varlist = []
    this.traceUpdate()
}

RandomExecutionTrace.prototype.deepcopy = function deepcopy()
{
	var newdb = new RandomExecutionTrace(this.computation, false)
	newdb.logprob = this.logprob
	newdb.oldlogprob = this.oldlogprob
	newdb.newlogprob = this.newlogprob
	newdb.conditionsSatisfied = this.conditionsSatisfied
	newdb.returnValue = this.returnValue

	for (var i = 0; i < this.varlist.length; i++)
	{
		var newvar = this.varlist[i].copy()
		newdb.varlist.push(newvar)
		newdb.vars[newvar.name] = newvar
	}

	return newdb
}

//RandomExecutionTrace.prototype.freeVarNames = function freeVarNames(structural, nonstructural)
//{
//	structural = (structural == undefined ? true : structural)
//	nonstructural = (nonstructural == undefined ? true : nonstructural)
//	var names = []
//	for (var i=0, rec; rec = this.varlist[i]; i++)
//	{
//		if ()
//        {names.push(rec.name)}
//    }
//	return names
//}
RandomExecutionTrace.prototype.freeVarNames = function freeVarNames(pred)
{
	pred = (pred == undefined ? function(r){return true} : pred)
	var names = []
	for (var i=0, rec; rec = this.varlist[i]; i++)
	{
		if (!rec.conditioned && pred(rec)) {names.push(rec.name)}
    }
	return names
}

/*
Names of variables that this trace has that the other does not
*/
RandomExecutionTrace.prototype.varDiff = function varDiff(other)
{
	var arr = []
	for (var name in this.vars)
	{
		if (!other.vars[name])
			arr.push(name)
	}
	return arr
}

/*
Difference in log probability between this trace and the other
due to variables that this one has that the other does not
*/
RandomExecutionTrace.prototype.lpDiff = function lpDiff(other)
{
	return this.varDiff(other)
		.map(function(name) {return this.vars[name].logprob}.bind(this))
		.reduce(function(a,b) {return a+b}, 0)
}

/*
The singleton trace object
*/
var trace = null

/*
Run computation and update this trace accordingly
*/
RandomExecutionTrace.prototype.traceUpdate = function traceUpdate(structureIsFixed)
{
    structureIsFixed = (structureIsFixed===undefined?false:structureIsFixed)

	var origtrace = trace
	trace = this

	this.logprob = 0.0
	this.newlogprob = 0.0
	this.genlogprob = 0.0
	this.loopcounters = {}
	this.conditionsSatisfied = true
	this.currVarIndex = 0
    this.structureIsFixed = structureIsFixed

	// If updating this trace can change the variable structure, then we
	// clear out the flat list of variables beforehand
	if (!structureIsFixed) {
        var oldvarlist = this.varlist
        this.varlist=[]
    }

	// Run the computation, creating/looking up random variables
	this.returnValue = this.computation()

	// Clean up
	this.loopcounters = {}

  this.oldlogprob = 0.0
  if (!structureIsFixed) {
    // Clear out any old random values that are no longer reachable
    for(var i=0,rec; rec = oldvarlist[i]; i++) {
      // before checking to see if the old random value is active,
      // make sure that it was not supplanted by a new value
      // (e.g., change of support)
      if( this.vars[rec.name] == rec && !rec.active) {
        this.oldlogprob += rec.logprob
        delete this.vars[rec.name]
      }
    }
  }

   //reset active record marks for next traceUpdate..
   for(var i=0, v; v=this.varlist[i]; i++) {v.active = false}

	// Reset the original singleton trace
	trace = origtrace
}

/*
Propose a random change to a random variable 'varname'
Returns a new sample trace from the computation and the
forward and reverse probabilities of this proposal
*/
RandomExecutionTrace.prototype.proposeChange = function proposeChange(varname)
{
	var nextTrace = this.deepcopy()
	var v = nextTrace.getRecord(varname)
	var propval = v.erp.proposal(v.val, v.params)
	var fwdPropLP = v.erp.logProposalProb(v.val, propval, v.params)
	var rvsPropLP = v.erp.logProposalProb(propval, v.val, v.params)
	v.val = propval
	v.logprob = v.erp.logprob(v.val, v.params)
    nextTrace.traceUpdate(!v.structural)
	fwdPropLP += nextTrace.newlogprob
	rvsPropLP += nextTrace.oldlogprob
	return [nextTrace, fwdPropLP, rvsPropLP]
}

/*
Looks up the value of a random variable.
Creates the variable if it does not already exist
*/
RandomExecutionTrace.prototype.lookup = function lookup(erp, params, isStructural, conditionedValue)
{
    var record = null
    var name = null

    // If structure of this trace is fixed get variable from flatlist, otherwise do slower structural lookup
    if (this.structureIsFixed) {
        record = this.varlist[this.currVarIndex]
    } else {
        name = currentName(this)
        record = this.vars[name]
        if (record) {
          if (record.erp !== erp) {
            record = null
          } else {
            if ( record.structural !== isStructural ||
                 // if this ERP compares supports but we fail the
                 // comparison, say that there's no record
                 (erp.compareSupport && !erp.compareSupport(params, record.params))
               ) {
              record = null;
            }
          }
        }
    }

	// If we didn't find the variable, create a new one
	if (!record)
	{
        if (this.enumerate && typeof erp.nextVal === 'function') { // If we are doing ennumeration init new vars to first val in domain:
            var val = erp.nextVal(null, params)
        } else {
            var val = (conditionedValue == undefined) ? erp.sample_impl(params) : conditionedValue
        }
		var ll = erp.logprob(val, params)
		this.newlogprob += ll
		if (conditionedValue == undefined) this.genlogprob += ll
		record = new RandomVariableRecord(name, erp, params, val, ll, isStructural, conditionedValue !== undefined)
		this.vars[name] = record
	}
	// Otherwise, reuse the variable we found, but check if its parameters/conditioning
	// status have changed
	else {
		record.conditioned = (conditionedValue != undefined)
		var hasChanges = false
		if (!util.arrayEquals(record.params, params))
		{
			record.params = params
			hasChanges = true
		}
		if (conditionedValue && conditionedValue != record.val)
		{
			record.val = conditionedValue
			record.conditioned = true
			hasChanges = true
		}
		if (hasChanges) {record.logprob = erp.logprob(record.val, record.params)}
    }

	// Finish up and return
    this.currVarIndex++
    this.logprob += record.logprob
    record.active = true
    if (!this.structureIsFixed){ this.varlist.push(record)}
    return record.val
}

// Simply retrieve the variable record associated with 'name'
RandomExecutionTrace.prototype.getRecord = function getRecord(name)
{
	return this.vars[name]
}

// Add a new factor into the log-likelihood of this trace
RandomExecutionTrace.prototype.addFactor = function addFactor(num)
{
	this.logprob += num
}

// Condition the trace on the value of a boolean expression
RandomExecutionTrace.prototype.conditionOn = function conditionOn(boolexpr)
{
	this.conditionsSatisfied &= boolexpr
}

//Next state for enumeration:
RandomExecutionTrace.prototype.nextEnumState = function nextEnumState() {
    this.enumerate=true
    var names = this.freeVarNames()

    var newval = null
    while (newval == null) {

        // if we are out of names it means we're done enumerating with no satisfying execution, return null.
        if (names.length == 0) {this.enumerate=false; return null}

        //otherwise get next var:
        var varname = names.pop()
        var v = this.getRecord(varname)

        //if the domain is enumerable, go to next value:
        if (typeof v.erp.nextVal === 'function') {
            var newval = v.erp.nextVal(v.val, v.params)
            if (newval == null) {
                v.val = v.erp.nextVal(null, v.params) //get first in domain
            } else {
                v.val = newval
            }
            v.logprob = v.erp.logprob(v.val, v.params)
        }
    }
    this.traceUpdate()
    this.enumerate=false
    return this
}

// Exported functions for interacting with the global trace

function lookupVariableValue(erp, params, isStructural, conditionedValue)
{
	if (!trace)
	{
		return conditionedValue || erp.sample_impl(params)
	}
	else
	{
		return trace.lookup(erp, params, isStructural, conditionedValue)
	}
}

function newTrace(computation, init)
{
	return new RandomExecutionTrace(computation, init)
}

function factor(num)
{
	if (trace)
		trace.addFactor(num)
}

function condition(boolexpr)
{
	if (trace)
		trace.conditionOn(boolexpr)
}

module.exports =
{
	enterfn: enterfn,
	leavefn: leavefn,
//    setmaxid: setmaxid,
	lookupVariableValue: lookupVariableValue,
	newTrace: newTrace,
	factor: factor,
	condition: condition
}
<|endoftext|>


<commit_before>// ControlDepo 3 Widget Component
// based on
//		Justin Palmer's EventSelectors (http://encytemedia.com/event-selectors)
// 		Dan Webb's LowPro (http://svn.danwebb.net/external/lowpro)
if (!CD3) var CD3 = {};

CD3.Behaviors = function(rules){
	document.observe('dom:loaded', CD3.Behaviors.assign.curry(rules, null));
}

Object.extend(CD3.Behaviors, {
	cache: [],
	assign: function(rules, parent){
		for (var selector in rules){
			var observer = rules[selector];
			selector.split(',').each(function(sel){
				var parts = sel.split(/:(?=[a-z]+$)/), css = parts.shift(), event = parts.join('');
				Selector.findChildElements(parent || document, [css]).each(function(element){
					if (event) {
						CD3.Behaviors.observe(element, event, observer);
					} else if (Object.isArray(observer)){
						var klass = observer.shift();
						new klass(element, observer.shift());
					} else if (observer.prototype && observer.prototype.initialize){
						new observer(element);
					} else if (Object.isFunction(observer)){
						observer.call(element, element);
					} else {
						for(var e in observer){
							CD3.Behaviors.observe(element, e, observer[e]);
						}
					}
				});
			});
		}
	},
	assignIf: function(selector, rules){
		var parent = $$(selector).first();
		if (parent) CD3.Behaviors.assign(Object.isFunction(rules) ? rules(parent) : rules, parent);
	},
	when: function(selector, rules){
		document.observe('dom:loaded', CD3.Behaviors.assignIf.curry(selector, rules));
	},
	observe: function(element, event, observer){
		if (!Object.isFunction(observer))
			observer = this.delegate(observer);

		$(element).observe(event, observer)
		CD3.Behaviors.cache.push([element, event, observer]);
	},
	delegate: function(rules){
		return function(e){
			var element = Event.element(e), elements = [element].concat(element.ancestors());
			for (var selector in rules)
				if (element = Selector.matchElements(elements, selector)[0])
					return rules[selector].call(element, e);
		}
	},
	unload: function(){
		CD3.Behaviors.cache.each(function(c){ Event.stopObserving.apply(Event, c); });
		CD3.Behaviors.cache = [];
	}
});

Event.observe(window, 'unload', CD3.Behaviors.unload);<commit_msg>Set value of parent once, not in every loop<commit_after>// ControlDepo 3 Widget Component
// based on
//		Justin Palmer's EventSelectors (http://encytemedia.com/event-selectors)
// 		Dan Webb's LowPro (http://svn.danwebb.net/external/lowpro)
if (!CD3) var CD3 = {};

CD3.Behaviors = function(rules){
	document.observe('dom:loaded', CD3.Behaviors.assign.curry(rules, null));
}

Object.extend(CD3.Behaviors, {
	cache: [],
	assign: function(rules, parent){
		parent = parent || document;
		for (var selector in rules){
			var observer = rules[selector];
			selector.split(',').each(function(sel){
				var parts = sel.split(/:(?=[a-z]+$)/), css = parts.shift(), event = parts.join('');
				Selector.findChildElements(parent, [css]).each(function(element){
					if (event) {
						CD3.Behaviors.observe(element, event, observer);
					} else if (Object.isArray(observer)){
						var klass = observer.shift();
						new klass(element, observer.shift());
					} else if (observer.prototype && observer.prototype.initialize){
						new observer(element);
					} else if (Object.isFunction(observer)){
						observer.call(element, element);
					} else {
						for(var e in observer){
							CD3.Behaviors.observe(element, e, observer[e]);
						}
					}
				});
			});
		}
	},
	assignIf: function(selector, rules){
		var parent = $$(selector).first();
		if (parent) CD3.Behaviors.assign(Object.isFunction(rules) ? rules(parent) : rules, parent);
	},
	when: function(selector, rules){
		document.observe('dom:loaded', CD3.Behaviors.assignIf.curry(selector, rules));
	},
	observe: function(element, event, observer){
		if (!Object.isFunction(observer))
			observer = this.delegate(observer);

		$(element).observe(event, observer)
		CD3.Behaviors.cache.push([element, event, observer]);
	},
	delegate: function(rules){
		return function(e){
			var element = Event.element(e), elements = [element].concat(element.ancestors());
			for (var selector in rules)
				if (element = Selector.matchElements(elements, selector)[0])
					return rules[selector].call(element, e);
		}
	},
	unload: function(){
		CD3.Behaviors.cache.each(function(c){ Event.stopObserving.apply(Event, c); });
		CD3.Behaviors.cache = [];
	}
});

Event.observe(window, 'unload', CD3.Behaviors.unload);<|endoftext|>