<commit_before>var linus = linus || {};
linus.canadapost = linus.canadapost || {};

linus.canadapost.d2po = linus.canadapost.d2po || (function($, Common)
{
    'use strict';

    var loaded = false;
    var apiKey = null;
    var map;

    var markers = [];
    var offices;

    function setApiKey(key)
    {
        apiKey = key;
    }

    function getApiKey()
    {
        return apiKey;
    }

    function lazyLoadGoogleMapsLibrary()
    {
        if (getApiKey() == null) {
            throw Exception('No GMaps Api key provided. Terminating.');
        }

        var promise = null;

        //Make sure we only load the GMaps library once.
        if (!loaded) {
            promise = $.when(
                $.ajax({
                    url: "https://maps.googleapis.com/maps/api/js?key=" + getApiKey(),
                    dataType: 'script',
                    cache: true,
                    crossDomain: true
                })
            ).then(function () {
                loaded = true;
            });
        } else {
            promise = $.when();
        }

        return promise;
    }

    /**
     * Load the office location data from Canada Post
     * @param epicenter
     * @returns {*}
     */
    function getPostOfficeData(epicenter)
    {
        return $.ajax('/canadapost/office/nearest?postal_code='+epicenter.postalCode+'&city='+epicenter.city+'&province='+epicenter.province, {
            method: 'GET',
            dataType: 'json'
        });
    }

    //Get the lat/long coordinates for the postal code
    function getPostalCodeCoordinates(postalCode, callback)
    {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: postalCode}, callback);
    }

    /**
     * Load the google maps library, then center on the give area code
     * @param $target
     * @param epicenter
     * @returns {*}
     */
    function createMap($target, epicenter)
    {
        return lazyLoadGoogleMapsLibrary()
            .then(function () {
                getPostalCodeCoordinates(epicenter.postalCode, function(results, status){
                    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
                        map = new google.maps.Map($target[0], {
                            center: results[0].geometry.location
                        });
                    }
                });
            });
    }

    /**
     * Load the post office data from Canada Post, and inject it as map markers.
     * @param epicenter
     */
    function displayOfficeMarkers(epicenter)
    {
        getPostOfficeData(epicenter).done(function(response){
            offices = response.payload;
            var $mapDiv = $(map.getDiv());

            $mapDiv.trigger('onOfficesLoaded', [response.payload]);

            var markerBounds = new google.maps.LatLngBounds();

            $.each(response.payload, function(index, office){
                var location = new google.maps.LatLng(
                    office.address.latitude,
                    office.address.longitude
                );

                var marker = new google.maps.Marker({
                    position: location,
                    title: office.name,
                    map: map,
                    animation: google.maps.Animation.DROP,
                    icon: Common.getCspData('cpost_logo')
                });

                markerBounds.extend(location);

                var content = '
' +
                    '' +
                    office.name +
                    '
' + office.address['office-address'] +
                    '
' + office.address.city  +
                    ', ' + office.address['postal-code'] +
                    '
'
                ;

                var infowindow = new google.maps.InfoWindow({
                    content: content
                });

                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                    $mapDiv.trigger('onOfficeMarkerClick', [office]);
                });

                markers.push(marker);
            });

            map.fitBounds(markerBounds);
        });
    }

    /**
     * Zoom and center on a specific location, generally to show an office
     * at a sane default zoom level.
     * @param latitude
     * @param longitude
     */
    function recenterAndZoom(latitude, longitude)
    {
        var markerBounds = new google.maps.LatLngBounds();
        var location = new google.maps.LatLng(
            latitude,
            longitude
        );
        markerBounds.extend(location);
        map.fitBounds(markerBounds);
        map.setZoom(16);
    }

    /**
     * Resets the zoom and map bounds to contain all displayed post offices.
     */
    function resetZoom()
    {
        var markerBounds = new google.maps.LatLngBounds();
        $.each(offices, function(index, office) {
            var location = new google.maps.LatLng(
                office.address.latitude,
                office.address.longitude
            );

            markerBounds.extend(location);
        });
        map.fitBounds(markerBounds);
    }

    /**
     * Wrap map creation (if not already created) and adding markers
     */
    function render(target, epicenter, apiKey)
    {
        var $target = $(target);

        if (typeof apiKey == 'undefined' || apiKey == null) {
           apiKey = linus.common.getCspData('gmaps_api_key');
        }

        setApiKey(apiKey);

        $.when(createMap($target, epicenter))
            .then(function(){
                displayOfficeMarkers(epicenter);
            });
    }

    /**
     * Get the current map object
     */
    function getMap()
    {
        return map;
    }

    return {
        getMap: getMap,
        recenterAndZoom: recenterAndZoom,
        render: render,
        resetZoom: resetZoom
    };
})(jQuery, linus.common);
<commit_msg>Wrap address in spans.<commit_after>var linus = linus || {};
linus.canadapost = linus.canadapost || {};

linus.canadapost.d2po = linus.canadapost.d2po || (function($, Common)
{
    'use strict';

    var loaded = false;
    var apiKey = null;
    var map;

    var markers = [];
    var offices;

    function setApiKey(key)
    {
        apiKey = key;
    }

    function getApiKey()
    {
        return apiKey;
    }

    function lazyLoadGoogleMapsLibrary()
    {
        if (getApiKey() == null) {
            throw Exception('No GMaps Api key provided. Terminating.');
        }

        var promise = null;

        //Make sure we only load the GMaps library once.
        if (!loaded) {
            promise = $.when(
                $.ajax({
                    url: "https://maps.googleapis.com/maps/api/js?key=" + getApiKey(),
                    dataType: 'script',
                    cache: true,
                    crossDomain: true
                })
            ).then(function () {
                loaded = true;
            });
        } else {
            promise = $.when();
        }

        return promise;
    }

    /**
     * Load the office location data from Canada Post
     * @param epicenter
     * @returns {*}
     */
    function getPostOfficeData(epicenter)
    {
        return $.ajax('/canadapost/office/nearest?postal_code='+epicenter.postalCode+'&city='+epicenter.city+'&province='+epicenter.province, {
            method: 'GET',
            dataType: 'json'
        });
    }

    //Get the lat/long coordinates for the postal code
    function getPostalCodeCoordinates(postalCode, callback)
    {
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: postalCode}, callback);
    }

    /**
     * Load the google maps library, then center on the give area code
     * @param $target
     * @param epicenter
     * @returns {*}
     */
    function createMap($target, epicenter)
    {
        return lazyLoadGoogleMapsLibrary()
            .then(function () {
                getPostalCodeCoordinates(epicenter.postalCode, function(results, status){
                    if (status == google.maps.GeocoderStatus.OK && results.length > 0) {
                        map = new google.maps.Map($target[0], {
                            center: results[0].geometry.location
                        });
                    }
                });
            });
    }

    /**
     * Load the post office data from Canada Post, and inject it as map markers.
     * @param epicenter
     */
    function displayOfficeMarkers(epicenter)
    {
        getPostOfficeData(epicenter).done(function(response){
            offices = response.payload;
            var $mapDiv = $(map.getDiv());

            $mapDiv.trigger('onOfficesLoaded', [response.payload]);

            var markerBounds = new google.maps.LatLngBounds();

            $.each(response.payload, function(index, office){
                var location = new google.maps.LatLng(
                    office.address.latitude,
                    office.address.longitude
                );

                var marker = new google.maps.Marker({
                    position: location,
                    title: office.name,
                    map: map,
                    animation: google.maps.Animation.DROP,
                    icon: Common.getCspData('cpost_logo')
                });

                markerBounds.extend(location);

                var content = '
' +
                    ''+office.name + '' +
                    '
' + office.address['office-address']+ '' +
                    '
' + office.address.city+ ''  +
                    ', ' + office.address.province+ ''  +
                    ' ' + office.address['postal-code']+ '' +
                    '
'
                ;

                var infowindow = new google.maps.InfoWindow({
                    content: content
                });

                marker.addListener('click', function() {
                    infowindow.open(map, marker);
                    $mapDiv.trigger('onOfficeMarkerClick', [office]);
                });

                markers.push(marker);
            });

            map.fitBounds(markerBounds);
        });
    }

    /**
     * Zoom and center on a specific location, generally to show an office
     * at a sane default zoom level.
     * @param latitude
     * @param longitude
     */
    function recenterAndZoom(latitude, longitude)
    {
        var markerBounds = new google.maps.LatLngBounds();
        var location = new google.maps.LatLng(
            latitude,
            longitude
        );
        markerBounds.extend(location);
        map.fitBounds(markerBounds);
        map.setZoom(16);
    }

    /**
     * Resets the zoom and map bounds to contain all displayed post offices.
     */
    function resetZoom()
    {
        var markerBounds = new google.maps.LatLngBounds();
        $.each(offices, function(index, office) {
            var location = new google.maps.LatLng(
                office.address.latitude,
                office.address.longitude
            );

            markerBounds.extend(location);
        });
        map.fitBounds(markerBounds);
    }

    /**
     * Wrap map creation (if not already created) and adding markers
     */
    function render(target, epicenter, apiKey)
    {
        var $target = $(target);

        if (typeof apiKey == 'undefined' || apiKey == null) {
           apiKey = linus.common.getCspData('gmaps_api_key');
        }

        setApiKey(apiKey);

        $.when(createMap($target, epicenter))
            .then(function(){
                displayOfficeMarkers(epicenter);
            });
    }

    /**
     * Get the current map object
     */
    function getMap()
    {
        return map;
    }

    return {
        getMap: getMap,
        recenterAndZoom: recenterAndZoom,
        render: render,
        resetZoom: resetZoom
    };
})(jQuery, linus.common);
<|endoftext|>


