<commit_before>lingcod.Manipulator = function(gex, form, render_target, div){

    this.altitude = 100;
    var json = false;
    var data = form.find('.json').html();
    if(data){
        json = JSON.parse(data);
    }
    this.needed = true;
    // Return false if manipulations are not needed, else proceed.
    if(!json || !json.manipulators){
        this.needed = false;
        return false;
    }
    this.div = div;
    this.shape_;
    this.manipulators_ = json.manipulators;
    this.gex_ = gex;
    this.form_ = form;
    this.render_target_ = render_target;
    this.formats_ = new lingcod.Formats();

    // Fill in the form with content from map.html
    this.render_target_.html($('#geopanel').html());

    var self = this;

    // Setup event listeners
    this.render_target_.find('.draw_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.drawNewShape_();
        }
    });

    this.render_target_.find('div.manipulated .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    this.render_target_.find('.done_editing').click(function(){
        self.render_target_.find('.done_editing').addClass('disabled');
        self.finishedEditingCallback_();
    });

    this.render_target_.find('div.edit .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    // Figure out if there is an existing shape in the form, or if a new one
    // needs to be drawn
    if(this.form_.find('#id_geometry_final').val()){
        this.enterExistingShapeState_();
    }else{
        this.enterNewState_();
    }
}

lingcod.Manipulator.prototype.drawNewShape_ = function(){
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = true;
    this.addNewShape_();
    var bounds = this.shape_.getGeometry().getOuterBoundary();
    var self = this;
    this.gex_.edit.drawLineString(bounds, {
        bounce: false,
        finishCallback: function(){
            self.finishedEditingCallback_();
        },
        drawCallback: function(i){
            var coords = bounds.getCoordinates();
            var coord = coords.get(i);
            coord.setAltitude(this.altitude);
            coords.set(i, coord);
        },
        ensureCounterClockwise: false
    });
}

lingcod.Manipulator.prototype.addNewShape_ = function(kml){
    this.clearShape_();
    if(kml){
        this.shape_ = this.gex_.util.displayKmlString(kml);
    }else{
        this.shape_ = this.gex_.dom.addPlacemark({
            visibility: true,
            polygon: [],
            style: {
                line: { width: 2, color: 'ffffffff' },
                poly: { color: '8000ff00' }
            }
        });
    }
    this.shape_.getGeometry().setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
    this.shape_.getGeometry().setExtrude(true);
    var coords = this.shape_.getGeometry().getOuterBoundary().getCoordinates();
    var length = coords.getLength();
    for(var i =0; i<length;i++){
        var coord = coords.get(i)
        coord.setAltitude(this.altitude);
        coords.set(i, coord);
    }
    return this.shape_;
}

lingcod.Manipulator.prototype.finishedEditingCallback_ = function(){
    var orig_wkt = this.formats_.kmlToWkt(this.shape_);
    var self = this;
    this.process(orig_wkt, this.manipulators_, function(data){
        if(data.success === '1'){
            var g = JSON.parse(data.geojson_clipped);
            var kml = self.formats_.geojsonToKmlPlacemark(g);
            var kmlObject = self.addNewShape_(kml);
            // that.finalKmlObject = gex.util.displayKmlString(kml);
            self.gex_.util.flyToObject(kmlObject, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.setGeometryFields_(orig_wkt, self.formats_.geojsonToWkt(g));
            // setGeomFields(wkt, formats.geojsonToWkt(g));
            self.enterManipulatedState_(data.html, true);
        }else{
            self.setGeometryFields_(orig_wkt, '');
            var shape = self.shape_;
            self.addNewShape_(shape.getKml());
            self.gex_.util.flyToObject(self.shape_, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.enterManipulatedState_(data.html, false);
        }
    });
}

lingcod.Manipulator.prototype.setGeometryFields_ = function(original_wkt, final_wkt){
    this.form_.find('#id_geometry_final').val('SRID=4326;'+final_wkt);
    this.form_.find('#id_geometry_orig').val('SRID=4326;'+original_wkt);
}

lingcod.Manipulator.prototype.hideStates_ = function(){
    this.render_target_.find('div.new, div.edit, div.manipulated, div.editing').hide();
}

lingcod.Manipulator.prototype.enterManipulatedState_ = function(html, success){
    this.hideStates_();
    if(success === true){
        this.render_target_.find('div.manipulated').removeClass('error');
        this.is_invalid_geometry = false;
        this.is_defining_shape_ = false;
        this.is_defining_new_shape_ = false;
    }else{
        this.is_invalid_geometry = true;
        this.render_target_.find('div.manipulated').addClass('error');
    }
    this.render_target_.find('div.manipulated a.edit_shape').removeClass('disabled');
    this.render_target_.find('div.manipulated').show().find('>p')
        .html(html);
}

lingcod.Manipulator.prototype.isInvalidGeometry = function(){
    return this.is_invalid_geometry;
}

lingcod.Manipulator.prototype.enterNewState_ = function(){
    this.hideStates_();
    // this.is_defining_shape_ = true;
    this.render_target_.find('div.new').show();
    this.render_target_.find('a.draw_shape').removeClass('disabled');
}

lingcod.Manipulator.prototype.isDefiningNewShape = function(){
    return this.is_defining_new_shape_;
}

lingcod.Manipulator.prototype.enterEditingState_ = function(){
    this.hideStates_();
    this.is_invalid_geometry = false;
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = false;
    this.render_target_.find('.done_editing').removeClass('disabled');
    this.render_target_.find('div.editing').show();
}

lingcod.Manipulator.prototype.enterExistingShapeState_ = function(){
    this.hideStates_();
    this.is_defining_shape = false;
    this.render_target_.find('div.edit .edit_shape').removeClass('disabled');
    this.render_target_.find('div.edit').show();
    var wkt = this.form_.find('#id_geometry_final').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
}

lingcod.Manipulator.prototype.isShapeDefined = function(){
    return !!this.form_.find('#id_geometry_final').val();
}

lingcod.Manipulator.prototype.isDefiningShape = function(){
    return this.is_defining_shape_;
}

lingcod.Manipulator.prototype.process = function(wkt, url, callback){
    $.ajax({
        url: url,
        type: 'POST',
        data: { target_shape: wkt },
        success: function(data, status){
            if(status === 'success'){
                callback(JSON.parse(data));
            }else{
                alert('there was an error processing your shape.');
                $(this).trigger('error', "There was an error processing your shape.");
                callback({success: false, html: $('#manipulators_server_error')});
            }
        },
        error: function(data, status){
            $(this).trigger('error', 'There was an error processing your shape.');
            callback({success: false, html: $('#manipulators_server_error').html()});
        }
    });
}

lingcod.Manipulator.prototype.editExistingShape_ = function(){
    var wkt = this.form_.find('#id_geometry_orig').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    window.shape = this.shape_;
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
    this.gex_.edit.editLineString(this.shape_.getGeometry().getOuterBoundary());
    this.enterEditingState_();

}

lingcod.Manipulator.prototype.clearShape_ = function(){
    if(this.shape_ && this.shape_.getParentNode()){
        this.gex_.edit.endEditLineString(this.shape_.getGeometry().getOuterBoundary());
        gex.dom.removeObject(this.shape_);
        this.shape_ = false;
    }
}

lingcod.Manipulator.prototype.destroy = function(){
    this.clearShape_();
}<commit_msg>fixed altitude setting problem when drawing a new mpa<commit_after>lingcod.Manipulator = function(gex, form, render_target, div){

    this.altitude = 100;
    var json = false;
    var data = form.find('.json').html();
    if(data){
        json = JSON.parse(data);
    }
    this.needed = true;
    // Return false if manipulations are not needed, else proceed.
    if(!json || !json.manipulators){
        this.needed = false;
        return false;
    }
    this.div = div;
    this.shape_;
    this.manipulators_ = json.manipulators;
    this.gex_ = gex;
    this.form_ = form;
    this.render_target_ = render_target;
    this.formats_ = new lingcod.Formats();

    // Fill in the form with content from map.html
    this.render_target_.html($('#geopanel').html());

    var self = this;

    // Setup event listeners
    this.render_target_.find('.draw_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.drawNewShape_();
        }
    });

    this.render_target_.find('div.manipulated .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    this.render_target_.find('.done_editing').click(function(){
        self.render_target_.find('.done_editing').addClass('disabled');
        self.finishedEditingCallback_();
    });

    this.render_target_.find('div.edit .edit_shape').click(function(){
        if(!$(this).hasClass('disabled')){
            $(this).addClass('disabled');
            self.editExistingShape_();
        }
    });

    // Figure out if there is an existing shape in the form, or if a new one
    // needs to be drawn
    if(this.form_.find('#id_geometry_final').val()){
        this.enterExistingShapeState_();
    }else{
        this.enterNewState_();
    }
}

lingcod.Manipulator.prototype.drawNewShape_ = function(){
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = true;
    this.addNewShape_();
    var bounds = this.shape_.getGeometry().getOuterBoundary();
    var self = this;
    this.gex_.edit.drawLineString(bounds, {
        bounce: false,
        finishCallback: function(){
            self.finishedEditingCallback_();
        },
        drawCallback: function(i){
            var coords = bounds.getCoordinates();
            var coord = coords.get(i);
            coord.setAltitude(self.altitude);
            coords.set(i, coord);
        },
        ensureCounterClockwise: false
    });
}