<commit_before>JSON.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(container, update, url, options) {
    this.container = $(container);

    options = options || { }

    this.baseInitialize(this.container.down('input[type=text]'), update, options);
    this.id_field              = this.container.down('input[type=hidden]')
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
    this.options.method        = this.options.method || 'get';
    this.options.paramName     = 'autocomplete';
    this.options.labelAttribute = this.options.labelAttribute || 'name'

    pulldown = document.createElement('img');
    pulldown.setAttribute('src', 'http://apps.urbacon.net/assets/images/pulldown.png');
    pulldown.setAttribute('alt', 'Show All');

    pulldown.style.position = 'absolute';
    pulldown.style.right = '-2px';
    pulldown.style.top = '2px';
    pulldown.style.cursor = 'pointer';

    if (Prototype.Browser.IE) {
      pulldown.style.right = '-4px';
      pulldown.style.top = '3px';
    }

    this.container.appendChild(pulldown);
    this.pulldownTrigger = pulldown;

    Event.observe(this.element, 'dblclick', this.getAllChoices.bindAsEventListener(this));
    Event.observe(this.pulldownTrigger, 'click', this.pulldown.bindAsEventListener(this));
  },

  pulldown: function(event) {
    if (Element.getStyle(this.update, 'display') == 'none') {
      this.active = true;
      this.element.focus();
      this.getAllChoices(event);
    } else {
      this.active = false;
      this.hide();
    }
  },

  onBlur: function(event) {
    // needed to make click events working
    if (event.explicitOriginalTarget != this.pulldownTrigger) {
      setTimeout(this.hide.bind(this), 250);
      this.hasFocus = false;
      this.active = false;
    }
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix &&
      /*(Prototype.Browser.IE) &&*/
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '');
      this.iefix = $(this.update.id+'_iefix');
      this.iefix.style.top = this.element.getHeight() + 'px';
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 60);

    setTimeout(this.fixSize.bind(this), 50);
  },

  fixSize: function() {
    if (this.update.offsetWidth < 200)
      this.update.style.width = '200px';

    height = this.update.down('ul').offsetHeight
    if (200 > height && height > 0)
      this.update.style.height = height + 'px';
    else
      this.update.style.height = '200px';
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  getAllChoices: function(event) {
    this.startIndicator();

    parameters = {};
    for (i in this.options.withFormElements) {
      parameters[i] = $F(this.options.withFormElements[i]);
    }
    this.options.parameters = parameters;

    new Ajax.Request(this.url, this.options);

    this.changed = false;
    this.hasFocus = true;
    this.element.focus();
  },

  getMoreChoices: function(event) {
    this.startIndicator();

    options2 = Object.clone(this.options);
    options2.parameters = this.options.defaultParams;

    new Ajax.Request(this.url, options2);

    this.changed = false;
    this.hasFocus = true;
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) { // use override callback (if present)
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';

    id_value = Element.collectTextNodes($(selectedElement).down('span.id'));
    label_value = Element.collectTextNodes($(selectedElement).down('span.label'))

    this.element.value = label_value;

    previous_id_value = this.id_field.value

    this.id_field.value = id_value

    if (previous_id_value != id_value && this.options.onchange) {
      this.options.onchange(id_value);
    }

    this.oldElementValue = this.element.value;
    this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  onComplete: function(request) {
    data = JSON.parse(request.responseText);

    more = null;

    ul = "
"

    data.each(function(entry){
      keys = []
      for (prop in entry)
        keys.push(prop);

      if (keys.length == 1 && typeof(entry[keys[0]]) == 'object')
        entry = entry[keys[0]]

      if (entry['id']) {
        label = entry[this.options.labelAttribute || 'id']

        ul += '
' +
          '' + label + '' +
          '' + entry['id'] + '' +
          '
';
      } else if (entry['more']) {
        more = entry['more'];
      }
    }, this)

    this.more = more;

    if (this.more) {
  		// FIXME: create an LI node for the next URL, then bind to it to
      //       Event.observe(more, 'click', this.getMoreChoices.bindAsEventListener(this));
  		ul += '
More...
';
  	}

    ul += "
"

    this.updateChoices(ul);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
    window.document.body.style.cursor = 'wait'
    this.element.style.cursor = 'wait'
    this.pulldownTrigger.style.cursor = 'wait'
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
    window.document.body.style.cursor = null
    this.element.style.cursor = null
    this.pulldownTrigger.style.cursor = null
  }
});<commit_msg>can now disable the pulldown, and clearing the autocomlete value should now correctly clear the id value<commit_after>JSON.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(container, update, url, options) {
    this.container = $(container);

    options = options || { }

    this.baseInitialize(this.container.down('input[type=text]'), update, options);
    this.id_field              = this.container.down('input[type=hidden]')
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
    this.options.method        = this.options.method || 'get';
    this.options.paramName     = 'autocomplete';
    this.options.labelAttribute = this.options.labelAttribute || 'name'
    this.options.disablePulldown = this.options.disablePulldown || false

    pulldown = document.createElement('img');
    pulldown.setAttribute('src', 'http://apps.urbacon.net/assets/images/pulldown.png');
    pulldown.setAttribute('alt', 'Show All');

    pulldown.style.position = 'absolute';
    pulldown.style.right = '-2px';
    pulldown.style.top = '2px';
    pulldown.style.cursor = 'pointer';

    if (Prototype.Browser.IE) {
      pulldown.style.right = '-4px';
      pulldown.style.top = '3px';
    }

    if (!this.options.disablePulldown)
      this.container.appendChild(pulldown);
    this.pulldownTrigger = pulldown;

    Event.observe(this.element, 'dblclick', this.getAllChoices.bindAsEventListener(this));
    Event.observe(this.pulldownTrigger, 'click', this.pulldown.bindAsEventListener(this));
    Event.observe(this.element, 'change', this.onChange.bindAsEventListener(this));
  },

  pulldown: function(event) {
    if (Element.getStyle(this.update, 'display') == 'none') {
      this.active = true;
      this.element.focus();
      this.getAllChoices(event);
    } else {
      this.active = false;
      this.hide();
    }
  },

  onBlur: function(event) {
    // needed to make click events working
    if (event.explicitOriginalTarget != this.pulldownTrigger) {
      setTimeout(this.hide.bind(this), 250);
      this.hasFocus = false;
      this.active = false;
    }
  },

  onChange: function(event) {
    // we use the onchange event to clear the id_field if the autocomplete field has been cleared
    if (this.element.value == "")
      this.id_field.value = ""
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix &&
      /*(Prototype.Browser.IE) &&*/
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '');
      this.iefix = $(this.update.id+'_iefix');
      this.iefix.style.top = this.element.getHeight() + 'px';
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 60);

    setTimeout(this.fixSize.bind(this), 50);
  },

  fixSize: function() {
    if (this.update.offsetWidth < 200)
      this.update.style.width = '200px';

    height = this.update.down('ul').offsetHeight
    if (200 > height && height > 0)
      this.update.style.height = height + 'px';
    else
      this.update.style.height = '200px';
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  getAllChoices: function(event) {
    this.startIndicator();

    parameters = {};
    for (i in this.options.withFormElements) {
      parameters[i] = $F(this.options.withFormElements[i]);
    }
    this.options.parameters = parameters;

    new Ajax.Request(this.url, this.options);

    this.changed = false;
    this.hasFocus = true;
    this.element.focus();
  },

  getMoreChoices: function(event) {
    this.startIndicator();

    options2 = Object.clone(this.options);
    options2.parameters = this.options.defaultParams;

    new Ajax.Request(this.url, options2);

    this.changed = false;
    this.hasFocus = true;
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) { // use override callback (if present)
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';

    id_value = Element.collectTextNodes($(selectedElement).down('span.id'));
    label_value = Element.collectTextNodes($(selectedElement).down('span.label'))

    this.element.value = label_value;

    previous_id_value = this.id_field.value

    this.id_field.value = id_value

    if (previous_id_value != id_value && this.options.onchange) {
      this.options.onchange(id_value);
    }

    this.oldElementValue = this.element.value;
    this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  onComplete: function(request) {
    data = JSON.parse(request.responseText);

    more = null;

    ul = "
"

    data.each(function(entry){
      keys = []
      for (prop in entry)
        keys.push(prop);

      if (keys.length == 1 && typeof(entry[keys[0]]) == 'object')
        entry = entry[keys[0]]

      if (entry['id']) {
        label = entry[this.options.labelAttribute || 'id']

        ul += '
' +
          '' + label + '' +
          '' + entry['id'] + '' +
          '
';
      } else if (entry['more']) {
        more = entry['more'];
      }
    }, this)

    this.more = more;

    if (this.more) {
  		// FIXME: create an LI node for the next URL, then bind to it to
      //       Event.observe(more, 'click', this.getMoreChoices.bindAsEventListener(this));
  		ul += '
More...
';
  	}

    ul += "
"

    this.updateChoices(ul);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
    window.document.body.style.cursor = 'wait'
    this.element.style.cursor = 'wait'
    this.pulldownTrigger.style.cursor = 'wait'
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
    window.document.body.style.cursor = null
    this.element.style.cursor = null
    this.pulldownTrigger.style.cursor = null
  }
});<|endoftext|>


<commit_before>//'use strict';
(function () {
    var pk = {};

    function scope_gen(n) {
        // for normal sudoku latin square, n is 3
        // a latin square has n^4 cells
        var i, j, r, c, gr, gc, l, p;
        var out = [];
        l = n * n * n * n;
        /* malloc from stdlib.h */
        for (i = 0; i < l; i++) {
            var scope = new Array(l);
            r = Math.floor(i / (n * n));
            c = i % (n * n);
            gr = Math.floor(r / n) * n;
            gc = Math.floor(c / n) * n;
            for (j = 0; j < n * n; j++) {
                scope[r * n * n + j] = true;
                scope[j * n * n + c] = true;
                scope[(gr + Math.floor(j / n)) * n * n + gc + j %
                    n] = true;
            }
            scope[i] = false;
            var eye = [];
            for (j = 0; j < l; j++)
                if (scope[j]) {
                    eye.push(j);
                }
            out.push(eye);
        }
        return out;
    }
    //the cell class
    pk.cell = function (i) {
        //cell object constructor
        if (i) {
            if (typeof i === "object") {
                this.v = i.v;
            } else {
                var idea = i - 1;
                if ((idea < 9) && (idea >= 0)) {
                    this.putIdea(idea);
                } else {
                    this.v = 0x7fe7;
                }
            }
        } else {
            this.v = 0x7fe7;
        }
    };
    pk.cell.prototype.putIdea = function (idea) {
        this.v = (idea | pk.open | pk.may_b[idea]);
    };
    pk.cell.prototype.copyIn = function (i) {
        this.v = i.v;
    };
    pk.cell.prototype.txt = function () {
        return this.v.toString();
    };
    pk.cell.prototype.yo = function (mask) {
        return ((this.v & mask) !== 0);
    };
    pk.cell.prototype.reset = function (mask) {
        //reset the mask
        this.v &= ~mask;
    };
    pk.cell.prototype.value = function () {
        //value of an open or filled cell
        return (this.v & pk.data);
    };
    pk.cell.prototype.rm = function (i) {
        // returns success or failure (false or true respectively)
        if (this.yo(pk.may_b[i])) {
            //has it in probable
            if (!this.yo(pk.wait)) {
                return true;
                // it is the only probable!!
            }
            this.reset(pk.may_b[i]);
            this.v -= 1;
            if (this.yo(pk.open)) {
                // only one probable left now
                for (i = 0; i < 9; i += 1) {
                    if (this.yo(pk.may_b[i])) {
                        break;
                    }
                }
                this.putIdea(i);
            }
        }
        return false;
        //removed ok
    };
    pk.cell.prototype.trial = function (i) {
        // returns trial value or >=9 if no trial available
        for (; i < 9; i += 1) {
            if (this.yo(pk.may_b[i])) {
                break;
            }
        }
        return i;
    };
    //the package globals
    pk.wait = 0x20;
    pk.open = 0x10;
    pk.data = 0xf;
    pk.may_b = [
        0x4000, 0x2000, 0x1000,
        0x0800, 0x0400, 0x0200,
        0x0100, 0x0080, 0x0040
    ];
    pk.clr = scope_gen(3);
    //the sud class. models a sudoku
    pk.sud = function (inp) {
        if (inp) {
            if (typeof inp === "object") {
                this.left = inp.left;
                this.i_v = [];
                for (var i = 0; i < 81; i += 1) {
                    this.i_v[i] = new pk.cell(inp.i_v[i]);
                }
                return;
            } else inp = inp.toString()
        } else inp = '123456789'
        var len = inp.length
        this.left = 81
        this.i_v = []
        var i = 0
        for (; i < len && i < 81; i += 1) {
            this.i_v[i] = new pk.cell(inp.charAt(i))
        }
        for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
        arguments.callee.__out__ = []
    }
    pk.sud.prototype.copyIn = function (t) {
        this.left = t.left;
        for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
            i]);
    }
    pk.sud.prototype.first = function () {
        // first waiting cell or >=81; for ordered listing of solutions
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.wait)) {
                break;
            }
        }
        return i
    }
    pk.sud.prototype.idea = function () {
        //first open cell or >=81
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.open)) {
                break
            }
        }
        return i
    }
    pk.sud.prototype.toString = function () {
        var buf = ''
        for (var i = 0; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.cell.open)) {
                buf += '?';
            } else {
                buf += (1 + this.i_v[i].value());
            }
        }
        return buf;
    }
    pk.sud.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) {
                    return -1;
                }
            }
            this.i_v[pos].reset(pk.open)
            if ((this.left -= 1) === 0) {
                this.constructor.__out__.push(this.toString())
                return this.constructor.__out__.length === this.constructor
                    .__n__ ? 2 : 1;
            }
        }
        return 0
    }
    pk.sud.prototype.crook = function () {
        var mc, cc, pos, val = 0
        var copy = new pk.sud(this)
        if ((pos = this.first()) < 81) {
            mc = this.i_v[pos]
            cc = copy.i_v[pos]
        } else return 1
        while ((val = mc.trial(val)) < 9) {
            copy.copyIn(this)
            cc.putIdea(val)
            switch (copy.squash()) {
            case 1:
                val += 1
                break
            case 2:
                return 2
            case -1:
                mc.rm(val) // should i check?
                if (
                        ((pos = this.idea()) < 81)
                        &&
                        (this.i_v[pos].value() > val)
                ) {
                    copy = null
                    return 0
                }
            }
        }
        copy = null
        return 1
    }
    pk.sud.prototype.squash = function () {
        var ret
        do
            if ((ret = this.hook()) !== 0) return ret;
        while (0 === (ret = this.crook())) return ret
    }
    //the list class. subclass of sud.
    //solution lister engine
    //an iterator
    pk.list = function (inp) {
        // calling superclass constructor
        pk.sud.call(this, inp)
        this.status = function (ls, pos, val) {
            this.l = new pk.list(ls)
            this.p = pos
            this.v = val
        }
        if (typeof inp === 'object') return
        pk.nxt = []
        switch (this.squash()) {
        case -1:
            break
        case 2:
        }
    }
    // subclass extends superclass
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
    pk.list.prototype = Object.create(pk.sud.prototype)
    pk.list.prototype.constructor = pk.list
    pk.list.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        if (pk.stata) {
            if (pk.stata.length === 0) {
                delete pk.stata
                return 1
            } else return 0
        }
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
            } // try removing braces
            this.i_v[pos].reset(pk.open)
            if ((this.left -= 1) === 0) {
                pk.nxt.push(this.toString())
                if (pk.nxt.length === pk.n) {
                    pk.stata = []
                    // i hope empty array is true in js
                    return 2
                } else return 1
            }
        }
        return 0
    }
    pk.list.prototype.crook = function () {
        var mc, cc, pos, val = 0,
            copy
        if (pk.stata) {
            copy = pk.stata.pop();
            mc = this.i_v[copy.p];
            cc = copy.l.i_v[copy.p];
        } else {
            if ((pos = this.first()) >= 81) return 1
            else {
                copy = new this.status(this, pos, 0)
                mc = this.i_v[copy.p]
                cc = copy.l.i_v[copy.p]
            }
        }
        while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
            if (!pk.stata) {
                copy.l.copyIn(this);
                cc.putIdea(copy.v);
            }
            switch (copy.l.squash()) {
            case 1:
                copy.v += 1;
                break;
            case 2:
                pk.stata.push(copy);
                return 2;
            case -1:
                mc.rm(copy.v); /* should i check? */
                if (
                    ((pos = this.idea()) < 81) && (this.i_v[pos].value() >
                        copy.v)) return 0
            }
        }
        return 1
    }
    pk.list.prototype.next = function () {
        if (pk.nxt.length === 0) return undefined
        pk.out = pk.nxt
        pk.nxt = []
        this.squash()
        return pk.out
    }
    pk.list.prototype.hasNext = function () {
        return pk.nxt.length !== 0;
    }
    //exports
    module.exports.iter = function (constraints, n) {
        pk.n = n || 2
        return new pk.list(constraints)
    }
    module.exports.list = function (constraints, n) {
        var master = new pk.sud(constraints)
        master.constructor.__n__ = n || 2;
        switch (master.squash()) {
        case -1:
            console.log("no solution")
            break
        case 2:
        }
        return master.constructor.__out__
    }
})();
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
<commit_msg>now works in browser!<commit_after>//'use strict';