lingcod.Manipulator.prototype.addNewShape_ = function(kml){
    this.clearShape_();
    if(kml){
        this.shape_ = this.gex_.util.displayKmlString(kml);
    }else{
        this.shape_ = this.gex_.dom.addPlacemark({
            visibility: true,
            polygon: [],
            style: {
                line: { width: 2, color: 'ffffffff' },
                poly: { color: '8000ff00' }
            }
        });
    }
    this.shape_.getGeometry().setAltitudeMode(ge.ALTITUDE_ABSOLUTE);
    this.shape_.getGeometry().setExtrude(true);
    var coords = this.shape_.getGeometry().getOuterBoundary().getCoordinates();
    var length = coords.getLength();
    for(var i =0; i<length;i++){
        var coord = coords.get(i)
        coord.setAltitude(this.altitude);
        coords.set(i, coord);
    }
    return this.shape_;
}

lingcod.Manipulator.prototype.finishedEditingCallback_ = function(){
    var orig_wkt = this.formats_.kmlToWkt(this.shape_);
    var self = this;
    this.process(orig_wkt, this.manipulators_, function(data){
        if(data.success === '1'){
            var g = JSON.parse(data.geojson_clipped);
            var kml = self.formats_.geojsonToKmlPlacemark(g);
            var kmlObject = self.addNewShape_(kml);
            // that.finalKmlObject = gex.util.displayKmlString(kml);
            self.gex_.util.flyToObject(kmlObject, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.setGeometryFields_(orig_wkt, self.formats_.geojsonToWkt(g));
            // setGeomFields(wkt, formats.geojsonToWkt(g));
            self.enterManipulatedState_(data.html, true);
        }else{
            self.setGeometryFields_(orig_wkt, '');
            var shape = self.shape_;
            self.addNewShape_(shape.getKml());
            self.gex_.util.flyToObject(self.shape_, {
                boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
            self.enterManipulatedState_(data.html, false);
        }
    });
}

lingcod.Manipulator.prototype.setGeometryFields_ = function(original_wkt, final_wkt){
    this.form_.find('#id_geometry_final').val('SRID=4326;'+final_wkt);
    this.form_.find('#id_geometry_orig').val('SRID=4326;'+original_wkt);
}

lingcod.Manipulator.prototype.hideStates_ = function(){
    this.render_target_.find('div.new, div.edit, div.manipulated, div.editing').hide();
}

lingcod.Manipulator.prototype.enterManipulatedState_ = function(html, success){
    this.hideStates_();
    if(success === true){
        this.render_target_.find('div.manipulated').removeClass('error');
        this.is_invalid_geometry = false;
        this.is_defining_shape_ = false;
        this.is_defining_new_shape_ = false;
    }else{
        this.is_invalid_geometry = true;
        this.render_target_.find('div.manipulated').addClass('error');
    }
    this.render_target_.find('div.manipulated a.edit_shape').removeClass('disabled');
    this.render_target_.find('div.manipulated').show().find('>p')
        .html(html);
}

lingcod.Manipulator.prototype.isInvalidGeometry = function(){
    return this.is_invalid_geometry;
}

lingcod.Manipulator.prototype.enterNewState_ = function(){
    this.hideStates_();
    // this.is_defining_shape_ = true;
    this.render_target_.find('div.new').show();
    this.render_target_.find('a.draw_shape').removeClass('disabled');
}

lingcod.Manipulator.prototype.isDefiningNewShape = function(){
    return this.is_defining_new_shape_;
}

lingcod.Manipulator.prototype.enterEditingState_ = function(){
    this.hideStates_();
    this.is_invalid_geometry = false;
    this.is_defining_shape_ = true;
    this.is_defining_new_shape_ = false;
    this.render_target_.find('.done_editing').removeClass('disabled');
    this.render_target_.find('div.editing').show();
}

lingcod.Manipulator.prototype.enterExistingShapeState_ = function(){
    this.hideStates_();
    this.is_defining_shape = false;
    this.render_target_.find('div.edit .edit_shape').removeClass('disabled');
    this.render_target_.find('div.edit').show();
    var wkt = this.form_.find('#id_geometry_final').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
}

lingcod.Manipulator.prototype.isShapeDefined = function(){
    return !!this.form_.find('#id_geometry_final').val();
}

lingcod.Manipulator.prototype.isDefiningShape = function(){
    return this.is_defining_shape_;
}

lingcod.Manipulator.prototype.process = function(wkt, url, callback){
    $.ajax({
        url: url,
        type: 'POST',
        data: { target_shape: wkt },
        success: function(data, status){
            if(status === 'success'){
                callback(JSON.parse(data));
            }else{
                alert('there was an error processing your shape.');
                $(this).trigger('error', "There was an error processing your shape.");
                callback({success: false, html: $('#manipulators_server_error')});
            }
        },
        error: function(data, status){
            $(this).trigger('error', 'There was an error processing your shape.');
            callback({success: false, html: $('#manipulators_server_error').html()});
        }
    });
}

lingcod.Manipulator.prototype.editExistingShape_ = function(){
    var wkt = this.form_.find('#id_geometry_orig').val();
    var kml = this.formats_.wktPolyToKml(wkt);
    this.addNewShape_(kml);
    window.shape = this.shape_;
    this.gex_.util.flyToObject(this.shape_, {
        boundsFallback: true, aspectRatio: $(this.div).width() / $(this.div).height()});
    this.gex_.edit.editLineString(this.shape_.getGeometry().getOuterBoundary());
    this.enterEditingState_();

}

lingcod.Manipulator.prototype.clearShape_ = function(){
    if(this.shape_ && this.shape_.getParentNode()){
        this.gex_.edit.endEditLineString(this.shape_.getGeometry().getOuterBoundary());
        gex.dom.removeObject(this.shape_);
        this.shape_ = false;
    }
}

lingcod.Manipulator.prototype.destroy = function(){
    this.clearShape_();
}<|endoftext|>


<commit_before>(function($) {
    // MODULE: wok.pollster

    window.wok = window.wok || {
        version: '1.0',
        error: function(msg) { alert("wok error: " + msg); }
    };
    window.wok.pollster = {
        options: {
            // UI part selectors.
            canvasSelector: "#pollster-canvas",
            propertiesSelector: "#pollster-properties",
            templateClass: "survey",
            questionClass: "question"
        }
    };

    // POLLSTER SURVEY

    function PollsterRuntime(context, options) {
        context = context || document;
        options = $.extend({}, window.wok.pollster.options, options);

        var self = this;
        var $survey = $('.'+options.templateClass, context);
        var questionSelector = '.'+options.questionClass;

        var last_partecipation_data = pollster_last_partecipation_data();

        var data_types = {}, rules_by_question = {}, derived_values = {};

        pollster_fill_data_types(data_types);
        pollster_fill_rules(rules_by_question);
        pollster_fill_derived_values(derived_values);

        $survey.find('.open-option-data').attr('disabled', true);
        if (last_partecipation_data && last_partecipation_data.timestamp)
            $('.question-builtin [name=timestamp]').val(last_partecipation_data.timestamp);

        // Bind data types to question elements

        $.each(data_types, function(question, data_type) {
            data_type.bind($('#question-'+question));
        });

        // Event handlers.

        $survey.find("input").change(function(evt, extra) {
            if (evt.target.nodeName !== "INPUT")
                return;

            var $input = $(evt.target);
            var $question = $(evt.target).closest(questionSelector);
            if (!$question.length)
                return true;
            var $option = $input.closest("li");
            var isRadio = $input.is(":radio");
            var isText = $input.is(":text");
            var isHidden = $input.is("[type=hidden]");
            var qid = parseInt($question.attr("id").replace("question-",""));
            var oid = parseInt(($option.attr("id") || '').replace("option-",""));
            var checked = false;
            // some checks are disabled on synthetized 'change' event
            var synthetic = extra && extra.synthetic;

            // If the <input> is a checkbox or radio button determine its checked state.

            if ($input.is(":radio,:checkbox")) {
                checked = $input.is(":checked");
                $question.find('.open-option-data').attr('disabled', function(){
                    return !$(this).closest('li').find(":radio,:checkbox").is(':checked');
                });
            }

            // Else check regular expressions for text entries

            else if ($input.attr('pattern')) {
                var pattern = new RegExp($input.attr('pattern'));
                checked = pattern.test($input.val());
                if (!synthetic)
                    $question.toggleClass("error", !checked);
            }

            // Else just use the string inside the text entry.

            else {
                checked = $input.val() !== "";
                if (!synthetic && $question.is('.mandatory'))
                    $question.toggleClass("error", !checked);
            }

            // Invoke all rules for the rule/option combination.

            var exclusives = [];
            var rules = rules_by_question[qid] || [];
            for (var i=0 ; i < rules.length ; i++) {
                var rule = rules[i];
                if (isRadio) {
                    // checking a radio button must apply rules associated with the uncheck of
                    // all other options
                    jQuery.each(rule.subjectOptions, function(i, o) {
                        var option = $question.find('#option-'+o+' :radio');
                        rule.apply($survey, option.is(':checked'));
                    });
                }
                else if (jQuery.inArray(oid, rule.subjectOptions) >= 0) {
                    // apply rules if the current option is in the subjectOptions set
                    rule.apply($survey, checked);
                }
                else if (isText || isHidden) {
                    // do not check options for text questions
                    rule.apply($survey, checked);
                }
                if (rule.isExclusive)
                    exclusives.push('#option-'+oid);
            }

            if (checked && $.inArray('#option-'+oid, exclusives) >= 0) {
                // uncheck all other options when checking an exclusive one
                var extra = { synthetic: true };
                $question.find(':radio,:checkbox').not($input).filter(':checked').attr('checked', false).trigger('change', extra);
            }
            else if (checked && exclusives) {
                // uncheck all exclusives when checking a non-exclusive option
                var extra = { synthetic: true };
                $question.find(exclusives.join(',')).find(':radio,:checkbox').attr('checked', false).trigger('change', extra);
            }

            // Propagate changes to derived options

            if ($input.is(':not(.derived)')) {
                var val = $input.val();
                var derived = derived_values[qid] || [];
                for (var i=0 ; i < derived.length ; i++) {
                    var $derived_input = $question.find('#option-'+derived[i].option).find(':input');
                    var match = Boolean(derived[i].match(val));
                    var checked = $derived_input.is(':checked');
                    if (match != checked) {
                        var extra = { synthetic: true };
                        $derived_input.attr('checked', match).trigger('change', extra);
                    }
                }
            }
        });

        jQuery.each(rules_by_question, function(i, by_question) {
            jQuery.each(by_question, function(i, rule) {
                rule.init($survey, last_partecipation_data);
            });
        });

        // ensure that the initial status is consistent with rules and whatnot
        var extra = { synthetic: true };
        $survey.find(":input").trigger('change', extra);
    }

    // MODULE FUNCTIONS

    window.wok.pollster.createPollsterRuntime = function(context, options) {
        return new PollsterRuntime(context, options);
    };

})(jQuery);

<commit_msg>Fix exclusive rules in the survey runtime<commit_after>(function($) {
    // MODULE: wok.pollster

    window.wok = window.wok || {
        version: '1.0',
        error: function(msg) { alert("wok error: " + msg); }
    };
    window.wok.pollster = {
        options: {
            // UI part selectors.
            canvasSelector: "#pollster-canvas",
            propertiesSelector: "#pollster-properties",
            templateClass: "survey",
            questionClass: "question"
        }
    };

    // POLLSTER SURVEY

    function PollsterRuntime(context, options) {
        context = context || document;
        options = $.extend({}, window.wok.pollster.options, options);

        var self = this;
        var $survey = $('.'+options.templateClass, context);
        var questionSelector = '.'+options.questionClass;

        var last_partecipation_data = pollster_last_partecipation_data();

        var data_types = {}, rules_by_question = {}, derived_values = {};

        pollster_fill_data_types(data_types);
        pollster_fill_rules(rules_by_question);
        pollster_fill_derived_values(derived_values);

        $survey.find('.open-option-data').attr('disabled', true);
        if (last_partecipation_data && last_partecipation_data.timestamp)
            $('.question-builtin [name=timestamp]').val(last_partecipation_data.timestamp);

        // Bind data types to question elements

        $.each(data_types, function(question, data_type) {
            data_type.bind($('#question-'+question));
        });

        // Event handlers.

        $survey.find("input").change(function(evt, extra) {
            if (evt.target.nodeName !== "INPUT")
                return;

            var $input = $(evt.target);
            var $question = $(evt.target).closest(questionSelector);
            if (!$question.length)
                return true;
            var $option = $input.closest("li");
            var isRadio = $input.is(":radio");
            var isText = $input.is(":text");
            var isHidden = $input.is("[type=hidden]");
            var qid = parseInt($question.attr("id").replace("question-",""));
            var oid = parseInt(($option.attr("id") || '').replace("option-",""));
            var checked = false;
            // some checks are disabled on synthetized 'change' event
            var synthetic = extra && extra.synthetic;

            // If the <input> is a checkbox or radio button determine its checked state.

            if ($input.is(":radio,:checkbox")) {
                checked = $input.is(":checked");
                $question.find('.open-option-data').attr('disabled', function(){
                    return !$(this).closest('li').find(":radio,:checkbox").is(':checked');
                });
            }

            // Else check regular expressions for text entries

            else if ($input.attr('pattern')) {
                var pattern = new RegExp($input.attr('pattern'));
                checked = pattern.test($input.val());
                if (!synthetic)
                    $question.toggleClass("error", !checked);
            }

            // Else just use the string inside the text entry.

            else {
                checked = $input.val() !== "";
                if (!synthetic && $question.is('.mandatory'))
                    $question.toggleClass("error", !checked);
            }

            // Invoke all rules for the rule/option combination.

            var exclusives = [];
            var rules = rules_by_question[qid] || [];
            for (var i=0 ; i < rules.length ; i++) {
                var rule = rules[i];
                if (isRadio) {
                    // checking a radio button must apply rules associated with the uncheck of
                    // all other options
                    jQuery.each(rule.subjectOptions, function(i, o) {
                        var option = $question.find('#option-'+o+' :radio');
                        rule.apply($survey, option.is(':checked'));
                    });
                }
                else if (jQuery.inArray(oid, rule.subjectOptions) >= 0) {
                    // apply rules if the current option is in the subjectOptions set
                    rule.apply($survey, checked);
                }
                else if (isText || isHidden) {
                    // do not check options for text questions
                    rule.apply($survey, checked);
                }
                if (rule.isExclusive) {
                    exclusives = exclusives.concat(jQuery.map(rule.subjectOptions, function(i){ return '#option-'+i;}));
                }
            }

            if (checked && $.inArray('#option-'+oid, exclusives) >= 0) {
                // uncheck all other options when checking an exclusive one
                var extra = { synthetic: true };
                $question.find(':radio,:checkbox').not($input).filter(':checked').attr('checked', false).trigger('change', extra);
            }
            else if (checked && exclusives.length) {
                // uncheck all exclusives when checking a non-exclusive option
                var extra = { synthetic: true };
                $question.find(exclusives.join(',')).find(':radio,:checkbox').attr('checked', false).trigger('change', extra);
            }

            // Propagate changes to derived options

            if ($input.is(':not(.derived)')) {
                var val = $input.val();
                var derived = derived_values[qid] || [];
                for (var i=0 ; i < derived.length ; i++) {
                    var $derived_input = $question.find('#option-'+derived[i].option).find(':input');
                    var match = Boolean(derived[i].match(val));
                    var checked = $derived_input.is(':checked');
                    if (match != checked) {
                        var extra = { synthetic: true };
                        $derived_input.attr('checked', match).trigger('change', extra);
                    }
                }
            }
        });

        jQuery.each(rules_by_question, function(i, by_question) {
            jQuery.each(by_question, function(i, rule) {
                rule.init($survey, last_partecipation_data);
            });
        });

        // ensure that the initial status is consistent with rules and whatnot
        var extra = { synthetic: true };
        $survey.find(":input").trigger('change', extra);
    }

    // MODULE FUNCTIONS

    window.wok.pollster.createPollsterRuntime = function(context, options) {
        return new PollsterRuntime(context, options);
    };

})(jQuery);

<|endoftext|>


<commit_before>
define([
  'jquery',
  'underscore',
  'backbone'
], function ($, _, Backbone) {

  var Entry = Backbone.Model.extend ({

    defaults: {
      content: '',
      rawContent: '',
      creationTime: '',
      modifyTime: '',
      author: '',
    },

    relativeTime: function (time) {
      var current = new Date ();

      var msPerMinute = 60 * 1000;
      var msPerHour = msPerMinute * 60;
      var msPerDay = msPerHour * 24;
      var msPerMonth = msPerDay * 30;
      var msPerYear = msPerDay * 365;

      var elapsed = current - new Date (time) + (2*60*60*1000);

      if (elapsed < msPerMinute) {
        return Math.round (elapsed/1000) + ' saniye';
      }

      else if (elapsed < msPerHour) {
        return Math.round (elapsed/msPerMinute) + ' dakika';
      }

      else if (elapsed < msPerDay ) {
        return Math.round (elapsed/msPerHour ) + ' saat';
      }

      else if (elapsed < msPerMonth) {
        return Math.round (elapsed/msPerDay) + ' gün';
      }

      else if (elapsed < msPerYear) {
        return Math.round (elapsed/msPerMonth) + ' ay';
      }

      else {
        return Math.round (elapsed/msPerYear ) + ' yıl';
      }
    },

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    parseContent: function (content) {

      var that = this;

      var contentObj = $.parseHTML ('
' + content + '
');

      $(contentObj).find ('a').each (function () {

        // EXTERNAL LINKS
        if ($(this).attr ('href').match (/^https?\:\/\//)) {

          var matches = $(this).attr ('href')
                               .match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
          var domain = matches && matches[1];
          domain = domain.replace (/^[^.]+\./g, '');
          $(this).html (' ' +
                        domain);

          // show youtube videos
          var youtube_id = that.parseYoutubeUrl ($(this).attr ('href'));
          if (youtube_id != false) {
            $(this).after ('

');
          }
        }

      });

      return $(contentObj).html ();

    },

    initialize: function () {

      if (!this.has ('htmlDoc'))
        return;

      var htmlDoc = this.get ('htmlDoc');

      this.set ('rawContent', $(htmlDoc).find ('div.content').html ());
      this.set ('content', this.parseContent (this.get ('rawContent')));
      this.set ('creationTime',
                this.relativeTime(
                  $(htmlDoc).find ('time[itemprop="commentTime"]')
                            .attr ('datetime')));
      this.set ('id', $(htmlDoc).find ('footer').attr ('data-id'));
      this.set ('author', $(htmlDoc).find ('address a').text ());

    }

  });

  return Entry;

});
<commit_msg>update relativeTime<commit_after>
define([
  'jquery',
  'underscore',
  'backbone'
], function ($, _, Backbone) {

  var Entry = Backbone.Model.extend ({

    defaults: {
      content: '',
      rawContent: '',
      creationTime: '',
      modifyTime: '',
      author: '',
    },

    relativeTime: function (time) {
      var current = new Date ();

      var msPerMinute = 60 * 1000;
      var msPerHour = msPerMinute * 60;
      var msPerDay = msPerHour * 24;
      var msPerMonth = msPerDay * 30;
      var msPerYear = msPerDay * 365;

      // FIXME: need to check DST
      var elapsed = current - new Date (time) + (3*60*60*1000);

      if (elapsed < msPerMinute) {
        return Math.round (elapsed/1000) + ' saniye';
      }

      else if (elapsed < msPerHour) {
        return Math.round (elapsed/msPerMinute) + ' dakika';
      }

      else if (elapsed < msPerDay ) {
        return Math.round (elapsed/msPerHour ) + ' saat';
      }

      else if (elapsed < msPerMonth) {
        return Math.round (elapsed/msPerDay) + ' gün';
      }

      else if (elapsed < msPerYear) {
        return Math.round (elapsed/msPerMonth) + ' ay';
      }

      else {
        return Math.round (elapsed/msPerYear ) + ' yıl';
      }
    },

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    parseContent: function (content) {

      var that = this;

      var contentObj = $.parseHTML ('
' + content + '
');

      $(contentObj).find ('a').each (function () {

        // EXTERNAL LINKS
        if ($(this).attr ('href').match (/^https?\:\/\//)) {

          var matches = $(this).attr ('href')
                               .match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
          var domain = matches && matches[1];
          domain = domain.replace (/^[^.]+\./g, '');
          $(this).html (' ' +
                        domain);

          // show youtube videos
          var youtube_id = that.parseYoutubeUrl ($(this).attr ('href'));
          if (youtube_id != false) {
            $(this).after ('

');
          }
        }

      });

      return $(contentObj).html ();

    },

    initialize: function () {

      if (!this.has ('htmlDoc'))
        return;

      var htmlDoc = this.get ('htmlDoc');

      this.set ('rawContent', $(htmlDoc).find ('div.content').html ());
      this.set ('content', this.parseContent (this.get ('rawContent')));
      this.set ('creationTime',
                this.relativeTime(
                  $(htmlDoc).find ('time[itemprop="commentTime"]')
                            .attr ('datetime')));
      this.set ('id', $(htmlDoc).find ('footer').attr ('data-id'));
      this.set ('author', $(htmlDoc).find ('address a').text ());

    }

  });

  return Entry;

});
<|endoftext|>


<commit_before>import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware, push, replace } from 'react-router-redux';

import ListsReducer from './screens/List/reducers/main';
import ActiveReducer from './screens/List/reducers/active';

import { loadItems } from './screens/List/actions';

const reducers = combineReducers({
	lists: ListsReducer,
	active: ActiveReducer,
	routing: routerReducer,
});

const store = createStore(
	reducers,
	applyMiddleware(
		thunk,
		routerMiddleware(browserHistory)
	)
);

// Sync the state to the URL parameters. The parameters are:
// - columns: column1,column2,...
// - search: somestring
// - sort: -somestring
// - page: 3
let cachedColumns = '';
let cachedSearch = '';
let cachedSort = '';
let cachedPage = 0;
store.subscribe(() => {
	// Get all the necessary data
	const state = store.getState();
	const list = state.lists.currentList;
	const items = state.lists.items;
	// If we aren't on a list, or haven't loaded any items yet don't do anything
	if (!list || items.count < 1) return;
	const search = state.active.search;
	const location = state.routing.locationBeforeTransitions;

	let columns = state.active.columns;
	let sort = state.active.sort.rawInput;
	let page = state.lists.page.index;

	if (columns) {
		columns = columns.map((column) => column.path);
	}

	// Column handling
	if (Array.isArray(columns)) columns = columns.join(',');
	if (columns === list.defaultColumnPaths) columns = undefined;

	// TODO: Starting or clearing a search pushes a new history state, but updating
	// the current search replaces it for nicer history navigation support

	// Sorting
	if (sort === list.defaultSort) sort = undefined;

	// Pagination
	if (page === 1) page = undefined;

	// If at least one value is different from the cached value, change the query
	// parameter
	// This check is important because updateQueryParams dispatches an action
	// so this would be an endless loop if we didn't check this
	if ((page !== cachedPage)
			|| (columns !== cachedColumns)
			|| (sort !== cachedSort)
			|| (search !== cachedSearch)) {
		// Cache the new values
		cachedPage = page;
		cachedColumns = columns;
		cachedSort = sort;
		cachedSearch = search;
		// Update the query params
		updateQueryParams({
			page,
			columns,
			sort,
			search,
		}, false, location);
		// After we've updated the query params, load the new items
		store.dispatch(loadItems());
	}
});

function updateQueryParams (params, shouldReplace, location) {
	if (!location) return;
	const newParams = Object.assign({}, location.query);
	Object.keys(params).forEach(i => {
		if (params[i]) {
			newParams[i] = params[i];
			if (typeof newParams[i] === 'object') {
				newParams[i] = JSON.stringify(newParams[i]);
			}
		} else {
			delete newParams[i];
		}
	});
	if (shouldReplace) {
		store.dispatch(replace({
			pathname: location.pathname,
			query: newParams,
		}));
	} else {
		store.dispatch(push({
			pathname: location.pathname,
			query: newParams,
		}));
	}
}

export default store;
<commit_msg>Add Redux DevTools extension support<commit_after>import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { browserHistory } from 'react-router';
import { routerReducer, routerMiddleware, push, replace } from 'react-router-redux';

import ListsReducer from './screens/List/reducers/main';
import ActiveReducer from './screens/List/reducers/active';

import { loadItems } from './screens/List/actions';

const reducers = combineReducers({
	lists: ListsReducer,
	active: ActiveReducer,
	routing: routerReducer,
});

const store = createStore(
	reducers,
	compose(
		applyMiddleware(
			thunk,
			routerMiddleware(browserHistory)
		),
		window.devToolsExtension ? window.devToolsExtension() : f => f
	)
);

// Sync the state to the URL parameters. The parameters are:
// - columns: column1,column2,...
// - search: somestring
// - sort: -somestring
// - page: 3
let cachedColumns = '';
let cachedSearch = '';
let cachedSort = '';
let cachedPage = 0;
store.subscribe(() => {
	// Get all the necessary data
	const state = store.getState();
	const list = state.lists.currentList;
	const items = state.lists.items;
	// If we aren't on a list, or haven't loaded any items yet don't do anything
	if (!list || items.count < 1) return;
	const search = state.active.search;
	const location = state.routing.locationBeforeTransitions;

	let columns = state.active.columns;
	let sort = state.active.sort.rawInput;
	let page = state.lists.page.index;

	if (columns) {
		columns = columns.map((column) => column.path);
	}

	// Column handling
	if (Array.isArray(columns)) columns = columns.join(',');
	if (columns === list.defaultColumnPaths) columns = undefined;

	// TODO: Starting or clearing a search pushes a new history state, but updating
	// the current search replaces it for nicer history navigation support

	// Sorting
	if (sort === list.defaultSort) sort = undefined;

	// Pagination
	if (page === 1) page = undefined;

	// If at least one value is different from the cached value, change the query
	// parameter
	// This check is important because updateQueryParams dispatches an action
	// so this would be an endless loop if we didn't check this
	if (page !== cachedPage
		|| columns !== cachedColumns
		|| sort !== cachedSort
		|| search !== cachedSearch) {
		// Cache the new values
		cachedPage = page;
		cachedColumns = columns;
		cachedSort = sort;
		cachedSearch = search;
		// Update the query params
		updateQueryParams({
			page,
			columns,
			sort,
			search,
		}, false, location);
		// After we've updated the query params, load the new items
		store.dispatch(loadItems());
	}
});

function updateQueryParams (params, shouldReplace, location) {
	if (!location) return;
	const newParams = Object.assign({}, location.query);
	Object.keys(params).forEach(i => {
		if (params[i]) {
			newParams[i] = params[i];
			if (typeof newParams[i] === 'object') {
				newParams[i] = JSON.stringify(newParams[i]);
			}
		} else {
			delete newParams[i];
		}
	});
	if (shouldReplace) {
		store.dispatch(replace({
			pathname: location.pathname,
			query: newParams,
		}));
	} else {
		store.dispatch(push({
			pathname: location.pathname,
			query: newParams,
		}));
	}
}

export default store;
<|endoftext|>


<commit_before>import update from "react-addons-update";

class PermissionManager {
  constructor(permissions) {
    if(!permissions) {
      throw "Missing permission hash"
    }

    // Remove the hidden __dataID__ from the permissions object (which comes
    // from Relay)
    this.permissions = update(permissions, {});
    delete this.permissions.__dataID__;
  }

  // Returns true if a specific permission is allowed
  isPermissionAllowed(key) {
    return this.find(key).allowed;
  }

  // Returns true if this permission is the only one that's allowed
  isPermissionOnlyOneAllowed(key) {
    let thisPermissionAllowed = this.find(key).allowed;
    let othersAllowed = false;

    // Check to see if one of the other permissions is allowed
    for(let name in this.permissions) {
      if(name != key && this.find(name).allowed) {
        othersAllowed = true;
      }
    }

    return thisPermissionAllowed && !othersAllowed;
  }

  // Returns true if _any_ of the permissions in the hash are allowed -
  // otherwise returns false.
  areAnyPermissionsAllowed() {
    for(let name in this.permissions) {
      if(this.find(name).allowed) {
        return true
      }
    }

    return false;
  }

  // Returns true if _all of the permissions in the hash are allowed -
  // otherwise returns false.
  areAllPermissionsAllowed() {
    for(let name in this.permissions) {
      if(!this.find(name).allowed) {
        return false
      }
    }

    return true;
  }

  check(config, args) {
    args = args || [];

    if(config.all) {
      if(this.areAllPermissionsAllowed()) return config.render(...args);
    } else if (config.allowed) {
      if(this.isPermissionAllowed(config.allowed)) return config.render(...args);
    } else if (config.any) {
      if(this.areAllPermissionsAllowed()) return config.render(...args);
    } else if (config.only) {
      if(this.isPermissionOnlyOneAllowed(config.only)) return config.render(...args);
    } else {
      throw('Missing permission config attribute. Must be either `all`, `allowed`, `any` or `only`');
    }

    return null;
  }

  // Returns the result of the first permission that's allowed
  first() {
    for(let config of arguments) {
      let result = this.check(config);

      if(result) return config.render();
    }

    return null;
  }

  // Loops through the arguments, and collects the results of each check. The
  // resulting array has all null values removed.
  collect() {
    let results = [];
    for(let idx in arguments) {
      let config = arguments[idx];
      let result = this.check(config, idx);

      if(result) results.push(result);
    }

    return (results.length > 0) ? results : null;
  }

  find(key) {
    let result = this.permissions[key]

    // Ensure sure the permission is even there
    if(!result) {
      throw('Missing permission "' + key + '"', this.permissions);
    }

    // Validate that the 'allowed' key is present
    if(result.allowed == undefined) {
      throw('Missing `allowed` property for "' + key + '" permission');
    }

    return result;
  }
}

export default (permissions) => { return new PermissionManager(permissions) }
<commit_msg>Fixed error throwing in the permissions function<commit_after>import update from "react-addons-update";

class PermissionManager {
  constructor(permissions) {
    if(!permissions) {
      throw new Error("Missing permission hash");
    }

    // Remove the hidden __dataID__ from the permissions object (which comes
    // from Relay)
    this.permissions = update(permissions, {});
    delete this.permissions.__dataID__;
  }

  // Returns true if a specific permission is allowed
  isPermissionAllowed(key) {
    return this.find(key).allowed;
  }

  // Returns true if this permission is the only one that's allowed
  isPermissionOnlyOneAllowed(key) {
    let thisPermissionAllowed = this.find(key).allowed;
    let othersAllowed = false;

    // Check to see if one of the other permissions is allowed
    for(let name in this.permissions) {
      if(name != key && this.find(name).allowed) {
        othersAllowed = true;
      }
    }

    return thisPermissionAllowed && !othersAllowed;
  }

  // Returns true if _any_ of the permissions in the hash are allowed -
  // otherwise returns false.
  areAnyPermissionsAllowed() {
    for(let name in this.permissions) {
      if(this.find(name).allowed) {
        return true
      }
    }

    return false;
  }

  // Returns true if _all of the permissions in the hash are allowed -
  // otherwise returns false.
  areAllPermissionsAllowed() {
    for(let name in this.permissions) {
      if(!this.find(name).allowed) {
        return false
      }
    }

    return true;
  }

  check(config, args) {
    args = args || [];

    if(config.all) {
      if(this.areAllPermissionsAllowed()) return config.render(...args);
    } else if (config.allowed) {
      if(this.isPermissionAllowed(config.allowed)) return config.render(...args);
    } else if (config.any) {
      if(this.areAllPermissionsAllowed()) return config.render(...args);
    } else if (config.only) {
      if(this.isPermissionOnlyOneAllowed(config.only)) return config.render(...args);
    } else {
      throw new Error('Missing permission config attribute. Must be either `all`, `allowed`, `any` or `only`');
    }

    return null;
  }

  // Returns the result of the first permission that's allowed
  first() {
    for(let config of arguments) {
      let result = this.check(config);

      if(result) return config.render();
    }

    return null;
  }

  // Loops through the arguments, and collects the results of each check. The
  // resulting array has all null values removed.
  collect() {
    let results = [];
    for(let idx in arguments) {
      let config = arguments[idx];
      let result = this.check(config, idx);

      if(result) results.push(result);
    }

    return (results.length > 0) ? results : null;
  }

  find(key) {
    let result = this.permissions[key]

    // Ensure sure the permission is even there
    if(!result) {
      throw new Error('Missing permission "' + key + '"', this.permissions);
    }

    // Validate that the 'allowed' key is present
    if(result.allowed == undefined) {
      throw new Error('Missing `allowed` property for "' + key + '" permission');
    }

    return result;
  }
}

export default (permissions) => { return new PermissionManager(permissions) }
<|endoftext|>


<commit_before>import { CarouselCard, Carousel } from './carousel';

export default function init() {
  const projectsContainer = document.getElementsByClassName('projects-container')[0];
  const cardElems = [...projectsContainer.getElementsByClassName('carousel-card')];
  const cards = cardElems.map((c, i) => new CarouselCard(c, i));
  window.workCarousel = new Carousel(cards);
}
<commit_msg>Fix bad argument to CarouselCard construction<commit_after>import { CarouselCard, Carousel } from './carousel';

export default function init() {
  const projectsContainer = document.getElementsByClassName('projects-container')[0];
  const cardElems = [...projectsContainer.getElementsByClassName('carousel-card')];
  const cards = cardElems.map(c => new CarouselCard(c));
  window.workCarousel = new Carousel(cards);
}
<|endoftext|>


<commit_before>'use strict';

const path = require('path');
const execa = require('execa');
const execBuffer = require('exec-buffer');
const isPng = require('is-png');
const isJpg = require('is-jpg');
const isGif = require('is-gif');
const isSvg = require('is-svg');

function optipng(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('optipng-bin'),
    args  : [
      '-i 1',
      '-strip all',
      '-fix',
      '-o7',
      '-force',
      '-out', execBuffer.output,
      execBuffer.input
    ]
  });
}

function pngquant(buffer) {
  return execa.stdout(require('pngquant-bin'), [
    '--speed=1',
    '--force',
    '256'
  ], {
    encoding : null,
    input    : buffer
  });
}

function pngcrush(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('pngcrush-bin'),
    args  : [
      '-rem alla',
      '-rem text',
      '-brute',
      '-reduce',
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function zopflipng(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('zopflipng-bin'),
    args  : [
      '-y',
      '--lossy_8bit',
      '--lossy_transparent',
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function gifsicle(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('gifsicle'),
    args  : [
      '--optimize',
      '--output',
      execBuffer.output,
      execBuffer.input
    ]
  });
}

function jpegRecompress(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('jpeg-recompress-bin'),
    args  : [
      '--strip',
      '--quality', 'medium',
      '--min', 40,
      '--max', 80,
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function jpegoptim(buffer) {
  return execa.stdout(require('jpegoptim-bin'), [
    '--strip-all',
    '--strip-iptc',
    '--strip-icc',
    '--stdin',
	  '--stdout'
  ], {
    encoding : null,
    input    : buffer
  });
}

function mozjpeg(buffer) {
  return execa.stdout(require('mozjpeg'), [
    '-optimize',
    '-progressive'
  ], {
    encoding : null,
    input    : buffer
  });
}

function svgo(buffer, options) {
  let args = [
    '--input', execBuffer.input,
    '--output', execBuffer.output
  ];

  if (options.enable) {
    args.push(`--enable=${options.enable}`);
  }

  if (options.disable) {
    args.push(`--disable=${options.disable}`);
  }

  return execBuffer({
    input : buffer,
    bin   : path.join(__dirname, './node_modules/svgo/bin/svgo'),
    args  : args
  });
}

module.exports = function(buffer, options) {
  if (isJpg(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.jpegRecompress ? jpegRecompress(buffer) : buffer)
      .then(buffer => options.jpegoptim ? jpegoptim(buffer) : buffer)
      .then(buffer => options.mozjpeg ? mozjpeg(buffer) : buffer)
      .catch(error => console.error(error));
  } else if (isPng(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.pngquant ? pngquant(buffer) : buffer)
      .then(buffer => options.optipng ? optipng(buffer) : buffer)
      .then(buffer => options.zopflipng ? zopflipng(buffer) : buffer)
      .catch(error => console.error(error));
  } else if (isGif(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.gifsicle ? gifsicle(buffer) : buffer)
      .catch(error => console.error(error));
  } else if (isSvg(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.svgo ? svgo(buffer, options.svgo) : buffer)
      .catch(error => console.error(error));
  }

  return Promise.resolve(buffer);
};
<commit_msg>Remove needless catching<commit_after>'use strict';

const path = require('path');
const execa = require('execa');
const execBuffer = require('exec-buffer');
const isPng = require('is-png');
const isJpg = require('is-jpg');
const isGif = require('is-gif');
const isSvg = require('is-svg');

function optipng(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('optipng-bin'),
    args  : [
      '-i 1',
      '-strip all',
      '-fix',
      '-o7',
      '-force',
      '-out', execBuffer.output,
      execBuffer.input
    ]
  });
}

function pngquant(buffer) {
  return execa.stdout(require('pngquant-bin'), [
    '--speed=1',
    '--force',
    '256'
  ], {
    encoding : null,
    input    : buffer
  });
}

function pngcrush(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('pngcrush-bin'),
    args  : [
      '-rem alla',
      '-rem text',
      '-brute',
      '-reduce',
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function zopflipng(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('zopflipng-bin'),
    args  : [
      '-y',
      '--lossy_8bit',
      '--lossy_transparent',
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function gifsicle(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('gifsicle'),
    args  : [
      '--optimize',
      '--output',
      execBuffer.output,
      execBuffer.input
    ]
  });
}

function jpegRecompress(buffer) {
  return execBuffer({
    input : buffer,
    bin   : require('jpeg-recompress-bin'),
    args  : [
      '--strip',
      '--quality', 'medium',
      '--min', 40,
      '--max', 80,
      execBuffer.input,
      execBuffer.output
    ]
  });
}

function jpegoptim(buffer) {
  return execa.stdout(require('jpegoptim-bin'), [
    '--strip-all',
    '--strip-iptc',
    '--strip-icc',
    '--stdin',
	  '--stdout'
  ], {
    encoding : null,
    input    : buffer
  });
}

function mozjpeg(buffer) {
  return execa.stdout(require('mozjpeg'), [
    '-optimize',
    '-progressive'
  ], {
    encoding : null,
    input    : buffer
  });
}

function svgo(buffer, options) {
  let args = [
    '--input', execBuffer.input,
    '--output', execBuffer.output
  ];

  if (options.enable) {
    args.push(`--enable=${options.enable}`);
  }

  if (options.disable) {
    args.push(`--disable=${options.disable}`);
  }

  return execBuffer({
    input : buffer,
    bin   : path.join(__dirname, './node_modules/svgo/bin/svgo'),
    args  : args
  });
}

module.exports = function(buffer, options) {
  if (isJpg(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.jpegRecompress ? jpegRecompress(buffer) : buffer)
      .then(buffer => options.jpegoptim ? jpegoptim(buffer) : buffer)
      .then(buffer => options.mozjpeg ? mozjpeg(buffer) : buffer);
  } else if (isPng(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.pngquant ? pngquant(buffer) : buffer)
      .then(buffer => options.optipng ? optipng(buffer) : buffer)
      .then(buffer => options.zopflipng ? zopflipng(buffer) : buffer);
  } else if (isGif(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.gifsicle ? gifsicle(buffer) : buffer);
  } else if (isSvg(buffer)) {
    return Promise.resolve(buffer)
      .then(buffer => options.svgo ? svgo(buffer, options.svgo) : buffer);
  }

  return Promise.resolve(buffer);
};
<|endoftext|>


<commit_before>var groundstation = {};
var Channel = Backbone.Model.extend();

var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();

var Grefs = Backbone.Collection.extend({
  model: Gref
});

groundstation.channels = new Channels();
groundstation.channels.url = '/channels';
groundstation.username = "Anonymous Coward";

groundstation.active_grefs = new Grefs();

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    $(this.el.parentElement.children).removeClass("active");
    $(this.el).addClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.fetch({
      success: function(collection, response, options) {
        $("#gref-container").show();
        _.each(visible_grefs, function(el) { el.remove(); });
        _.each(collection.models, function(gref) {
          visible_grefs.push(new GrefMenuItem({
            model: gref
          }));
        });
      }
    });
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var input, submit;

  input = document.createElement("p");
  input.className = "github-issue-comment";
  input.contentEditable = true;
  input.id = "new-comment-body";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  submit.innerText = "Submit";

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.innerText,
            parents: JSON.stringify([_.last(model.attributes.content).hash]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(input);
  div.appendChild(submit);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    console.log("Rendering new refs");
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];

    _.each(this.$el.children(), function(el) { el.remove(); });
    if (root.protocol.search("richo@psych0tik.net:github:" === 0)) {
      // Github issue
      render_github_issue(content, root, self.el);
    } else {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }
    buildCommentBox(self.el, self.model);
    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<commit_msg>don't show active until the ref loads<commit_after>var groundstation = {};
var Channel = Backbone.Model.extend();

var Channels = Backbone.Collection.extend({
  model: Channel
});

var Gref = Backbone.Model.extend();

var Grefs = Backbone.Collection.extend({
  model: Gref
});

groundstation.channels = new Channels();
groundstation.channels.url = '/channels';
groundstation.username = "Anonymous Coward";

groundstation.active_grefs = new Grefs();

var GrefMenuItem = Backbone.View.extend({
  tagName: "li",
  className: "gref",

  template: '{{identifier}}',

  getUrl: function() {
    return "/gref/" + this.model.attributes["channel"] + "/" + this.model.attributes["identifier"];
  },

  render: function() {
    this.$el.html(this.template.replace("{{identifier}}", this.model.attributes["identifier"]));
    return this;
  },

  select: function() {
    var active_el = this.el;
    $(this.el.parentElement.children).removeClass("active");
    rendered_gref.url = this.getUrl();
    rendered_gref.fetch({
      success: function(model, response, options) {
        $(active_el).addClass("active");
        rendered_gref_content.render();
      }
    });
  },

  events: {
    "click .select":  "select"
  },

  install: function() {
    $('#current-grefs')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }
});

var visible_grefs = [];
var ChannelTab = Backbone.View.extend({

  tagName: "li",

  className: "",

  template: '{{name}}',

  render: function() {
    this.$el.html(this.template.replace("{{name}}", this.model.attributes["name"]));
    return this;
  },

  select: function() {
    var current_grefs = $("#current-grefs")[0];
    groundstation.active_grefs.url = '/grefs/' + this.model.attributes["name"];
    groundstation.active_grefs.fetch({
      success: function(collection, response, options) {
        $("#gref-container").show();
        _.each(visible_grefs, function(el) { el.remove(); });
        _.each(collection.models, function(gref) {
          visible_grefs.push(new GrefMenuItem({
            model: gref
          }));
        });
      }
    });
  },

  events: {
    "click .select":          "select"
  },

  install: function() {
    $('#channels-content')[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.render();
    this.install();
  }

});

function buildCommentBox(div, model) {
  var input, submit;

  input = document.createElement("p");
  input.className = "github-issue-comment";
  input.contentEditable = true;
  input.id = "new-comment-body";

  submit = document.createElement("button");
  submit.className = "btn";
  submit.id = "new-comment-submit";
  submit.innerText = "Submit";

  $(submit).on('click', function(ev) {
    $.ajax({
        type: "POST",
        url: model.url,
        data: {
            body: input.innerText,
            parents: JSON.stringify([_.last(model.attributes.content).hash]),
            user: groundstation.username

        },
        success: function(data, st, xhr) {
            rendered_gref.fetch();
            console.log("Successfully updated groundstation");
        }
    });
    console.log("Sending new comment to groundstation");
  });

  div.appendChild(input);
  div.appendChild(submit);
}

var RenderedGref = Backbone.View.extend({

  tagName: "div",
  className: "",

  render: function() {
    console.log("Rendering new refs");
    var self = this;
    var content = this.model.attributes["content"];
    var root = this.model.attributes["root"];

    _.each(this.$el.children(), function(el) { el.remove(); });
    if (root.protocol.search("richo@psych0tik.net:github:" === 0)) {
      // Github issue
      render_github_issue(content, root, self.el);
    } else {
      console.log("Unhandled protocol: " + root.protocol);
      return this;
    }
    buildCommentBox(self.el, self.model);
    return this;
  },

  install: function() {
    $("#gref-content")[0].appendChild(this.el);
  },

  initialize: function() {
    this.listenTo(this.model, "change", this.render);
    this.install();
  }
});
var rendered_gref = new Gref();
var rendered_gref_content;
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';
import ENUMS from 'irene/enums';
import { translationMacro as t } from 'ember-i18n';

const Analysis = DS.Model.extend({
  findings: DS.attr(),
  risk: DS.attr('number'),
  status: DS.attr('number'),
  owasp: DS.hasMany('owasp'),
  cvssBase: DS.attr('number'),
  pcidss: DS.hasMany('pcidss'),
  cvssVector: DS.attr('string'),
  cvssVersion: DS.attr('number'),
  cvssMetricsHumanized: DS.attr(),
  computedRisk: DS.attr('number'),
  overriddenRisk: DS.attr('number'),
  analiserVersion: DS.attr('number'),
  attachments: DS.hasMany('attachment'),
  vulnerability: DS.belongsTo('vulnerability'),
  file: DS.belongsTo('file', {inverse: 'analyses'}),

  hascvccBase: Ember.computed.equal('cvssVersion', 3),

  tLow: t("low"),
  tNone: t("none"),
  tHigh: t("high"),
  tMedium: t("medium"),
  tCritical: t("critical"),

  isOverriddenRisk: Ember.computed.notEmpty('overriddenRisk'),

  isScanning: ( function() {
    const risk = this.get("computedRisk");
    return risk === ENUMS.RISK.UNKNOWN;
  }).property("computedRisk"),

  hasType(type) {
    const types = this.get("vulnerability.types");
    if (Ember.isEmpty(types)) {
      return false;
    }
    return types.includes(type);
  },

  isRisky: (function() {
    const risk = this.get("computedRisk");
    return ![ENUMS.RISK.NONE, ENUMS.RISK.UNKNOWN].includes(risk);
  }).property("computedRisk"),

  iconClass(risk) {
    switch (risk) {
      case ENUMS.RISK.UNKNOWN: return "fa-spinner fa-spin";
      case ENUMS.RISK.NONE: return "fa-check";
      case ENUMS.RISK.CRITICAL: case ENUMS.RISK.HIGH: case ENUMS.RISK.LOW: case ENUMS.RISK.MEDIUM:  return "fa-warning";
    }
  },

  riskIconClass: (function() {
    return this.iconClass(this.get("risk"));
  }).property("risk"),

  overriddenRiskIconClass: (function() {
    return this.iconClass(this.get("overriddenRisk"));
  }).property("overriddenRisk"),

  riskLabelClass: (function() {
    return this.labelClass(this.get("risk"));
  }).property("risk"),

  overriddenRiskLabelClass: (function() {
    return this.labelClass(this.get("overriddenRisk"));
  }).property("overriddenRisk"),

  labelClass(risk) {
    const cls = 'tag';
    switch (risk) {
      case ENUMS.RISK.UNKNOWN: return `${cls} is-progress`;
      case ENUMS.RISK.NONE: return `${cls} is-success`;
      case ENUMS.RISK.LOW: return `${cls} is-info`;
      case ENUMS.RISK.MEDIUM: return `${cls} is-warning`;
      case ENUMS.RISK.HIGH: return `${cls} is-danger`;
      case ENUMS.RISK.CRITICAL: return `${cls} is-critical`;
    }
  },

  riskText:( function() {
    const tNone = this.get("tNone");
    const tLow = this.get("tLow");
    const tMedium = this.get("tMedium");
    const tHigh = this.get("tHigh");
    const tCritical = this.get("tCritical");

    switch (this.get("risk")) {
      case ENUMS.RISK.NONE: return tNone;
      case ENUMS.RISK.LOW: return tLow;
      case ENUMS.RISK.MEDIUM: return tMedium;
      case ENUMS.RISK.HIGH: return tHigh;
      case ENUMS.RISK.CRITICAL: return tCritical;
    }
  }).property("risk")
});

export default Analysis;
<commit_msg>refactor: remove dead code<commit_after>import Ember from 'ember';
import DS from 'ember-data';
import ENUMS from 'irene/enums';
import { translationMacro as t } from 'ember-i18n';

const Analysis = DS.Model.extend({
  findings: DS.attr(),
  risk: DS.attr('number'),
  status: DS.attr('number'),
  owasp: DS.hasMany('owasp'),
  cvssBase: DS.attr('number'),
  pcidss: DS.hasMany('pcidss'),
  cvssVector: DS.attr('string'),
  cvssVersion: DS.attr('number'),
  cvssMetricsHumanized: DS.attr(),
  computedRisk: DS.attr('number'),
  overriddenRisk: DS.attr('number'),
  analiserVersion: DS.attr('number'),
  attachments: DS.hasMany('attachment'),
  vulnerability: DS.belongsTo('vulnerability'),
  file: DS.belongsTo('file', {inverse: 'analyses'}),

  hascvccBase: Ember.computed.equal('cvssVersion', 3),

  tLow: t("low"),
  tNone: t("none"),
  tHigh: t("high"),
  tMedium: t("medium"),
  tCritical: t("critical"),

  isOverriddenRisk: Ember.computed.notEmpty('overriddenRisk'),

  isScanning: ( function() {
    const risk = this.get("computedRisk");
    return risk === ENUMS.RISK.UNKNOWN;
  }).property("computedRisk"),

  hasType(type) {
    const types = this.get("vulnerability.types");
    if (Ember.isEmpty(types)) {
      return false;
    }
    return types.includes(type);
  },

  isRisky: (function() {
    const risk = this.get("computedRisk");
    return ![ENUMS.RISK.NONE, ENUMS.RISK.UNKNOWN].includes(risk);
  }).property("computedRisk"),

  iconClass(risk) {
    switch (risk) {
      case ENUMS.RISK.UNKNOWN: return "fa-spinner fa-spin";
      case ENUMS.RISK.NONE: return "fa-check";
      case ENUMS.RISK.CRITICAL: case ENUMS.RISK.HIGH: case ENUMS.RISK.LOW: case ENUMS.RISK.MEDIUM:  return "fa-warning";
    }
  },

  riskIconClass: (function() {
    return this.iconClass(this.get("risk"));
  }).property("risk"),

  overriddenRiskIconClass: (function() {
    return this.iconClass(this.get("overriddenRisk"));
  }).property("overriddenRisk"),

  riskLabelClass: (function() {
    return this.labelClass(this.get("risk"));
  }).property("risk"),

  overriddenRiskLabelClass: (function() {
    return this.labelClass(this.get("overriddenRisk"));
  }).property("overriddenRisk"),

  labelClass(risk) {
    const cls = 'tag';
    switch (risk) {
      case ENUMS.RISK.UNKNOWN: return `${cls} is-progress`;
      case ENUMS.RISK.NONE: return `${cls} is-success`;
      case ENUMS.RISK.LOW: return `${cls} is-info`;
      case ENUMS.RISK.MEDIUM: return `${cls} is-warning`;
      case ENUMS.RISK.HIGH: return `${cls} is-danger`;
      case ENUMS.RISK.CRITICAL: return `${cls} is-critical`;
    }
  }
});

export default Analysis;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TextInput,
  TouchableNativeFeedback,
  Image,
  TouchableOpacity,
} from 'react-native';

//import TabNavigator from 'react-native-tab-navigator';
//import Communications from 'react-native-communications';

class EditClub extends Component {
    constructor(props){
        super(props);
        this.state = {
            hasData: false,
            data: [],
            newVal: '',
            currentVal:'',
            newValues : []

        };
    }
    render() {
        var TouchableElement = TouchableNativeFeedback;
        var officer = true; // figure this out later
        //var vals = ['Secondary Advisor Department','Meeting Location','Vice President Email','President Email','Parent Organization','Meeting Times','Advisor Email','Vice President Name','Advisor Phone','Organization Email','Secretary Name','Advisor Department','Seceretary Email','Primary Contact','Meeting Day','Secondary Advisor Name and Title','url','Advisor Name and Title','Secondary Advisor Phone','Summary','Treasurer Email','Secondary Advisor Email','Main Summary','About Summary','Name', 'President Name'];
        //image

        var data = this.state.data;

        // var clubValue = () => {

        //    var returnValue = [];

        //   // something wierd is going on with the text input
        //    data.map(club=> {
        //        for (let prop in club){
        //             if (prop==="id" || prop === "events" || prop==="posts" || prop==="img"){
        //                 continue;
        //             }

        //             this.setState({currentVal : club[prop]});
        //             if (Array.isArray(val)){

        //                 // this should be changed? whats in the arrays?
        //                 this.setState({currentVal:club[prop][0]});

        //             }

        //             returnValue.push(<View><Text style={styles.welcome}>{prop}:</Text>

                        // <TextInput
                        //     style = {styles.textEdit}
                        //     value = {this.state.curentVal}
                        //     onChangeText = {(newValue)=>{this.setState({stuff: newValue});}}

                        // ></TextInput>

        //                 </View>);
        //           // club[prop] = this.state.newVal;
        //        }

        //     })
        //     return returnValue;

        // }

        var clubValue= ()=>{

           var returnValue = [];
           this.state.newValues;
            //onChangeText={(text)=>{this.state.newValues[i]=text}}
            //this.state.newValue.push(club[prop]);
           data.map(club=> {
               var i = 0;
               this.state.newValues;
               for (let prop in club){

                    this.setState(this.state.newValues);
                    if (prop==="id" || prop === "events" || prop==="posts" || prop==="img"){
                        continue;
                    }

                    returnValue.push(
                        <View>
                            <Text style={styles.welcome}>
                                {prop}:
                            </Text>
                            <TextInput
                                style = {styles.textEdit}
                                value = {club[prop]}>

                            </TextInput>
                        </View>);
                    i++;
               }

            }, this) // end of map

          return returnValue;

        }

        return (
        <ScrollView style = {{marginTop: 30, paddingBottom: 30}}>

            {clubValue()}
            <Text>{this.props.route.clubName}</Text>
            <TouchableElement style = {styles.button} onPress = {()=>{alert(this.state.newValues[0])}}>

                <View><Text>Submit</Text></View>
            </TouchableElement>
            <TouchableElement style = {styles.button} onPress = {()=>this._onGoClub()}>
                <View><Text>Back</Text></View>
            </TouchableElement>

        </ScrollView>

        );

    }
        // Jonathan's component code
    componentDidMount() {
        const url = "http://skeleton20161103012840.azurewebsites.net/api/organizations/name?name="+
                this.props.route.clubName.replace(" ","+");
        fetch(url)
            .then(res=>res.json())
            .then(json => {
                this.setState({
                    hasData: true,
                    data: json
                })
            })
            .catch(e => {
                console.error(e);
                //TODO: figure out how to navigate back out if something went wrong
            })
        }

    _onGoClub() {
        this.props.navigator.push({
            type: 'club',
            index: this.props.route.index+1,
            state: this.props.route.state,
        })
    }

}

   module.exports = EditClub;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    //justifyContent: 'center',
    //alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
  //  textAlign: 'center',
    margin: 10,
  },
  instructions: {
    //textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  button: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  profilepic: {
      height: 100,
      width: 100

  },
  pad: {
      justifyContent: 'center',
      alignItems: 'center',

  },
  message: {
      borderWidth: 1,
  },
  edit: {
      height: 25,
      width: 25,

  },
  textEdit: {
    marginLeft: 20,
    height: 40,
    width: 200,
    borderColor: 'grey',
    backgroundColor: 'white',
    borderWidth: 1
  },
  box: {

      flexDirection: 'row',
      flexWrap: 'wrap'

  },
  longBox: {
      height: 125

  },
  boxSpace:{
    //   flexDirection: 'row',
    //   flexWrap: 'wrap',
      paddingTop: 20,
      paddingLeft: 20
  }
});
<commit_msg>Fix up ead26c152a685acc4eb28aa244a5ecc53c0acd2a<commit_after>import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView,
  TextInput,
  TouchableNativeFeedback,
  Image,
  TouchableOpacity,
} from 'react-native';

//import TabNavigator from 'react-native-tab-navigator';
//import Communications from 'react-native-communications';

class EditClub extends Component {
    constructor(props){
        super(props);
        this.state = {
            hasData: false,
            data: [],
            newVal: '',
            currentVal:'',
            newValues : '',
            //newValues : {hi:0},
            //hasValues:false

        };
        //this.setState({hasValues:false});
    }
    render() {
        var TouchableElement = TouchableNativeFeedback;
        var officer = true; // figure this out later
        //var vals = ['Secondary Advisor Department','Meeting Location','Vice President Email','President Email','Parent Organization','Meeting Times','Advisor Email','Vice President Name','Advisor Phone','Organization Email','Secretary Name','Advisor Department','Seceretary Email','Primary Contact','Meeting Day','Secondary Advisor Name and Title','url','Advisor Name and Title','Secondary Advisor Phone','Summary','Treasurer Email','Secondary Advisor Email','Main Summary','About Summary','Name', 'President Name'];
        //image

        var data = this.state.data;
        var ho = this.state.hasData;
        //this.setState({hasData:false});

        var yo = this;

        if (this.state.hasData){
            this.setState({hasData:false});
            this.setState({newValues:{}});
        }

        function hey(boo){
            if (boo in this.state.newValues){
            //if (ho){
                //yo.setState({hasData: false});
                // this.setState(newValues: 'hey');
                //this.state.newValues;
                //return this.state.newValues[club[prop]];
                return "blah2";
            }
            else{
                return "blah";
            }
         }

        var clubValue= ()=>{

            var returnValue = [];
            //this.state.newValues;
                //onChangeText={(text)=>{this.state.newValues[i]=text}}
                //this.state.newValue.push(club[prop]);
            data.map(club=> {
                var i = 0;

                for (let prop in club){
                        //this.state.newValues;

                        if (prop==="id" || prop === "events" || prop==="posts" || prop==="img"){
                            continue;
                        }

                        returnValue.push(
                            <View>
                                <Text style={styles.welcome}>
                                    {prop}:
                                </Text>
                                <TextInput
                                    style = {styles.textEdit}
                                    onChangeText={(newText)=>{
                                        //this.state.newValues[club[prop]] = newText;
                                        this.setState({newValues[club[prop]]:this.state.newValues});
                                        }
                                    }
                                    value = {hey(club[prop])}
                                     >

                                </TextInput>
                            </View>);
                        i++;                }

                }, this) // end of map
            return returnValue;

        }

        return (
        <ScrollView style = {{marginTop: 30, paddingBottom: 30}}>

            {clubValue()}
            <Text>{this.state.newValues[0]}</Text>
            <TouchableElement style = {styles.button} onPress = {()=>{alert(blah[1])}}>
                <View><Text>Submit</Text></View>
            </TouchableElement>
            <TouchableElement style = {styles.button} onPress = {()=>this._onGoClub()}>
                <View><Text>Back</Text></View>
            </TouchableElement>

        </ScrollView>

        );

    }
        // Jonathan's component code
    componentDidMount() {
        const url = "http://skeleton20161103012840.azurewebsites.net/api/organizations/name?name="+
                this.props.route.clubName.replace(" ","+");
        fetch(url)
            .then(res=>res.json())
            .then(json => {
                this.setState({
                    hasData: true,
                    data: json
                })
            })
            .catch(e => {
                console.error(e);
                //TODO: figure out how to navigate back out if something went wrong
            })
        }

    _onGoClub() {
        this.props.navigator.push({
            type: 'club',
            index: this.props.route.index+1,
            state: this.props.route.state,
        })
    }

}

   module.exports = EditClub;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    //justifyContent: 'center',
    //alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
  //  textAlign: 'center',
    margin: 10,
  },
  instructions: {
    //textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  button: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  profilepic: {
      height: 100,
      width: 100

  },
  pad: {
      justifyContent: 'center',
      alignItems: 'center',

  },
  message: {
      borderWidth: 1,
  },
  edit: {
      height: 25,
      width: 25,

  },
  textEdit: {
    marginLeft: 20,
    height: 40,
    width: 200,
    borderColor: 'grey',
    backgroundColor: 'white',
    borderWidth: 1
  },
  box: {

      flexDirection: 'row',
      flexWrap: 'wrap'

  },
  longBox: {
      height: 125

  },
  boxSpace:{
    //   flexDirection: 'row',
    //   flexWrap: 'wrap',
      paddingTop: 20,
      paddingLeft: 20
  }
});
<|endoftext|>


<commit_before>import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany, belongsTo } from 'ember-data/relationships';
import { computed } from '@ember/object';
import Ember from 'ember';

export default Model.extend({
    intl: Ember.inject.service(),

    titulo: computed('id',function(){
      return this.intl.t(`model.chapters.${this.id}.title`);
    }),

    grupos: hasMany('grupo'),
    libro: belongsTo('libro')
});
<commit_msg>Fix jshint<commit_after>import Model from 'ember-data/model';
import { hasMany, belongsTo } from 'ember-data/relationships';
import { computed } from '@ember/object';
import Ember from 'ember';

export default Model.extend({
    intl: Ember.inject.service(),

    titulo: computed('id',function(){
      return this.intl.t(`model.chapters.${this.id}.title`);
    }),

    grupos: hasMany('grupo'),
    libro: belongsTo('libro')
});
<|endoftext|>


<commit_before>'use strict';

var memoize     = require('memoizee/plain')
  , validDbType = require('dbjs/valid-dbjs-type')
  , isDbjsType  = require('dbjs/is-dbjs-type')
  , defineDocument = require('../document')
  , defineSubmission  = require('../submission');

module.exports = memoize(function (Target/* options */) {
	var db, options, name, Submission, Document, Doc;
	validDbType(Target);
	db = Target.database;
	options = Object(arguments[1]);
	Submission = defineSubmission(db);
	Document = defineDocument(db);
	Target.prototype.defineProperties({
		submissions: {
			type: db.Object,
			nested: true
		}
	});

	if (options.classes) {
		options.classes.forEach(function (param) {
			if (isDbjsType(param)) {
				Doc = param;
				name = Doc.__id__[0].toLowerCase() + Doc.__id__.slice(1);
			} else {
				name = param.name;
				Doc  = param.Document;
			}
			if (Object.getPrototypeOf(Doc) !== Document) {
				throw new Error("Class: " + Doc.__id__ + " must extend Document.");
			}
			Target.prototype.submissions.define(name, {
				type: Submission,
				nested: true
			});
			Target.prototype.submissions[name].getOwnDescriptor('document').type = Doc;
			Target.prototype.submissions[name].document.setProperties({
				uniqueKey: function () {
					return this.owner.key;
				},
				label: function (_observe) {
					var requirement = this.master.requirements[this.owner.key];
					if (requirement && requirement.label) return _observe(requirement._label);
					return this.constructor.label;
				},
				legend: function (_observe) {
					var requirement = this.master.requirements[this.owner.key];
					if (requirement && requirement.legend) return _observe(requirement._legend);
					return this.constructor.label;
				}
			});
		});
	}

	return Target;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<commit_msg>#607 made label and legend safe in submissions setup<commit_after>'use strict';

var memoize     = require('memoizee/plain')
  , validDbType = require('dbjs/valid-dbjs-type')
  , isDbjsType  = require('dbjs/is-dbjs-type')
  , defineDocument = require('../document')
  , defineSubmission  = require('../submission');

module.exports = memoize(function (Target/* options */) {
	var db, options, name, Submission, Document, Doc;
	validDbType(Target);
	db = Target.database;
	options = Object(arguments[1]);
	Submission = defineSubmission(db);
	Document = defineDocument(db);
	Target.prototype.defineProperties({
		submissions: {
			type: db.Object,
			nested: true
		}
	});

	if (options.classes) {
		options.classes.forEach(function (param) {
			if (isDbjsType(param)) {
				Doc = param;
				name = Doc.__id__[0].toLowerCase() + Doc.__id__.slice(1);
			} else {
				name = param.name;
				Doc  = param.Document;
			}
			if (Object.getPrototypeOf(Doc) !== Document) {
				throw new Error("Class: " + Doc.__id__ + " must extend Document.");
			}
			Target.prototype.submissions.define(name, {
				type: Submission,
				nested: true
			});
			Target.prototype.submissions[name].getOwnDescriptor('document').type = Doc;
			Target.prototype.submissions[name].document.setProperties({
				uniqueKey: function () {
					return this.owner.key;
				},
				label: function (_observe) {
					var requirement;
					//this.master may not have requirements (i.e CompanyRepresentative)
					if (this.master.requirements) {
						requirement = this.master.requirements[this.owner.key];
					}
					if (requirement && requirement.label) return _observe(requirement._label);
					return this.constructor.label;
				},
				legend: function (_observe) {
					var requirement;
					//this.master may not have requirements (i.e CompanyRepresentative)
					if (this.master.requirements) {
						requirement = this.master.requirements[this.owner.key];
					}
					if (requirement && requirement.legend) return _observe(requirement._legend);
					return this.constructor.label;
				}
			});
		});
	}

	return Target;
}, { normalizer: require('memoizee/normalizers/get-1')() });
<|endoftext|>