//WOAH https://gist.github.com/ryanflorence/1198466
(function (name, definition){
  if (typeof define === 'function'){ // AMD
    define(definition);
  } else if (typeof module !== 'undefined' && module.exports) { // Node.js
    module.exports = definition();
  } else { // Browser
    var theModule = definition(), global = this, old = global[name];
    theModule.noConflict = function () {
      global[name] = old;
      return theModule;
    };
    global[name] = theModule;
  }
})('sud', function () {
    var pk = {};

    function scope_gen(n) {
        // for normal sudoku latin square, n is 3
        // a latin square has n^4 cells
        var i, j, r, c, gr, gc, l, p;
        var out = [];
        l = n * n * n * n;
        /* malloc from stdlib.h */
        for (i = 0; i < l; i++) {
            var scope = new Array(l);
            r = Math.floor(i / (n * n));
            c = i % (n * n);
            gr = Math.floor(r / n) * n;
            gc = Math.floor(c / n) * n;
            for (j = 0; j < n * n; j++) {
                scope[r * n * n + j] = true;
                scope[j * n * n + c] = true;
                scope[(gr + Math.floor(j / n)) * n * n + gc + j %
                    n] = true;
            }
            scope[i] = false;
            var eye = [];
            for (j = 0; j < l; j++)
                if (scope[j]) {
                    eye.push(j);
                }
            out.push(eye);
        }
        return out;
    }
    //the cell class
    pk.cell = function (i) {
        //cell object constructor
        if (i) {
            if (typeof i === "object") {
                this.v = i.v;
            } else {
                var idea = i - 1;
                if ((idea < 9) && (idea >= 0)) {
                    this.putIdea(idea);
                } else {
                    this.v = 0x7fe7;
                }
            }
        } else {
            this.v = 0x7fe7;
        }
    };
    pk.cell.prototype.putIdea = function (idea) {
        this.v = (idea | pk.open | pk.may_b[idea]);
    };
    pk.cell.prototype.copyIn = function (i) {
        this.v = i.v;
    };
    pk.cell.prototype.txt = function () {
        return this.v.toString();
    };
    pk.cell.prototype.yo = function (mask) {
        return ((this.v & mask) !== 0);
    };
    pk.cell.prototype.reset = function (mask) {
        //reset the mask
        this.v &= ~mask;
    };
    pk.cell.prototype.value = function () {
        //value of an open or filled cell
        return (this.v & pk.data);
    };
    pk.cell.prototype.rm = function (i) {
        // returns success or failure (false or true respectively)
        if (this.yo(pk.may_b[i])) {
            //has it in probable
            if (!this.yo(pk.wait)) {
                return true;
                // it is the only probable!!
            }
            this.reset(pk.may_b[i]);
            this.v -= 1;
            if (this.yo(pk.open)) {
                // only one probable left now
                for (i = 0; i < 9; i += 1) {
                    if (this.yo(pk.may_b[i])) {
                        break;
                    }
                }
                this.putIdea(i);
            }
        }
        return false;
        //removed ok
    };
    pk.cell.prototype.trial = function (i) {
        // returns trial value or >=9 if no trial available
        for (; i < 9; i += 1) {
            if (this.yo(pk.may_b[i])) {
                break;
            }
        }
        return i;
    };
    //the package globals
    pk.wait = 0x20;
    pk.open = 0x10;
    pk.data = 0xf;
    pk.may_b = [
        0x4000, 0x2000, 0x1000,
        0x0800, 0x0400, 0x0200,
        0x0100, 0x0080, 0x0040
    ];
    pk.clr = scope_gen(3);
    //the sud class. models a sudoku
    pk.sud = function (inp) {
        if (inp) {
            if (typeof inp === "object") {
                this.left = inp.left;
                this.i_v = [];
                for (var i = 0; i < 81; i += 1) {
                    this.i_v[i] = new pk.cell(inp.i_v[i]);
                }
                return;
            } else inp = inp.toString()
        } else inp = '123456789'
        var len = inp.length
        this.left = 81
        this.i_v = []
        var i = 0
        for (; i < len && i < 81; i += 1) {
            this.i_v[i] = new pk.cell(inp.charAt(i))
        }
        for (; i < 81; i += 1) this.i_v[i] = new pk.cell()
        arguments.callee.__out__ = []
    }
    pk.sud.prototype.copyIn = function (t) {
        this.left = t.left;
        for (var i = 0; i < 81; i += 1) this.i_v[i].copyIn(t.i_v[
            i]);
    }
    pk.sud.prototype.first = function () {
        // first waiting cell or >=81; for ordered listing of solutions
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.wait)) {
                break;
            }
        }
        return i
    }
    pk.sud.prototype.idea = function () {
        //first open cell or >=81
        var i = 0
        for (; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.open)) {
                break
            }
        }
        return i
    }
    pk.sud.prototype.toString = function () {
        var buf = ''
        for (var i = 0; i < 81; i += 1) {
            if (this.i_v[i].yo(pk.cell.open)) {
                buf += '?';
            } else {
                buf += (1 + this.i_v[i].value());
            }
        }
        return buf;
    }
    pk.sud.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) {
                    return -1;
                }
            }
            this.i_v[pos].reset(pk.open)
            if ((this.left -= 1) === 0) {
                this.constructor.__out__.push(this.toString())
                return this.constructor.__out__.length === this.constructor
                    .__n__ ? 2 : 1;
            }
        }
        return 0
    }
    pk.sud.prototype.crook = function () {
        var mc, cc, pos, val = 0
        var copy = new pk.sud(this)
        if ((pos = this.first()) < 81) {
            mc = this.i_v[pos]
            cc = copy.i_v[pos]
        } else return 1
        while ((val = mc.trial(val)) < 9) {
            copy.copyIn(this)
            cc.putIdea(val)
            switch (copy.squash()) {
            case 1:
                val += 1
                break
            case 2:
                return 2
            case -1:
                mc.rm(val) // should i check?
                if (
                        ((pos = this.idea()) < 81)
                        &&
                        (this.i_v[pos].value() > val)
                ) {
                    copy = null
                    return 0
                }
            }
        }
        copy = null
        return 1
    }
    pk.sud.prototype.squash = function () {
        var ret
        do
            if ((ret = this.hook()) !== 0) return ret;
        while (0 === (ret = this.crook())) return ret
    }
    //the list class. subclass of sud.
    //solution lister engine
    //an iterator
    pk.list = function (inp) {
        // calling superclass constructor
        pk.sud.call(this, inp)
        this.status = function (ls, pos, val) {
            this.l = new pk.list(ls)
            this.p = pos
            this.v = val
        }
        if (typeof inp === 'object') return
        pk.nxt = []
        switch (this.squash()) {
        case -1:
            break
        case 2:
        }
    }
    // subclass extends superclass
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
    pk.list.prototype = Object.create(pk.sud.prototype)
    pk.list.prototype.constructor = pk.list
    pk.list.prototype.hook = function () {
        // returns { wrong, stale, solved, dumping } = -1, 0, 1, 2
        var x, pos, val
        if (pk.stata) {
            if (pk.stata.length === 0) {
                delete pk.stata
                return 1
            } else return 0
        }
        while ((pos = this.idea()) < 81) {
            val = this.i_v[pos].value()
            for (x = 0; x < 20; x += 1) {
                if (this.i_v[pk.clr[pos][x]].rm(val)) return -1
            } // try removing braces
            this.i_v[pos].reset(pk.open)
            if ((this.left -= 1) === 0) {
                pk.nxt.push(this.toString())
                if (pk.nxt.length === pk.n) {
                    pk.stata = []
                    // i hope empty array is true in js
                    return 2
                } else return 1
            }
        }
        return 0
    }
    pk.list.prototype.crook = function () {
        var mc, cc, pos, val = 0,
            copy
        if (pk.stata) {
            copy = pk.stata.pop();
            mc = this.i_v[copy.p];
            cc = copy.l.i_v[copy.p];
        } else {
            if ((pos = this.first()) >= 81) return 1
            else {
                copy = new this.status(this, pos, 0)
                mc = this.i_v[copy.p]
                cc = copy.l.i_v[copy.p]
            }
        }
        while (pk.stata || ((copy.v = mc.trial(copy.v)) < 9)) {
            if (!pk.stata) {
                copy.l.copyIn(this);
                cc.putIdea(copy.v);
            }
            switch (copy.l.squash()) {
            case 1:
                copy.v += 1;
                break;
            case 2:
                pk.stata.push(copy);
                return 2;
            case -1:
                mc.rm(copy.v); /* should i check? */
                if (
                    ((pos = this.idea()) < 81) && (this.i_v[pos].value() >
                        copy.v)) return 0
            }
        }
        return 1
    }
    pk.list.prototype.next = function () {
        if (pk.nxt.length === 0) return undefined
        pk.out = pk.nxt
        pk.nxt = []
        this.squash()
        return pk.out
    }
    pk.list.prototype.hasNext = function () {
        return pk.nxt.length !== 0;
    }
    //exports

    var o = {};
    o.iter = function (constraints, n) {
        pk.n = n || 2
        return new pk.list(constraints)
    }
    o.list = function (constraints, n) {
        var master = new pk.sud(constraints)
        master.constructor.__n__ = n || 2;
        switch (master.squash()) {
        case -1:
            console.log("no solution")
            break
        case 2:
        }
        return master.constructor.__out__
    }
    return o;
});
/*
TODO:
change pk.nxt pk.out pk.n pk.stata. /pk\.[^.]* /
change /stat/
for class list
use ed
add semicolons to statements
add braces to loop or if/else bodies
use semver.org and publish to npm
*/
<|endoftext|>


<commit_before>var Showroom = Class.create(Renderer, {

  initialize: function($super, staticCanvas, dynamicCanvas, bufferCanvas) {
    $super(staticCanvas, dynamicCanvas, bufferCanvas);

    this.setSize();

    this.trackID = null;
  },

  destroy: function($super) {
    $super();

    $('showButton').stopObserving();
    $('nextButton').stopObserving();
    $('previousButton').stopObserving();
  },

  quit: function($super) {
    $super();

    $('showroomLikeButton').stopObserving();
    $('showroomFlagButton').stopObserving();
  },

  init: function($super) {

    this.initField();
    this.setSize();
    trackStore.loadNext(currentTrack);
    trackStore.loadPrevious(currentTrack);
    this.setLikeBlameButtons();

    $super();
  },

  onBallExit: function($super) {

    this.field.stopBox2D();

    if (auto) {

      if (trackStore.hasNext(currentTrack)) {

        trackStore.loadTrack(trackStore.next(currentTrack), contentLoader.parseResponse, contentLoader, true);
        return;

      } else {

        contentLoader.loadContent("/tracks/" + currentTrack + "/next", true);

      }

    }

    $super();

  },

  setSize: function() {

    var width = this.field.x + this.field.width + 3,
        height = this.field.y + this.field.height + 3;

    this.width = this.staticCanvas.width = this.dynamicCanvas.width = this.bufferCanvas.width = width;
    this.height = this.staticCanvas.height = this.dynamicCanvas.height = this.bufferCanvas.height = height;

  },

  parseTrack: function(data) {
    this.field.setTrack(data.json);

    if (auto) {
      this.field.startBox2D();
    }
  },

  initializeHTMLInterface: function() {
    var myScope = this;

    $('showButton').observe('click', function(event) {
      myScope.field.startBox2D();
    });

    $('nextButton').observe('click', function(event) {

      if (trackStore.hasNext(currentTrack)) {
        trackStore.loadTrack(trackStore.next(currentTrack), contentLoader.parseResponse, contentLoader, true);
        return;
      }

      contentLoader.loadContent("/tracks/" + currentTrack + "/next");
    });

    $('previousButton').observe('click', function(event) {

      if (trackStore.hasPrevious(currentTrack)) {
        trackStore.loadTrack(trackStore.previous(currentTrack), contentLoader.parseResponse, contentLoader, true);
        return;
      }

      contentLoader.loadContent("/tracks/" + currentTrack + "/previous");
    });

  },

  setLikeBlameButtons: function() {
    var myScope = this;

    if (Cookie.likedTracks.indexOf(this.trackID) === -1) {
      $('showroomLikeButton').observe('click', function() {
        myScope.like();
      });

      $('showroomLikeButton').setStyle({display: "block"});
    } else {

      $('showroomLikeButton').stopObserving();
      $('showroomLikeButton').setStyle({display: "none"});
    }

    if (Cookie.flagedTracks.indexOf(this.trackID) === -1) {
      $('showroomFlagButton').observe('click', function() {
        myScope.flag();
      });

      $('showroomFlag').setStyle({display: "block"});
    } else {
      $('showroomFlagButton').stopObserving();
      $('showroomFlag').setStyle({display: "none"});
    }
  },

  startRender: function($super) {
    $super();

    if (auto) {
      this.field.startBox2D();
    }
  },

  like: function() {

    if (this.trackID) {
      var parameters = {};
      var myScope = this;

      parameters.likes = 1;

      var request = new Ajax.Request('/tracks/' + this.trackID, {
        method: 'put',
        parameters: parameters,
        requestHeaders: {Accept: 'application/json'},

        onSuccess: function(transport) {
          Cookie.likedTracks.push(myScope.trackID);
          Cookie.set('likes', JSON.stringify(Cookie.likedTracks), {maxAge: 60 * 60 * 24 * 365});

          $('tableLikes').update(parseInt($('tableLikes').innerHTML, 10) + 1);

          $('showroomLikeButton').setStyle({display: "none"});
        },

        onFailure: function(transport) {
          $('showroomLikeButton').setStyle({display: "none"});
        }
      });
    }
  },

  flag: function() {
    if (this.trackID) {
      var parameters = {};
      var myScope = this;

      parameters.flags = 1;

      var request = new Ajax.Request('/tracks/' + this.trackID, {
        method: 'put',
        parameters: parameters,
        requestHeaders: {Accept: 'application/json'},

        onSuccess: function(transport) {
          Cookie.flagedTracks.push(myScope.trackID);
          Cookie.set('flags', JSON.stringify(Cookie.flagedTracks), {maxAge: 60 * 60 * 24 * 365});

          $('showroomFlag').setStyle({display: "none"});
        },

        onFailure: function(transport) {
          $('showroomFlag').setStyle({display: "none"});
        }
      });
    }
  }

});<commit_msg>refactoring<commit_after>var Showroom = Class.create(Renderer, {

  initialize: function($super, staticCanvas, dynamicCanvas, bufferCanvas) {
    $super(staticCanvas, dynamicCanvas, bufferCanvas);

    this.setSize();

    this.trackID = null;
  },

  destroy: function($super) {
    $super();

    $('showButton').stopObserving();
    $('nextButton').stopObserving();
    $('previousButton').stopObserving();
  },

  quit: function($super) {
    $super();

    $('showroomLikeButton').stopObserving();
    $('showroomFlagButton').stopObserving();
  },

  init: function($super) {

    this.initField();
    this.setSize();
    trackStore.loadNext(currentTrack);
    trackStore.loadPrevious(currentTrack);
    this.setLikeBlameButtons();

    $super();
  },

  onBallExit: function($super) {

    $super();

    if (auto) {

      if (trackStore.hasNext(currentTrack)) {

        trackStore.loadTrack(trackStore.next(currentTrack), contentLoader.parseResponse, contentLoader, true);

      } else {

        contentLoader.loadContent("/tracks/" + currentTrack + "/next", true);

      }

    }

  },

  setSize: function() {

    var width = this.field.x + this.field.width + 3,
        height = this.field.y + this.field.height + 3;

    this.width = this.staticCanvas.width = this.dynamicCanvas.width = this.bufferCanvas.width = width;
    this.height = this.staticCanvas.height = this.dynamicCanvas.height = this.bufferCanvas.height = height;

  },

  parseTrack: function(data) {
    this.field.setTrack(data.json);

    if (auto) {
      this.field.startBox2D();
    }
  },

  initializeHTMLInterface: function() {
    var myScope = this;

    $('showButton').observe('click', function(event) {
      myScope.field.startBox2D();
    });

    $('nextButton').observe('click', function(event) {

      if (trackStore.hasNext(currentTrack)) {
        trackStore.loadTrack(trackStore.next(currentTrack), contentLoader.parseResponse, contentLoader, true);
        return;
      }

      contentLoader.loadContent("/tracks/" + currentTrack + "/next");
    });

    $('previousButton').observe('click', function(event) {

      if (trackStore.hasPrevious(currentTrack)) {
        trackStore.loadTrack(trackStore.previous(currentTrack), contentLoader.parseResponse, contentLoader, true);
        return;
      }

      contentLoader.loadContent("/tracks/" + currentTrack + "/previous");
    });

  },

  setLikeBlameButtons: function() {
    var myScope = this;

    if (Cookie.likedTracks.indexOf(this.trackID) === -1) {
      $('showroomLikeButton').observe('click', function() {
        myScope.like();
      });

      $('showroomLikeButton').setStyle({display: "block"});
    } else {

      $('showroomLikeButton').stopObserving();
      $('showroomLikeButton').setStyle({display: "none"});
    }

    if (Cookie.flagedTracks.indexOf(this.trackID) === -1) {
      $('showroomFlagButton').observe('click', function() {
        myScope.flag();
      });

      $('showroomFlag').setStyle({display: "block"});
    } else {
      $('showroomFlagButton').stopObserving();
      $('showroomFlag').setStyle({display: "none"});
    }
  },

  startRender: function($super) {
    $super();

    if (auto) {
      this.field.startBox2D();
    }
  },

  like: function() {

    if (this.trackID) {
      var parameters = {};
      var myScope = this;

      parameters.likes = 1;

      var request = new Ajax.Request('/tracks/' + this.trackID, {
        method: 'put',
        parameters: parameters,
        requestHeaders: {Accept: 'application/json'},

        onSuccess: function(transport) {
          Cookie.likedTracks.push(myScope.trackID);
          Cookie.set('likes', JSON.stringify(Cookie.likedTracks), {maxAge: 60 * 60 * 24 * 365});

          $('tableLikes').update(parseInt($('tableLikes').innerHTML, 10) + 1);

          $('showroomLikeButton').setStyle({display: "none"});
        },

        onFailure: function(transport) {
          $('showroomLikeButton').setStyle({display: "none"});
        }
      });
    }
  },

  flag: function() {
    if (this.trackID) {
      var parameters = {};
      var myScope = this;

      parameters.flags = 1;

      var request = new Ajax.Request('/tracks/' + this.trackID, {
        method: 'put',
        parameters: parameters,
        requestHeaders: {Accept: 'application/json'},

        onSuccess: function(transport) {
          Cookie.flagedTracks.push(myScope.trackID);
          Cookie.set('flags', JSON.stringify(Cookie.flagedTracks), {maxAge: 60 * 60 * 24 * 365});

          $('showroomFlag').setStyle({display: "none"});
        },

        onFailure: function(transport) {
          $('showroomFlag').setStyle({display: "none"});
        }
      });
    }
  }

});<|endoftext|>


<commit_before>angular.module('Components', ['reply', 'request', 'formbuilder', 'feedback'])
.directive('openform', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attr) {
            $(element).bind('click', function(e) {
                var widgetkey = $(this).attr('widgetkey');
                createLightboxes();
                s36_openLightbox(448, 600, '/widget/widget_loader/' + widgetkey + "?addfeedback=1");
                $('#s36_modalbox').css({'top': '25%'});
                e.preventDefault();
            });
        }
    }
})
.directive('execItem', function(MessageService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attr) {
          //for deletion
            $(element).bind("click", function(e) {
                var configure = $('.modal-configure');
                var msgid = configure.children('#msgid').val();
                var text  = configure.children('.regular-text').val();
                var msgtype = configure.children('#msgtype').val();

                if(text.length == 0) {
                    alert("This field cannot be blank.");
                } else {
                    if(msgid || msgid.length > 0) {

                        var msg_obj = {'type': msgtype, 'msg': text, 'id': msgid}
                        MessageService.update(msg_obj);

                        var a_msg = $("a#"+msgid);
                        a_msg.attr('req-text', MessageService.editdata.text);
                        a_msg.attr('id', MessageService.editdata.id);
                        a_msg.html(MessageService.editdata.short_text);

                    } else {
                        MessageService.save({'type': msgtype, 'msg': text});

                        if(msgtype == 'msg') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_reply_message();
                        }

                        if(msgtype == 'rqs') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_request_message();
                        }

                    }
                    configure.dialog("close");
                }
            });
        }
    }
})
<commit_msg>ohh my lord<commit_after>angular.module('Components', ['reply', 'request', 'formbuilder', 'feedback'])
.directive('openform', function() {
    return {
        restrict: 'A'
      , link: function(scope, element, attr) {
            $(element).bind('click', function(e) {
                var widgetkey = $(this).attr('widgetkey');
                createLightboxes();
                s36_openLightbox(448, 600, '/widget/widget_loader/' + widgetkey + "?addfeedback=1");
                $('#s36_modalbox').css({'top': '25%'});

                e.preventDefault();
            });
        }
    }
})
.directive('execItem', function(MessageService) {
    return {
        restrict: 'A'
      , link: function(scope, element, attr) {
          //for deletion
            $(element).bind("click", function(e) {
                var configure = $('.modal-configure');
                var msgid = configure.children('#msgid').val();
                var text  = configure.children('.regular-text').val();
                var msgtype = configure.children('#msgtype').val();

                if(text.length == 0) {
                    alert("This field cannot be blank.");
                } else {
                    if(msgid || msgid.length > 0) {

                        var msg_obj = {'type': msgtype, 'msg': text, 'id': msgid}
                        MessageService.update(msg_obj);

                        var a_msg = $("a#"+msgid);
                        a_msg.attr('req-text', MessageService.editdata.text);
                        a_msg.attr('id', MessageService.editdata.id);
                        a_msg.html(MessageService.editdata.short_text);

                    } else {
                        MessageService.save({'type': msgtype, 'msg': text});

                        if(msgtype == 'msg') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_reply_message();
                        }

                        if(msgtype == 'rqs') {
                            MessageService.fetch_messages(msgtype);
                            MessageService.register_request_message();
                        }

                    }
                    configure.dialog("close");
                }
            });
        }
    }
})
<|endoftext|>


<commit_before>// Given a sorted array of integers, find the number of occurrences of a given target value.
// Your algorithm’s runtime complexity must be in the order of O(log n).
// If the target is not found in the array, return 0

// **Example : **
// Given [5, 7, 7, 8, 8, 10] and target value 8,
// return 2.
<commit_msg>add params<commit_after>// Given a sorted array of integers, find the number of occurrences of a given target value.
// Your algorithm’s runtime complexity must be in the order of O(log n).
// If the target is not found in the array, return 0

// **Example : **
// Given [5, 7, 7, 8, 8, 10] and target value 8,
// return 2.

/**
 * @param {array[], number} nums k
 * @return {number}
 */
<|endoftext|>


<commit_before>import { Regular, Component } from 'nek-ui';
import template from '!raw!./index.html';
import ConfigModal from '../config.modal';
import _ from 'lodash';

const DropArea = Component.extend({
  name: 'drop.area',
  template,
  config() {
    this.defaults({
      categoryList: [],                               // 组件列表
      col: 12,                                        // drop区域一行有12格
      rows: [{ subRow: [[]], isContainer: false }],   // 放组件
    });
    this.supr();
  },
  dragOver(event) {
    let data = this.data;
    let moduleId = event.origin.data.moduleId;
    let moudleWidth = event.origin.data.width;
    let dropArea = event.target;
    let dropAreaRect = event.target.getBoundingClientRect();
    let proxy = event.proxy;
    let proxyRect = event.proxy.getBoundingClientRect();
    data.firstCol = this.getDropLattice(dropAreaRect, proxyRect, moudleWidth);
    this.setDropLatticeBorder(data.firstCol, moudleWidth, dropArea);
  },
  dragLeave(event) {
    const dropArea = event.target;
    this.clearBorder(dropArea);
  },
    // row_index 表示放入的行， subRow_index 表示放入的子行
  drop(event, row_index, subRow_index) {
    let data = this.data;
    let moduleName = event.origin.data.name;
    let moudleWidth = event.origin.data.width;
    let dropArea = event.target;
    let subRow = data.rows[row_index].subRow[subRow_index];
    // 移动组件时才有的参数
    let isMoveModule = event.origin.data.isMoveModule;   // 是否为移动组件
    let rowIndex = event.origin.data.rowIndex;           // 组件原先所在行的index
    let subRowIndex = event.origin.data.subRowIndex;     // 组件原先所在子行的index
    let moduleIndex = event.origin.data.moduleIndex;     // 组件原先所在的moduleIndex

    let res = this.getIndexAndOffset(subRow, data.firstCol, moudleWidth, row_index, subRow_index, isMoveModule, rowIndex, subRowIndex, moduleIndex);
    if (moduleName === 'container') {
    // 只有drop行不是container，且为空行才能放置container
      if (!data.rows[row_index].isContainer && data.rows[row_index].subRow.length === 1 && data.rows[row_index].subRow[0].length === 0) {
        data.rows[row_index].isContainer = true;
      }
    } else if (res) {
        // 移动组件
      if (isMoveModule) {
        let module = _.cloneDeep(data.rows[rowIndex].subRow[subRowIndex][moduleIndex]);
        module.firstCol = res.firstCol;
        module.offset = res.offset;
        this.deleteModule(data.rows[rowIndex].subRow[subRowIndex], moduleIndex);
        data.rows[row_index].subRow[subRow_index] = [
          ...subRow.slice(0, res.moduleIndex),
          module,
          ...subRow.slice(res.moduleIndex),
        ];
      } else {
        data.rows[row_index].subRow[subRow_index] = [
          ...subRow.slice(0, res.moduleIndex),
          { name: moduleName, moduleWidth: moudleWidth, offset: res.offset, firstCol: res.firstCol },
          ...subRow.slice(res.moduleIndex),
        ];
      }
    }
    this.clearBorder(dropArea);
  },
  // 计算move过程中，模块左侧所属的格子
  getDropLattice(dropAreaRect, proxyRect, moudleWidth) {
    let data = this.data;
    let dropAreaLeft = dropAreaRect.left;
    let dropAreaWidth = dropAreaRect.width;
    let colWidth = (dropAreaWidth - 2) / 12;
    let proxyLeft = proxyRect.left;
    let firstCol;
    for (let i = 0; i < data.col; i++) {
      if (proxyLeft > ((dropAreaLeft - 1) + (i * colWidth)) && proxyLeft < (dropAreaLeft + ((i + 1) * colWidth))) {
        firstCol = i;
        break;
      }
    }

    // 处理边界情况
    firstCol ? '' : firstCol = 0;
    firstCol + moudleWidth > data.col ? firstCol = data.col - moudleWidth : '';

    return firstCol;
  },
  // 设置模块所属dropArea的格子边框
  setDropLatticeBorder(firstCol, moduleWidth, dropArea) {
    let data = this.data;
    let lines = Array.prototype.slice.call(dropArea.getElementsByClassName('line'));
    this.clearBorder(dropArea);

    for (let i = 0; i < moduleWidth; i++) {
      if (firstCol + i > -1 && firstCol + i < data.col) {
        Regular.dom.addClass(lines[firstCol + i], 'linecolor');
      }
    }
  },
  // 清除所有border
  clearBorder(row) {
    let lines = Array.prototype.slice.call(row.getElementsByClassName('line'));
    lines.forEach((line) => {
      Regular.dom.delClass(line, 'linecolor');
    });
  },
  // 添加一行
  addRow() {
    let data = this.data;
    data.rows.push({ subRow: [[]], isContainer: false });
  },
  // 添加子行
  addSubRow(row) {
    row.subRow.push([]);
  },
  // 计算放下的组件在一行中的位置和offset
  getIndexAndOffset(subRow, firstCol, moduleWidth, dropRowIndex, dropSubRowIndex, isMoveModule, rowIndex, subRowIndex, moduleIndex) {
    let data = this.data;
    let subRowClone = _.cloneDeep(subRow);
    // 是移动组件且是同行内移动
    if (isMoveModule && dropRowIndex === rowIndex && dropSubRowIndex === subRowIndex) {
      subRowClone = this.deleteModule(subRowClone, moduleIndex);
    }

    // 为空行的情况下
    if (subRowClone.length === 0) {
      return { moduleIndex: 0, offset: firstCol, firstCol };
    }

    // 非空行，放在第一个的情况下
    if (firstCol + moduleWidth < subRowClone[0].firstCol + 1) {
      subRow[0].offset = subRow[0].firstCol - firstCol - moduleWidth;
      return { moduleIndex: 0, offset: firstCol, firstCol };
    }

    // 非空行，非第一个的情况下
    for (let i = 0; i < subRowClone.length; i++) {
      let module = subRowClone[i];
      // 没有下一个组件，就算到行尾
      let moduleNext = subRow[i + 1] || { firstCol: data.col };
      let moduleNextClone = subRowClone[i + 1] || { firstCol: data.col };
      if ((module.firstCol + module.moduleWidth) - 1 < firstCol && firstCol + moduleWidth < moduleNextClone.firstCol + 1) {
        subRowClone[i + 1] ? moduleNext.offset = moduleNext.firstCol - firstCol - moduleWidth : '';
        return { moduleIndex: i + 1, offset: firstCol - module.firstCol - module.moduleWidth, firstCol };
      }
    }
    return false;
  },
  deleteModule(subRow, module_index) {
    let module = subRow[module_index];
    let moduleNext = subRow[module_index + 1];
    subRow.splice(module_index, 1);
    if (moduleNext) {
      moduleNext.offset += module.offset + module.moduleWidth;
    }
    return subRow;
  },
  $$NEK(name) {
    let NEK = {};
    this.data.categoryList.forEach((category) => {
      category.componentList.forEach((component) => {
        if (component.name === name) NEK = component;
      });
    });
    return NEK;
  },
  configModule(name, row_index, subRow_index, module_index) {
    let ref = `name_${row_index}_${subRow_index}_${module_index}`;
    let modRef = this.$refs[ref];
    let module = this.data.rows[row_index].subRow[subRow_index][module_index];
    // 首次会把 NEK 数据放到 module 里作持久化，故需先调用组件的 $$NEK() 方法
    module.NEK = module.NEK || this.$$NEK(name);
    new ConfigModal({
      data: {
        modRef,
        conf: module.NEK.conf || [],
      },
    });
  },
  moveRowUp(row_index) {
    let data = this.data;
    let rows = data.rows;
    data.rows = [
      ...rows.slice(0, row_index - 1),
      rows[row_index],
      rows[row_index - 1],
      ...rows.slice(row_index + 1),
    ];
  },
  moveRowDown(row_index) {
    let data = this.data;
    let rows = data.rows;
    data.rows = [
      ...rows.slice(0, row_index),
      rows[row_index + 1],
      rows[row_index],
      ...rows.slice(row_index + 2),
    ];
  },
  deleteRow(row_index) {
    let data = this.data;
    data.rows.splice(row_index, 1);
  },
  trash(event) {
    let data = this.data;
    let isMoveModule = event.origin.data.isMoveModule;
    let rowIndex = event.origin.data.rowIndex;
    let subRowIndex = event.origin.data.subRowIndex;
    let moduleIndex = event.origin.data.moduleIndex;
    if (isMoveModule) {
      this.deleteModule(data.rows[rowIndex][subRowIndex], moduleIndex);
      console.log(data.rows[rowIndex].subRow[subRowIndex]);
    }
  },
  exportJson() {
    let data = this.data;
    let self = this;
    let res = {};
    res.rows = [];

    data.rows.forEach((row, rowIndex) => {
      res.rows.push({
        clazz: '',
        components: [],
      });
      let isContainer = row.isContainer;
      if (!isContainer) {
        row.subRow[0].forEach((module, moduleIndex) => {
          let NEK = module.NEK || self.$$NEK(module.name);
          res.rows[rowIndex].components.push({
            name: NEK.name,
            id: NEK.id,
            clazz: '',
            layout: NEK.layout,
            conf: NEK.conf,
          });
        });
      } else {
        res.rows[rowIndex].components.push({
          name: 'container',
          clazz: '',
          rows: [],
        });
        row.subRow.forEach((subRow, subRowIndex) => {
          res.rows[rowIndex].components[0].rows.push({ clazz: '', components: [] });
          subRow.forEach((module, moduleIndex) => {
            let NEK = module.NEK || self.$$NEK(module.name);
            res.rows[rowIndex].components[0].rows[subRowIndex].components.push({
              name: NEK.name,
              id: NEK.id,
              clazz: '',
              layout: NEK.layout,
              conf: NEK.conf,
            });
          });
        });
      }
    });
    console.log(this.data);
    console.log(res);
    console.log(JSON.stringify(res));
  },
}).filter('uniq', (name, row_index, subRow_index, module_index) => {
  return `name_${row_index}_${subRow_index}_${module_index}`;
});

export default DropArea;
<commit_msg>modify name<commit_after>import { Regular, Component } from 'nek-ui';
import template from '!raw!./index.html';
import ConfigModal from '../config.modal';
import _ from 'lodash';

const DropArea = Component.extend({
  name: 'drop.area',
  template,
  config() {
    this.defaults({
      categoryList: [],                               // 组件列表
      col: 12,                                        // drop区域一行有12格
      rows: [{ subRow: [[]], isContainer: false }],   // 放组件
    });
    this.supr();
  },
  dragOver(event) {
    let data = this.data;
    let moduleId = event.origin.data.moduleId;
    let moduleWidth = event.origin.data.width;
    let dropArea = event.target;
    let dropAreaRect = event.target.getBoundingClientRect();
    let proxy = event.proxy;
    let proxyRect = event.proxy.getBoundingClientRect();
    data.firstCol = this.getDropLattice(dropAreaRect, proxyRect, moduleWidth);
    this.setDropLatticeBorder(data.firstCol, moduleWidth, dropArea);
  },
  dragLeave(event) {
    const dropArea = event.target;
    this.clearBorder(dropArea);
  },
    // row_index 表示放入的行， subRow_index 表示放入的子行
  drop(event, row_index, subRow_index) {
    let data = this.data;
    let moduleName = event.origin.data.name;
    let moduleWidth = event.origin.data.width;
    let dropArea = event.target;
    let subRow = data.rows[row_index].subRow[subRow_index];
    // 移动组件时才有的参数
    let isMoveModule = event.origin.data.isMoveModule;   // 是否为移动组件
    let rowIndex = event.origin.data.rowIndex;           // 组件原先所在行的index
    let subRowIndex = event.origin.data.subRowIndex;     // 组件原先所在子行的index
    let moduleIndex = event.origin.data.moduleIndex;     // 组件原先所在的moduleIndex

    let res = this.getIndexAndOffset(subRow, data.firstCol, moduleWidth, row_index, subRow_index, isMoveModule, rowIndex, subRowIndex, moduleIndex);
    if (moduleName === 'container') {
    // 只有drop行不是container，且为空行才能放置container
      if (!data.rows[row_index].isContainer && data.rows[row_index].subRow.length === 1 && data.rows[row_index].subRow[0].length === 0) {
        data.rows[row_index].isContainer = true;
      }
    } else if (res) {
        // 移动组件
      if (isMoveModule) {
        let module = _.cloneDeep(data.rows[rowIndex].subRow[subRowIndex][moduleIndex]);
        module.firstCol = res.firstCol;
        module.offset = res.offset;
        this.deleteModule(data.rows[rowIndex].subRow[subRowIndex], moduleIndex);
        data.rows[row_index].subRow[subRow_index] = [
          ...subRow.slice(0, res.moduleIndex),
          module,
          ...subRow.slice(res.moduleIndex),
        ];
      } else {
        data.rows[row_index].subRow[subRow_index] = [
          ...subRow.slice(0, res.moduleIndex),
          { name: moduleName, moduleWidth: moduleWidth, offset: res.offset, firstCol: res.firstCol },
          ...subRow.slice(res.moduleIndex),
        ];
      }
    }
    this.clearBorder(dropArea);
  },
  // 计算move过程中，模块左侧所属的格子
  getDropLattice(dropAreaRect, proxyRect, moduleWidth) {
    let data = this.data;
    let dropAreaLeft = dropAreaRect.left;
    let dropAreaWidth = dropAreaRect.width;
    let colWidth = (dropAreaWidth - 2) / 12;
    let proxyLeft = proxyRect.left;
    let firstCol;
    for (let i = 0; i < data.col; i++) {
      if (proxyLeft > ((dropAreaLeft - 1) + (i * colWidth)) && proxyLeft < (dropAreaLeft + ((i + 1) * colWidth))) {
        firstCol = i;
        break;
      }
    }

    // 处理边界情况
    firstCol ? '' : firstCol = 0;
    firstCol + moduleWidth > data.col ? firstCol = data.col - moduleWidth : '';

    return firstCol;
  },
  // 设置模块所属dropArea的格子边框
  setDropLatticeBorder(firstCol, moduleWidth, dropArea) {
    let data = this.data;
    let lines = Array.prototype.slice.call(dropArea.getElementsByClassName('line'));
    this.clearBorder(dropArea);

    for (let i = 0; i < moduleWidth; i++) {
      if (firstCol + i > -1 && firstCol + i < data.col) {
        Regular.dom.addClass(lines[firstCol + i], 'linecolor');
      }
    }
  },
  // 清除所有border
  clearBorder(row) {
    let lines = Array.prototype.slice.call(row.getElementsByClassName('line'));
    lines.forEach((line) => {
      Regular.dom.delClass(line, 'linecolor');
    });
  },
  // 添加一行
  addRow() {
    let data = this.data;
    data.rows.push({ subRow: [[]], isContainer: false });
  },
  // 添加子行
  addSubRow(row) {
    row.subRow.push([]);
  },
  // 计算放下的组件在一行中的位置和offset
  getIndexAndOffset(subRow, firstCol, moduleWidth, dropRowIndex, dropSubRowIndex, isMoveModule, rowIndex, subRowIndex, moduleIndex) {
    let data = this.data;
    let subRowClone = _.cloneDeep(subRow);
    // 是移动组件且是同行内移动
    if (isMoveModule && dropRowIndex === rowIndex && dropSubRowIndex === subRowIndex) {
      subRowClone = this.deleteModule(subRowClone, moduleIndex);
    }

    // 为空行的情况下
    if (subRowClone.length === 0) {
      return { moduleIndex: 0, offset: firstCol, firstCol };
    }

    // 非空行，放在第一个的情况下
    if (firstCol + moduleWidth < subRowClone[0].firstCol + 1) {
      subRow[0].offset = subRow[0].firstCol - firstCol - moduleWidth;
      return { moduleIndex: 0, offset: firstCol, firstCol };
    }

    // 非空行，非第一个的情况下
    for (let i = 0; i < subRowClone.length; i++) {
      let module = subRowClone[i];
      // 没有下一个组件，就算到行尾
      let moduleNext = subRow[i + 1] || { firstCol: data.col };
      let moduleNextClone = subRowClone[i + 1] || { firstCol: data.col };
      if ((module.firstCol + module.moduleWidth) - 1 < firstCol && firstCol + moduleWidth < moduleNextClone.firstCol + 1) {
        subRowClone[i + 1] ? moduleNext.offset = moduleNext.firstCol - firstCol - moduleWidth : '';
        return { moduleIndex: i + 1, offset: firstCol - module.firstCol - module.moduleWidth, firstCol };
      }
    }
    return false;
  },
  deleteModule(subRow, module_index) {
    let module = subRow[module_index];
    let moduleNext = subRow[module_index + 1];
    subRow.splice(module_index, 1);
    if (moduleNext) {
      moduleNext.offset += module.offset + module.moduleWidth;
    }
    return subRow;
  },
  $$NEK(name) {
    let NEK = {};
    this.data.categoryList.forEach((category) => {
      category.componentList.forEach((component) => {
        if (component.name === name) NEK = component;
      });
    });
    return NEK;
  },
  configModule(name, row_index, subRow_index, module_index) {
    let ref = `name_${row_index}_${subRow_index}_${module_index}`;
    let modRef = this.$refs[ref];
    let module = this.data.rows[row_index].subRow[subRow_index][module_index];
    // 首次会把 NEK 数据放到 module 里作持久化，故需先调用组件的 $$NEK() 方法
    module.NEK = module.NEK || this.$$NEK(name);
    new ConfigModal({
      data: {
        modRef,
        conf: module.NEK.conf || [],
      },
    });
  },
  moveRowUp(row_index) {
    let data = this.data;
    let rows = data.rows;
    data.rows = [
      ...rows.slice(0, row_index - 1),
      rows[row_index],
      rows[row_index - 1],
      ...rows.slice(row_index + 1),
    ];
  },
  moveRowDown(row_index) {
    let data = this.data;
    let rows = data.rows;
    data.rows = [
      ...rows.slice(0, row_index),
      rows[row_index + 1],
      rows[row_index],
      ...rows.slice(row_index + 2),
    ];
  },
  deleteRow(row_index) {
    let data = this.data;
    data.rows.splice(row_index, 1);
  },
  trash(event) {
    let data = this.data;
    let isMoveModule = event.origin.data.isMoveModule;
    let rowIndex = event.origin.data.rowIndex;
    let subRowIndex = event.origin.data.subRowIndex;
    let moduleIndex = event.origin.data.moduleIndex;
    if (isMoveModule) {
      this.deleteModule(data.rows[rowIndex][subRowIndex], moduleIndex);
      console.log(data.rows[rowIndex].subRow[subRowIndex]);
    }
  },
  exportJson() {
    let data = this.data;
    let self = this;
    let res = {};
    res.rows = [];

    data.rows.forEach((row, rowIndex) => {
      res.rows.push({
        clazz: '',
        components: [],
      });
      let isContainer = row.isContainer;
      if (!isContainer) {
        row.subRow[0].forEach((module, moduleIndex) => {
          let NEK = module.NEK || self.$$NEK(module.name);
          res.rows[rowIndex].components.push({
            name: NEK.name,
            id: NEK.id,
            clazz: '',
            layout: NEK.layout,
            conf: NEK.conf,
          });
        });
      } else {
        res.rows[rowIndex].components.push({
          name: 'container',
          clazz: '',
          rows: [],
        });
        row.subRow.forEach((subRow, subRowIndex) => {
          res.rows[rowIndex].components[0].rows.push({ clazz: '', components: [] });
          subRow.forEach((module, moduleIndex) => {
            let NEK = module.NEK || self.$$NEK(module.name);
            res.rows[rowIndex].components[0].rows[subRowIndex].components.push({
              name: NEK.name,
              id: NEK.id,
              clazz: '',
              layout: NEK.layout,
              conf: NEK.conf,
            });
          });
        });
      }
    });
    console.log(this.data);
    console.log(res);
    console.log(JSON.stringify(res));
  },
}).filter('uniq', (name, row_index, subRow_index, module_index) => {
  return `name_${row_index}_${subRow_index}_${module_index}`;
});

export default DropArea;
<|endoftext|>


<commit_before>async function(args) {
/*
created_timestamp(-1)
base_component_id("homepage")
is_app(true)
display_name("Homepage app")
description('Homepage app')
load_once_from_file(true)
logo_url("https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/05/Best-Homepages--796x563.jpg")
*/

    var introa = ['homepage_1','todo', 'todo','test','vue','search']
    for (var rt = 0; rt < introa.length; rt++) {
        await load(introa[rt])
    }

    Vue.component('homepage', {

      template: `

Card 1

Text 1

Card 2

Text 2

More text 2

More text 2

Card 3

Text 3

                                    <component :is='item'></component>

{{item.display_name}}

Copy

                            Contact@AppShare.co   +45 2859 5405

Create amazing interactive forms for your website

Build forms in under 5 minutes in Javascript

Embed forms easily into your website

Many templates available to get started easily

Use online or host it in your Enterprise

                                    <form_subscribe_to_appshare/>

Choose a template and create a form now

{{item.display_name}}

Copy

                               Download Appshare for Windows

                               Download Appshare for Mac

                            This website was designed with Appshare

                            On Github:
                            https://github.com/zubairq/appshare

                            Website:
                            AppShare.co

       `
      ,

    data: function() {
        return {
                    apps: [],
                    intro_apps: introa
                }},

      mounted: async function() {

          this.search()
      },
      methods: {
          search: async function() {
               this.apps = await callApp({   driver_name: "systemFunctions3",  method_name:"get_public_apps_list"}, { }) }

      }
    })
}
<commit_msg>Testing with dynamically loading the homepage<commit_after>async function(args) {
/*
created_timestamp(-1)
base_component_id("homepage")
is_app(true)
display_name("Homepage app")
description('Homepage app')
load_once_from_file(true)
logo_url("https://cdn0.tnwcdn.com/wp-content/blogs.dir/1/files/2017/05/Best-Homepages--796x563.jpg")
*/
    var introa = ['homepage_1','todo', 'test','vue','search']

    var mm = null

    Vue.component('homepage', {

      template: `

Card 1

Text 1

Card 2

Text 2

More text 2

More text 2

Card 3

Text 3

                                    <component :is='item'
                                        ></component>

{{item.display_name}}

Copy

                            Contact@AppShare.co   +45 2859 5405

Create amazing interactive forms for your website

Build forms in under 5 minutes in Javascript

Embed forms easily into your website

Many templates available to get started easily

Use online or host it in your Enterprise

                                    <form_subscribe_to_appshare/>

Choose a template and create a form now

{{item.display_name}}

Copy

                               Download Appshare for Windows

                               Download Appshare for Mac

                            This website was designed with Appshare

                            On Github:
                            https://github.com/zubairq/appshare

                            Website:
                            AppShare.co

       `
      ,

    data: function() {
        return {
                    apps: [],
                    intro_apps: introa,
                    loaded_app: new Object(),
                    refresh: 0
                }},

      mounted: async function() {
            mm = this
            for (var rt = 0; rt < 2; rt++) {
                await load(mm.intro_apps[rt])
                mm.loaded_app[mm.intro_apps[rt]] = true
            }

            mm.search()
      },
      methods: {
          search: async function() {
               this.apps = await callApp({   driver_name: "systemFunctions3",  method_name:"get_public_apps_list"}, { }) }

      }
    })
    setTimeout(async function() {
        for (var rt2 = 2; rt2 < mm.intro_apps.length; rt2 ++) {
            var appN = mm.intro_apps[rt2]
            await load(appN)
            mm.loaded_app[appN] = true
            mm.refresh++
        }
    },3000)
}
<|endoftext|>


<commit_before>define(["jquery"], function($) {
	function lazyThumbNailClass(opt){
		this.o = {
			target:".lazyImage", // 대상 이미지 엘리먼트 클래스.
		};
		this.init(opt);
		var This = this;
		$(document).rea2y(function(){
			This.setPreLoader();
			alert("asd");
		});
		$(window).ready(function(){
			setTimeout(function(){
				This.loading();
			},500);
		});
	};
	lazyThumbNailClass.prototype.init = function(opt){
		$.extend(this.o,opt); // 옵션을 통합함.
	};
	lazyThumbNailClass.prototype.setPreLoader = function(){
		var This = this;
		// preloader 환경셋팅
		$(this.o.target).each(function(){
			var ow = $(this).attr("width");
			var oh = $(this).attr("height");
			$(this).css({opacity:0}).wrap("<i class='preloader' />");
			$(this).parent().css({"width":ow+"px","height":oh+"px"});
		});
	};
	lazyThumbNailClass.prototype.loading = function(){
		var This = this;
		$(this.o.target).each(function(){
			$(this).attr("src",$(this).attr("lazy-src"));
			$(this).one("load",function(){
				This.onLoad(this);
			});
			$(this).one("error",function(){
				This.onError(this);
			});
		});
	};
	lazyThumbNailClass.prototype.onLoad = function(obj){
		$(obj).unwrap('<i class="preloader" />').animate({opacity:1});
	};
	lazyThumbNailClass.prototype.onError = function(obj){
		$(obj).hide();
	};
	return lazyThumbNailClass;
});<commit_msg>how to Use 추가.<commit_after>/**
 * // 이미지 pre-loading.
	var lazyThumbNail = new lazyImage({
		target:"img[lazy-src]"
	});
 */

function lazyThumbNailClass(opt){
	this.o = {
		target:".lazyImage", // 대상 이미지 엘리먼트 클래스.
	};
	this.init(opt);
	var This = this;
	$(document).rea2y(function(){
		This.setPreLoader();
		alert("asd");
	});
	$(window).ready(function(){
		setTimeout(function(){
			This.loading();
		},500);
	});
};
lazyThumbNailClass.prototype.init = function(opt){
	$.extend(this.o,opt); // 옵션을 통합함.
};
lazyThumbNailClass.prototype.setPreLoader = function(){
	var This = this;
	// preloader 환경셋팅
	$(this.o.target).each(function(){
		var ow = $(this).attr("width");
		var oh = $(this).attr("height");
		$(this).css({opacity:0}).wrap("<i class='preloader' />");
		$(this).parent().css({"width":ow+"px","height":oh+"px"});
	});
};
lazyThumbNailClass.prototype.loading = function(){
	var This = this;
	$(this.o.target).each(function(){
		$(this).attr("src",$(this).attr("lazy-src"));
		$(this).one("load",function(){
			This.onLoad(this);
		});
		$(this).one("error",function(){
			This.onError(this);
		});
	});
};
lazyThumbNailClass.prototype.onLoad = function(obj){
	$(obj).unwrap('<i class="preloader" />').animate({opacity:1});
};
lazyThumbNailClass.prototype.onError = function(obj){
	$(obj).hide();
};<|endoftext|>


<commit_before>// How to perform preOrder traversal

//     23
//    /  \
//   16   45
//  / \   /  \
// 3 22  37  99

// Preorder traversal:
// 23 16 3 22 45 37 99

function preOrder( node ){
   if( node ){
      console.log( node.value );
      preorder( node.left );
      preorder( node.right );
   }
}
<commit_msg>add note<commit_after>// How to perform preOrder traversal

//     23
//    /  \
//   16   45
//  / \   /  \
// 3 22  37  99

// Preorder traversal:
// 23 16 3 22 45 37 99

function preOrder( node ){
   if( node ){
      console.log( node.value ); // print out current node, then traverse
      preorder( node.left );
      preorder( node.right );
   }
}
<|endoftext|>