问:
Uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator
I am facing the following issue:

ActionController::RoutingError (uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator):

  app/controllers/spree/api/aramex_address_controller.rb:2:in <class:AramexAddressController>

  app/controllers/spree/api/aramex_address_controller.rb:1:in <top (required)>

I included the following in my controllers/spree/api/aramex_address_controller.rb:

```<code>class Spree::Api::AramexAddressController < ApplicationController
  include AramexAddressValidator

  # fetch cities from aramex api
  def fetch_cities_from_aramex_address
    response = []
    zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
    if zones.map(&:countries).flatten.map(&:iso).include?(params['country_code'])
      response = JSON.parse(fetch_cities(params['country_code']))['Cities']
    end
    respond_to do |format|
      format.json { render :json => response, :status => 200 }
    end
  end

  # Validate address for aramex shipping
  def validate_address_with_aramex
    begin
      zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
      final_response = {}
      if zones.map(&:countries).flatten.map(&:iso).include?(params[:b_country])
        final_response[:b_errors] = confirm_address_validity(params[:b_city], params[:b_zipcode], params[:b_country])
      end
      if zones.map(&:countries).flatten.map(&:iso).include?(params[:s_country]) && params[:use_bill_address] == "false"
        final_response[:s_errors] = confirm_address_validity(params[:s_city], params[:s_zipcode], params[:s_country])
      end
    rescue
      return true
    end
    respond_to do |format|
      format.json { render :json => final_response, :status => 200 }
    end
  end

  # Confirm address validity with Aramex address validatio API
  def confirm_address_validity(city, zipcode, country)
    response = JSON.parse(validate_address(city, zipcode, country))
    if response['HasErrors'] == true
      if response['SuggestedAddresses'].present?
        response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + response['SuggestedAddresses'].map{|data| data['City']}.join(', ')
      else
        if response['Notifications'].first['Code'] == 'ERR06'
          response['Notifications'].map{|data| data['Message']}.join(', ')
        else
          cities_response = JSON.parse(fetch_cities(country, city[0..2]))
          cities_response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + cities_response['Cities'].join(' ,')
        end
      end
    end
  end
end
</code>```

In my route file I mentioned:

```<code>get 'validate_address_with_aramex', to: 'aramex_address#validate_address_with_aramex'
get 'fetch_cities_from_aramex_address', to: 'aramex_address#fetch_cities_from_aramex_address'
</code>```

I included the following JS call for the submitted Aramex Ajax validation in assets/javascripts/spree/frontend/checkout/address.js:

```<code>Spree.ready(function($) {
    Spree.onAddress = function() {
        var call_aramex = true;
        $("#checkout_form_address").on('submit', function(e) {
            if ($('#checkout_form_address').valid()) {
                var s_country = $("#order_ship_address_attributes_country_id").find('option:selected').attr('iso_code');
                var s_zipcode = $("#order_ship_address_attributes_zipcode").val();
                var s_city = $("#order_ship_address_attributes_city").val();
                var b_country = $("#order_bill_address_attributes_country_id").find('option:selected').attr('iso_code');
                var b_zipcode = $("#order_bill_address_attributes_zipcode").val();
                var b_city = $("#order_bill_address_attributes_city").val();
                if (call_aramex == true && (typeof aramex_countries !== 'undefined') && (aramex_countries.includes(b_country) || aramex_countries.includes(s_country))) {
                    e.preventDefault();
                    var error_id = $('#errorExplanation').is(':visible') ? '#errorExplanation' : '#manual_error'
                    $(error_id).html("").hide()
                    $.blockUI({
                        message: '<img src="/assets/ajax-loader.gif" />'
                    });
                    $.ajax({
                        url: "/api/validate_address_with_aramex",
                        type: 'GET',
                        dataType: "json",
                        data: {
                            s_country: s_country,
                            s_zipcode: s_zipcode,
                            s_city: s_city,
                            b_country: b_country,
                            b_zipcode: b_zipcode,
                            b_city: b_city,
                            use_bill_address: ($("#order_use_billing").is(":checked"))
                        },
                        success: function(result) {
                            $.unblockUI()
                            if (result.b_errors || result.s_errors) {
                                if (result.b_errors) {
                                    $(error_id).append('<div>Billing Address ' + result.b_errors + ' </div>')
                                }
                                if (result.s_errors) {
                                    $(error_id).append('<div>Shipping Address ' + result.s_errors + ' </div>')
                                }
                                if ((result.b_errors && !result.s_errors) && ($("#order_use_billing").is(":unchecked"))) {
                                    $(".js-summary-edit").trigger("click")
                                }
                                $(error_id).show();
                                $('html, body').animate({
                                    scrollTop: '0px'
                                }, 300);
                            } else {
                                call_aramex = false;
                                $('#checkout_form_address').submit()
                            }
                        },
                        error: function(xhr, status, error) {
                            $(error_id).append('Oops Something Went Wrong but you can process order')
                            $(error_id).show();
                            $.unblockUI()
                            $('html, body').animate({
                                scrollTop: '0px'
                            }, 300);
                            $('#checkout_form_address').submit()
                        }
                    });
                }
            }
        })

        var getCountryId, order_use_billing, update_shipping_form_state;
        if (($('#checkout_form_address')).is('*')) {
            ($('#checkout_form_address')).validate({
                rules: {
                    "order[bill_address_attributes][city]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 22)
                        }
                    },
                    "order[bill_address_attributes][firstname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 15)
                        }
                    },
                    "order[bill_address_attributes][lastname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 17)
                        }
                    },
                    "order[bill_address_attributes][address1]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[bill_address_attributes][address2]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[bill_address_attributes][zipcode]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 10)
                        }
                    },
                    "order[ship_address_attributes][city]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 22)
                        }
                    },
                    "order[ship_address_attributes][firstname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 15)
                        }
                    },
                    "order[ship_address_attributes][lastname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 17)
                        }
                    },
                    "order[ship_address_attributes][address1]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[ship_address_attributes][address2]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[ship_address_attributes][zipcode]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 10)
                        }
                    }
                }
            });
            getCountryId = function(region) {
                return $('#' + region + 'country select').val();
            };

            isCountryUsOrCa = function(country_id) {
                return ["38", "232"].includes(country_id)
            }

            maxCharLimit = function(country_id, limit) {
                if (["38", "232"].includes(country_id)) {
                    return limit;
                } else {
                    return 255;
                }
            };

            Spree.updateState = function(region) {
                var countryId;
                var cityId
                countryId = getCountryId(region);
                if (countryId != null) {
                    if (region == 'b') {
                        cityId = '#order_bill_address_attributes_city'
                        countryInputId = "#order_bill_address_attributes_country_id"
                    } else {
                        cityId = '#order_ship_address_attributes_city'
                        countryInputId = "#order_ship_address_attributes_country_id"
                    }
                    fill_cities($(countryInputId).find('option:selected').attr('iso_code'), cityId)
                    if (Spree.Checkout[countryId] == null) {
                        return $.get(Spree.routes.states_search, {
                            country_id: countryId
                        }, function(data) {
                            Spree.Checkout[countryId] = {
                                states: data.states,
                                states_required: data.states_required
                            };
                            return Spree.fillStates(Spree.Checkout[countryId], region);
                        });
                    } else {
                        return Spree.fillStates(Spree.Checkout[countryId], region);
                    }
                }
            };

            fill_cities = function(country_code, cityId) {
                $.ajax({
                    url: "/api/fetch_cities_from_aramex_address",
                    type: 'GET',
                    dataType: "json",
                    data: {
                        country_code: country_code
                    },
                    success: function(data) {
                        $(cityId).autocomplete({
                            source: data,
                        });
                    },
                    error: function() {}
                });
            }

            Spree.fillStates = function(data, region) {
                var selected, stateInput, statePara, stateSelect, stateSpanRequired, states, statesRequired, statesWithBlank;
                statesRequired = data.states_required;
                states = data.states;
                statePara = $('#' + region + 'state');
                stateSelect = statePara.find('select');
                stateInput = statePara.find('input');
                stateSpanRequired = statePara.find('[id$="state-required"]');
                if (states.length > 0) {
                    selected = parseInt(stateSelect.val());
                    stateSelect.html('');
                    statesWithBlank = [{
                        name: '',
                        id: ''
                    }].concat(states);
                    $.each(statesWithBlank, function(idx, state) {
                        var opt;
                        opt = ($(document.createElement('option'))).attr('value', state.id).html(state.name);
                        if (selected === state.id) {
                            opt.prop('selected', true);
                        }
                        return stateSelect.append(opt);
                    });
                    stateSelect.prop('disabled', false).show();
                    stateInput.hide().prop('disabled', true);
                    statePara.show();
                    stateSpanRequired.show();
                    if (statesRequired) {
                        stateSelect.addClass('required');
                    }
                    stateSelect.removeClass('hidden');
                    return stateInput.removeClass('required');
                } else {
                    stateSelect.hide().prop('disabled', true);
                    stateInput.show();
                    if (statesRequired) {
                        stateSpanRequired.show();
                        stateInput.addClass('required');
                    } else {
                        stateInput.val('');
                        stateSpanRequired.hide();
                        stateInput.removeClass('required');
                    }
                    statePara.toggle(!!statesRequired);
                    stateInput.prop('disabled', !statesRequired);
                    stateInput.removeClass('hidden');
                    return stateSelect.removeClass('required');
                }
            };
            ($('#bcountry select')).change(function() {
                $('label.error').hide()
                if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
                    $('#checkout_form_address').valid();
                }
                return Spree.updateState('b');
            });
            ($('#scountry select')).change(function() {
                $('label.error').hide()
                if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
                    $('#checkout_form_address').valid();
                }
                return Spree.updateState('s');
            });
            Spree.updateState('b');
            order_use_billing = $('input#order_use_billing');
            order_use_billing.change(function() {
                return update_shipping_form_state(order_use_billing);
            });
            update_shipping_form_state = function(order_use_billing) {
                if (order_use_billing.is(':checked')) {
                    ($('#shipping .inner')).hide();
                    return ($('#shipping .inner input, #shipping .inner select')).prop('disabled', true);
                } else {
                    ($('#shipping .inner')).show();
                    ($('#shipping .inner input, #shipping .inner select')).prop('disabled', false);
                    return Spree.updateState('s');
                }
            };
            return update_shipping_form_state(order_use_billing);
        }
    };
    return Spree.onAddress();
});
</code>```

Why am I am facing the issue mentioned at the top?

答:
well here is the issue of constant lookup. Your constant that is AramexAddressValidator is missing because of the way you wrote class Spree::Api::AramexAddressController < ApplicationController

So if your module AramexAddressValidator is inside some scope use that scope also while including this module
For Ex. if its inside spree/aramex_address_validator use
include Spree::AramexAddressValidator

Body:
I am facing the following issue:

ActionController::RoutingError (uninitialized constant Spree::Api::AramexAddressController::AramexAddressValidator):

  app/controllers/spree/api/aramex_address_controller.rb:2:in <class:AramexAddressController>

  app/controllers/spree/api/aramex_address_controller.rb:1:in <top (required)>

I included the following in my controllers/spree/api/aramex_address_controller.rb:

class Spree::Api::AramexAddressController < ApplicationController
  include AramexAddressValidator

  # fetch cities from aramex api
  def fetch_cities_from_aramex_address
    response = []
    zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
    if zones.map(&:countries).flatten.map(&:iso).include?(params['country_code'])
      response = JSON.parse(fetch_cities(params['country_code']))['Cities']
    end
    respond_to do |format|
      format.json { render :json => response, :status => 200 }
    end
  end

  # Validate address for aramex shipping
  def validate_address_with_aramex
    begin
      zones = Spree::ShippingMethod.where(['LOWER(admin_name) like ?', '%aramex%']).map(&:zones).flatten
      final_response = {}
      if zones.map(&:countries).flatten.map(&:iso).include?(params[:b_country])
        final_response[:b_errors] = confirm_address_validity(params[:b_city], params[:b_zipcode], params[:b_country])
      end
      if zones.map(&:countries).flatten.map(&:iso).include?(params[:s_country]) && params[:use_bill_address] == "false"
        final_response[:s_errors] = confirm_address_validity(params[:s_city], params[:s_zipcode], params[:s_country])
      end
    rescue
      return true
    end
    respond_to do |format|
      format.json { render :json => final_response, :status => 200 }
    end
  end

  # Confirm address validity with Aramex address validatio API
  def confirm_address_validity(city, zipcode, country)
    response = JSON.parse(validate_address(city, zipcode, country))
    if response['HasErrors'] == true
      if response['SuggestedAddresses'].present?
        response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + response['SuggestedAddresses'].map{|data| data['City']}.join(', ')
      else
        if response['Notifications'].first['Code'] == 'ERR06'
          response['Notifications'].map{|data| data['Message']}.join(', ')
        else
          cities_response = JSON.parse(fetch_cities(country, city[0..2]))
          cities_response['Notifications'].map{|data| data['Message']}.join(', ') + ', Suggested city name is - ' + cities_response['Cities'].join(' ,')
        end
      end
    end
  end
end

In my route file I mentioned:

get 'validate_address_with_aramex', to: 'aramex_address#validate_address_with_aramex'
get 'fetch_cities_from_aramex_address', to: 'aramex_address#fetch_cities_from_aramex_address'

I included the following JS call for the submitted Aramex Ajax validation in assets/javascripts/spree/frontend/checkout/address.js:

Spree.ready(function($) {
    Spree.onAddress = function() {
        var call_aramex = true;
        $("#checkout_form_address").on('submit', function(e) {
            if ($('#checkout_form_address').valid()) {
                var s_country = $("#order_ship_address_attributes_country_id").find('option:selected').attr('iso_code');
                var s_zipcode = $("#order_ship_address_attributes_zipcode").val();
                var s_city = $("#order_ship_address_attributes_city").val();
                var b_country = $("#order_bill_address_attributes_country_id").find('option:selected').attr('iso_code');
                var b_zipcode = $("#order_bill_address_attributes_zipcode").val();
                var b_city = $("#order_bill_address_attributes_city").val();
                if (call_aramex == true && (typeof aramex_countries !== 'undefined') && (aramex_countries.includes(b_country) || aramex_countries.includes(s_country))) {
                    e.preventDefault();
                    var error_id = $('#errorExplanation').is(':visible') ? '#errorExplanation' : '#manual_error'
                    $(error_id).html("").hide()
                    $.blockUI({
                        message: ''
                    });
                    $.ajax({
                        url: "/api/validate_address_with_aramex",
                        type: 'GET',
                        dataType: "json",
                        data: {
                            s_country: s_country,
                            s_zipcode: s_zipcode,
                            s_city: s_city,
                            b_country: b_country,
                            b_zipcode: b_zipcode,
                            b_city: b_city,
                            use_bill_address: ($("#order_use_billing").is(":checked"))
                        },
                        success: function(result) {
                            $.unblockUI()
                            if (result.b_errors || result.s_errors) {
                                if (result.b_errors) {
                                    $(error_id).append('
Billing Address ' + result.b_errors + '
')
                                }
                                if (result.s_errors) {
                                    $(error_id).append('
Shipping Address ' + result.s_errors + '
')
                                }
                                if ((result.b_errors && !result.s_errors) && ($("#order_use_billing").is(":unchecked"))) {
                                    $(".js-summary-edit").trigger("click")
                                }
                                $(error_id).show();
                                $('html, body').animate({
                                    scrollTop: '0px'
                                }, 300);
                            } else {
                                call_aramex = false;
                                $('#checkout_form_address').submit()
                            }
                        },
                        error: function(xhr, status, error) {
                            $(error_id).append('Oops Something Went Wrong but you can process order')
                            $(error_id).show();
                            $.unblockUI()
                            $('html, body').animate({
                                scrollTop: '0px'
                            }, 300);
                            $('#checkout_form_address').submit()
                        }
                    });
                }
            }
        })

        var getCountryId, order_use_billing, update_shipping_form_state;
        if (($('#checkout_form_address')).is('*')) {
            ($('#checkout_form_address')).validate({
                rules: {
                    "order[bill_address_attributes][city]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 22)
                        }
                    },
                    "order[bill_address_attributes][firstname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 15)
                        }
                    },
                    "order[bill_address_attributes][lastname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 17)
                        }
                    },
                    "order[bill_address_attributes][address1]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[bill_address_attributes][address2]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[bill_address_attributes][zipcode]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_bill_address_attributes_country_id").val(), 10)
                        }
                    },
                    "order[ship_address_attributes][city]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 22)
                        }
                    },
                    "order[ship_address_attributes][firstname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 15)
                        }
                    },
                    "order[ship_address_attributes][lastname]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 17)
                        }
                    },
                    "order[ship_address_attributes][address1]": {
                        required: true,
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[ship_address_attributes][address2]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 32)
                        }
                    },
                    "order[ship_address_attributes][zipcode]": {
                        maxlength: function(element) {
                            return maxCharLimit($("#order_ship_address_attributes_country_id").val(), 10)
                        }
                    }
                }
            });
            getCountryId = function(region) {
                return $('#' + region + 'country select').val();
            };

            isCountryUsOrCa = function(country_id) {
                return ["38", "232"].includes(country_id)
            }

            maxCharLimit = function(country_id, limit) {
                if (["38", "232"].includes(country_id)) {
                    return limit;
                } else {
                    return 255;
                }
            };

            Spree.updateState = function(region) {
                var countryId;
                var cityId
                countryId = getCountryId(region);
                if (countryId != null) {
                    if (region == 'b') {
                        cityId = '#order_bill_address_attributes_city'
                        countryInputId = "#order_bill_address_attributes_country_id"
                    } else {
                        cityId = '#order_ship_address_attributes_city'
                        countryInputId = "#order_ship_address_attributes_country_id"
                    }
                    fill_cities($(countryInputId).find('option:selected').attr('iso_code'), cityId)
                    if (Spree.Checkout[countryId] == null) {
                        return $.get(Spree.routes.states_search, {
                            country_id: countryId
                        }, function(data) {
                            Spree.Checkout[countryId] = {
                                states: data.states,
                                states_required: data.states_required
                            };
                            return Spree.fillStates(Spree.Checkout[countryId], region);
                        });
                    } else {
                        return Spree.fillStates(Spree.Checkout[countryId], region);
                    }
                }
            };

            fill_cities = function(country_code, cityId) {
                $.ajax({
                    url: "/api/fetch_cities_from_aramex_address",
                    type: 'GET',
                    dataType: "json",
                    data: {
                        country_code: country_code
                    },
                    success: function(data) {
                        $(cityId).autocomplete({
                            source: data,
                        });
                    },
                    error: function() {}
                });
            }

            Spree.fillStates = function(data, region) {
                var selected, stateInput, statePara, stateSelect, stateSpanRequired, states, statesRequired, statesWithBlank;
                statesRequired = data.states_required;
                states = data.states;
                statePara = $('#' + region + 'state');
                stateSelect = statePara.find('select');
                stateInput = statePara.find('input');
                stateSpanRequired = statePara.find('[id$="state-required"]');
                if (states.length > 0) {
                    selected = parseInt(stateSelect.val());
                    stateSelect.html('');
                    statesWithBlank = [{
                        name: '',
                        id: ''
                    }].concat(states);
                    $.each(statesWithBlank, function(idx, state) {
                        var opt;
                        opt = ($(document.createElement('option'))).attr('value', state.id).html(state.name);
                        if (selected === state.id) {
                            opt.prop('selected', true);
                        }
                        return stateSelect.append(opt);
                    });
                    stateSelect.prop('disabled', false).show();
                    stateInput.hide().prop('disabled', true);
                    statePara.show();
                    stateSpanRequired.show();
                    if (statesRequired) {
                        stateSelect.addClass('required');
                    }
                    stateSelect.removeClass('hidden');
                    return stateInput.removeClass('required');
                } else {
                    stateSelect.hide().prop('disabled', true);
                    stateInput.show();
                    if (statesRequired) {
                        stateSpanRequired.show();
                        stateInput.addClass('required');
                    } else {
                        stateInput.val('');
                        stateSpanRequired.hide();
                        stateInput.removeClass('required');
                    }
                    statePara.toggle(!!statesRequired);
                    stateInput.prop('disabled', !statesRequired);
                    stateInput.removeClass('hidden');
                    return stateSelect.removeClass('required');
                }
            };
            ($('#bcountry select')).change(function() {
                $('label.error').hide()
                if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
                    $('#checkout_form_address').valid();
                }
                return Spree.updateState('b');
            });
            ($('#scountry select')).change(function() {
                $('label.error').hide()
                if (isCountryUsOrCa($("#order_bill_address_attributes_country_id").val())) {
                    $('#checkout_form_address').valid();
                }
                return Spree.updateState('s');
            });
            Spree.updateState('b');
            order_use_billing = $('input#order_use_billing');
            order_use_billing.change(function() {
                return update_shipping_form_state(order_use_billing);
            });
            update_shipping_form_state = function(order_use_billing) {
                if (order_use_billing.is(':checked')) {
                    ($('#shipping .inner')).hide();
                    return ($('#shipping .inner input, #shipping .inner select')).prop('disabled', true);
                } else {
                    ($('#shipping .inner')).show();
                    ($('#shipping .inner input, #shipping .inner select')).prop('disabled', false);
                    return Spree.updateState('s');
                }
            };
            return update_shipping_form_state(order_use_billing);
        }
    };
    return Spree.onAddress();
});

Why am I am facing the issue mentioned at the top?


来源: stackexchange

问:
PHP accented characters in POST submit
I have a HTML form on submit.php, the page is encoded as UTF-8 (using a meta tag), when the form is submitted to process.php (via POST), some of the variables are stored in the session, and the page uses Header: Location to go back to submit.php, which then uses the session variables to redisplay some of the entered information.

If I enter an accented character, for example é (&eacute), when the page returns to submit.php, it does not render the character correctly, I get an ã (&atilde) and an © (&copy) instead.

Where should I be looking to solve this problem? I'm assuming it's server side, as the rendered page is always UTF-8 (the browser confirms the page is UTF-8 before and after submitting)

Solution:

The string was being passed through htmlentities() at one point, which it turns out has a default character encoding of ISO-8859-1 The answer was to simply specify 'UTF-8' in the function call.

答:
é being turned into ~© is a sure-fire sign that the 2-byte UTF-8 character at some point gets interpreted in a 1-byte character set (most likely ISO-8859-1).

You need to find where this happens, and fix it.

Maybe show some code - maybe somebody has an idea.

ContentLicense: CC BY-SA 3.0

Title: PHP accented characters in POST submit

ContentLicense: CC BY-SA 2.5


问:
Quick Sort Array Random Number Generator Nothing Printed Error
I have this C code that creates an array with 100 random numbers and I want to sort it using quick sort, but it always gives a Segmentation fault error.

Here is the code:

```<code>#define MAX 100
int a[MAX];
void quick_sort(double *x, int l, int r) {
    int l1, r1;

    if (l < r) {
        l1 = l;
        r1 = r;

        do {
            while (l1 < r && x[l1 - 1] <= x[l - 1]) {
                l1++;
            }
            while (l < r1 && x[r1 - 1] >= x[l - 1]) {
                r1--;
            }
            if (l1 < r1) {
                swap(&x[l1 - l], &x[r1 - 1]);
            }
        } while (l1 < r1);

        swap(&x[l - 1], &x[r1 - 1]);
        quick_sort(x, l, r1 - 1);
        quick_sort(x, r1 + 1, r);
    }
}

void printArray(int a[], int size) {
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", a[i]);
    printf("\n");
}

int main() {
    int i = 1;
    int a_size = sizeof(a) / sizeof(a[0]);
    srand((unsigned int)time(NULL));
    for (i = 0; i < MAX; i++) {
        a[i] = rand() % 501;
    }
    quick_sort(a, 0, a_size);
    printArray(a, a_size);
}
</code>```

The error is that nothing prints when I run the program.
Can someone help me with the problem?

答:
There are many problems in your code:

You do not include <stdio.h>, <stdlib.h>, nor <time.h>.

Your quick_sort function expects a pointer to an array of double, yet you pass an array of int.

The code for function swap() is not posted.

Your implementation of the Quick Sort algorithm in function quick_sort is flawed:

you should not scan slices of size 1, use (r - l > 1).

You cannot use x[l - 1] as pivot, it is not even part of the slice to be sorted.  Furthermore, you should extract the pivot from the array before the swapping phase as it may move.

You should not name a variable l, it looks too close to 1 and you do make the mistake here: swap(&x[l1 - l], &x[r1 - 1]);

You should initialize l1 and r1 such that you do not need to subtract 1 in so many places, it leads to confusion and erroneous code.

Study the algorithms from the Wikipedia article and translate one to C.

Here is a corrected version:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 100

void swap(int *a, int *b) {
    int x = *a;
    *a = *b;
    *b = x;
}

// Quick Sort using Hoare's original partition scheme
void quick_sort(int *x, int l, int r) {
    if (l < r) {
        int pivot = x[l];
        int l1 = l - 1;
        int r1 = r;

        for (;;) {
            while (x[++l1] < pivot)
                continue;

            while (x[--r1] > pivot)
                continue;

            if (l1 < r1) {
                swap(&x[l1], &x[r1]);
            } else {
                break;
            }
        }
        quick_sort(x, l, r1 + 1);
        quick_sort(x, r1 + 1, r);
    }
}

void printArray(int a[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

int main(void) {
    int a[MAX];
    int a_size = sizeof(a) / sizeof(a[0]);

    srand((unsigned int)time(NULL));

    for (int i = 0; i < MAX; i++) {
        a[i] = rand() % 501;
    }
    quick_sort(a, 0, a_size);

    printArray(a, a_size);
    return 0;
}
</code>```

Body:
I have this C code that creates an array with 100 random numbers and I want to sort it using quick sort, but it always gives a Segmentation fault error.

Here is the code:

#define MAX 100
int a[MAX];
void quick_sort(double *x, int l, int r) {
    int l1, r1;

    if (l < r) {
        l1 = l;
        r1 = r;

        do {
            while (l1 < r && x[l1 - 1] <= x[l - 1]) {
                l1++;
            }
            while (l < r1 && x[r1 - 1] >= x[l - 1]) {
                r1--;
            }
            if (l1 < r1) {
                swap(&x[l1 - l], &x[r1 - 1]);
            }
        } while (l1 < r1);

        swap(&x[l - 1], &x[r1 - 1]);
        quick_sort(x, l, r1 - 1);
        quick_sort(x, r1 + 1, r);
    }
}

void printArray(int a[], int size) {
    int i;
    for (i = 0; i < size; i++)
        printf("%d ", a[i]);
    printf("\n");
}

int main() {
    int i = 1;
    int a_size = sizeof(a) / sizeof(a[0]);
    srand((unsigned int)time(NULL));
    for (i = 0; i < MAX; i++) {
        a[i] = rand() % 501;
    }
    quick_sort(a, 0, a_size);
    printArray(a, a_size);
}

The error is that nothing prints when I run the program.
Can someone help me with the problem?

Body:
There are many problems in your code:

You do not include <stdio.h>, <stdlib.h>, nor <time.h>.

Your quick_sort function expects a pointer to an array of double, yet you pass an array of int.

The code for function swap() is not posted.

Your implementation of the Quick Sort algorithm in function quick_sort is flawed:

you should not scan slices of size 1, use (r - l > 1).

You cannot use x[l - 1] as pivot, it is not even part of the slice to be sorted.  Furthermore, you should extract the pivot from the array before the swapping phase as it may move.

You should not name a variable l, it looks too close to 1 and you do make the mistake here: swap(&x[l1 - l], &x[r1 - 1]);

You should initialize l1 and r1 such that you do not need to subtract 1 in so many places, it leads to confusion and erroneous code.

Study the algorithms from the Wikipedia article and translate one to C.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 100

void swap(int *a, int *b) {
    int x = *a;
    *a = *b;
    *b = x;
}

// Quick Sort using Hoare's original partition scheme
void quick_sort(int *x, int l, int r) {
    if (l < r) {
        int pivot = x[l];
        int l1 = l - 1;
        int r1 = r;

        for (;;) {
            while (x[++l1] < pivot)
                continue;

            while (x[--r1] > pivot)
                continue;

            if (l1 < r1) {
                swap(&x[l1], &x[r1]);
            } else {
                break;
            }
        }
        quick_sort(x, l, r1 + 1);
        quick_sort(x, r1 + 1, r);
    }
}

void printArray(int a[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", a[i]);
    }
    printf("\n");
}

int main(void) {
    int a[MAX];
    int a_size = sizeof(a) / sizeof(a[0]);

    srand((unsigned int)time(NULL));

    for (int i = 0; i < MAX; i++) {
        a[i] = rand() % 501;
    }
    quick_sort(a, 0, a_size);

    printArray(a, a_size);
    return 0;
}


问:
Android Instant App without having a verified website
To build an Instant App it is required to setup App Links. One of the steps  requires to verify that you are the owner of the website you are linking your app to.
Is it possible to create an Instant App if I don't have any website but still want to have ability to send a link to my Instant App to a friend, share in on social media etc?

Basically the idea is to implement "share" feature in the app that will generate a link that will be leading to the instant app.

答:
Instant Apps requires a link to a domain via App Links as Instant Apps are triggered/launched via a URL. There would be no way to launch an Instant App without connecting it to a domain. It's not necessarily required to host an actual website at that domain (aside from hosting the /.well-known/assetlinks.json file) although it is recommended (so that if a non-Instant App enabled device reaches that URL it actually shows something meaningful).

There's nothing to stop you registering and using some arbitrary domain and verifying it via App Links for the functionality you describe. You can use Firebase Hosting to very quickly set up hosting for free and add your assetlinks.json file (and of course there a multitude of other options to host that file as well).


问:
I have two images that I want to display in a single row next to each other
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div id="umar">
  <div class="card">
    <img src="images/img.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="images/img1.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>
</div></code>```

答:
Please use float:left for card class:

```<code>.card{
  float:left
}
</code>```

and also use media query for div width of the mobile version.

Body:
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}

Card

John Doe

Architect & Engineer

John Doe

Architect & Engineer

Body:
Please use float:left for card class:

.card{
  float:left
}

and also use media query for div width of the mobile version.

ContentLicense: CC BY-SA 4.0


问:
How to add current time to a date in 24 hr format
I have a date coming from UI in "MMM DD, YYYY" format, my goal is to convert it in to proper dateTime format and add current time stamp(In 24 hr format) to it and save. I was successfully able to convert and add time to it but it's only taking the AM/PM format.

I tried Below

```<code>string dueDate = "Jul 9, 2017";
        string currentTime = date.ToString("HH:mm:ss");
        DateTime convertedDateTime = Convert.ToDateTime(dueDate).Add(TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss")));
</code>```

Current: 8/27/2017 2:05:00 PM

Goal: 8/27/2017 14:05:00

Is there a way I can get date in 24 hr format in DateTime Format (not in string).

答:
The date time object contains the date and time. It can then be optionally formatted in 24 or 12 hours.

You just need to build a new DateTime made up of the two parts:

```<code>string dueDate = "Jul 9, 2017";
DateTime input = Convert.ToDateTime(dueDate).Date;
DateTime now = DateTime.Now;
DateTime output = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
Console.WriteLine(output.ToString("MM/dd/yyyy HH:mm:ss"));
</code>```

Body:
I have a date coming from UI in "MMM DD, YYYY" format, my goal is to convert it in to proper dateTime format and add current time stamp(In 24 hr format) to it and save. I was successfully able to convert and add time to it but it's only taking the AM/PM format.

I tried Below

string dueDate = "Jul 9, 2017";
        string currentTime = date.ToString("HH:mm:ss");
        DateTime convertedDateTime = Convert.ToDateTime(dueDate).Add(TimeSpan.Parse(DateTime.Now.ToString("HH:mm:ss")));

Current: 8/27/2017 2:05:00 PM

Goal: 8/27/2017 14:05:00

Is there a way I can get date in 24 hr format in DateTime Format (not in string).

Body:
The date time object contains the date and time. It can then be optionally formatted in 24 or 12 hours.

You just need to build a new DateTime made up of the two parts:

string dueDate = "Jul 9, 2017";
DateTime input = Convert.ToDateTime(dueDate).Date;
DateTime now = DateTime.Now;
DateTime output = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
Console.WriteLine(output.ToString("MM/dd/yyyy HH:mm:ss"));


问:
Link mongoDB instance database to meteor local
I've recently setup an ec-2 instance to deploy a meteor application on AWS. My app works correctly with mongoDB database.

Now I want to connect my meteor project's database to the EC2 database and then I've tried some command lines :

start my meteor project with a new mongo url with the following command line : "MONGO_URL="mongodb://username:password@xx.xx.xxx.xxx:27017/Tasks" meteor" but it returns the following screen

connect to mongo with the other following command line :
"meteor mongo --url xx.xx.xxx.xxx:27017" but it returns a timeout. I thought it was due to the lack of username and password however when I add this option meteor does not assume the command.

connect to mongo in my js collection file with
"export const Tasks = mongoose.connect("mongodb://username:password@xx.xx.xxx.xxx:27017/Tasks").connection;" but it returns "Error: connect ECONNREFUSED" (second screen)

Is there any tips to manage to establish database connection from local meteor ?

Thank you for answer,

Martin

答:
If the database and the Meteor processes are in the same machine, you can call it from "localhost".

```<code>MONGO_URL="mongodb://user:password@localhost/Tasks"
</code>```

If you really want to use the IP + Port approach, you have to ensure that it's accessible from the EC2 Security Groups you're using.

The same applies for connecting manually in Mongoose but you should't be using Mongoose with Meteor, it has it's own way of handling collections. If you need something more powerful, or a way to extend it yourself checkout the Meteor Simple Schema project.

Body:
If the database and the Meteor processes are in the same machine, you can call it from "localhost".

MONGO_URL="mongodb://user:password@localhost/Tasks"

If you really want to use the IP + Port approach, you have to ensure that it's accessible from the EC2 Security Groups you're using.

The same applies for connecting manually in Mongoose but you should't be using Mongoose with Meteor, it has it's own way of handling collections. If you need something more powerful, or a way to extend it yourself checkout the Meteor Simple Schema project.


问:
Stuck in echoing data out of variable CodeIgniter
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

```<code>print_r($data);
</code>```

My webpage gives me this:

```<code>(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)
</code>```

Everything seems to be good but when i try to do this:

```<code>echo $data->voornaam;
</code>```

I keep getting this error

```<code>A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once
</code>```

答:
Since your $data is a single-dimensional-array,so it need to be-

```<code>$data[0]->reparatie_id;
$data[0]->customer_id;
$data[0]->medewerker;
$data[0]->name;//so on for other indexes
</code>```

Body:
I try to get some information out of my database to my webpage. Everything seems to be fine but there is one thing that doesn't want to go right. I put all my information out my database into $data. When i do this

print_r($data);

My webpage gives me this:

(
[0] => stdClass Object
   (
   [reparatie_id] => 19
   [customer_id] => 4
   [medewerker] => 4
   [name] => Joost
   )
)

Everything seems to be good but when i try to do this:

echo $data->voornaam;

I keep getting this error

A PHP Error was encountered

Severity: Notice

Message:  Trying to get property of non-object

Filename: reparaties/cases.php

Line Number: 7

Backtrace:

        File: C:\Ampps\www\beco\application\views\reparaties\cases.php

        Line: 7

        Function: _error_handler

        File: C:\Ampps\www\beco\application\controllers\Reparaties.php

        Line: 57

        Function: view

        File: C:\Ampps\www\beco\public\index.php

        Line: 315

        Function: require_once

Body:
Since your $data is a single-dimensional-array,so it need to be-

$data[0]->reparatie_id;
$data[0]->customer_id;
$data[0]->medewerker;
$data[0]->name;//so on for other indexes


问:
Swift - Sort the content of NSSSet
I am using Core Data to fetch the list of clinics, the clinics has relations named doctors mapped to Doctor entity.

My issue is, every time I fetch doctors, which is of type NSSSet, the record is fetched randomly, I want to sort it alphabetically using Doctor.name

I tried the following

```<code>self.doctorList = clinic.doctors?.sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)])
</code>```

Where am I going wrong?

Thanks.

答:
(NS)Set is an unordered collection type.

To order a Set convert it to an array with the allObjects property and sort the array.

```<code>self.doctorList = (clinic.doctors!.allObjects as! [Doctor]).sorted(by: { $0.name < $1.name })
</code>```

You can even sort the set directly but the result is always an array

```<code>self.doctorList = (clinic.doctors as! Set<Doctor>).sorted(by: { $0.name < $1.name })
</code>```

And if the set is declared as native Set<Doctor> anyway you can omit the type cast.

I recommend to declare the doctors relationship as non-optional. If there is no associated doctor the set is empty. But a clinic without any doctor is very unlikely ;-)

Title: Swift - Sort the content of NSSSet

Body:
I am using Core Data to fetch the list of clinics, the clinics has relations named doctors mapped to Doctor entity.

My issue is, every time I fetch doctors, which is of type NSSSet, the record is fetched randomly, I want to sort it alphabetically using Doctor.name

I tried the following

self.doctorList = clinic.doctors?.sortedArray(using: [NSSortDescriptor(key: "name", ascending: true)])

Where am I going wrong?

Thanks.

Body:
(NS)Set is an unordered collection type.

To order a Set convert it to an array with the allObjects property and sort the array.

self.doctorList = (clinic.doctors!.allObjects as! [Doctor]).sorted(by: { $0.name < $1.name })

You can even sort the set directly but the result is always an array

self.doctorList = (clinic.doctors as! Set<Doctor>).sorted(by: { $0.name < $1.name })

And if the set is declared as native Set<Doctor> anyway you can omit the type cast.

I recommend to declare the doctors relationship as non-optional. If there is no associated doctor the set is empty. But a clinic without any doctor is very unlikely ;-)


问:
How to properly optimise mysql select statement
I have a web page that is divided into different sections. Each section has to show different results. These results are gotten from the database.
This is a sample data on SQLfiddle

http://sqlfiddle.com/#!9/ad98b/1

The following code is what comes to my mind but I'm afraid that it might somehow overload the server when this page is accessed multiple times by different people

```<code>$sectionA = $connect->query("SELECT * FROM Main_Section WHERE section = `A`
");
while ($row = $sectionA->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_a = $sec_result_a.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}

$sectionB = $connect->query("SELECT * FROM Main_Section WHERE section = `B` ");
while ($row = $sectionB->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_b = $sec_result_b.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}

$sectionC = $connect->query("SELECT * FROM Main_Section WHERE section = `C` ");
while ($row = $sectionC->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_c= $sec_result_c.'<p>'.$id.'</p><h3>'.$name.'</h3>';
}
</code>```

UP TO section Z

Is there a way I can Optimise this properly?

答:
Unless there's more to the picture, why not just query everything, ordered by section, to have the A-Z:

```<code>SELECT * FROM Main_Section ORDER BY section
</code>```

... and then process the results with one loop, which could look something like this:

```<code>$sections = $connect->query("SELECT * FROM Main_Section ORDER BY section");

while ($row = $sections->fetch_array())
{
    echo $row['section'] . ' ' . '<p>' . $row['id'] . '</p><h3>' . $row['firstname'] . ' ' . $row['lastname'] . '</h3>';
}
</code>```

Body:
I have a web page that is divided into different sections. Each section has to show different results. These results are gotten from the database.
This is a sample data on SQLfiddle

http://sqlfiddle.com/#!9/ad98b/1

The following code is what comes to my mind but I'm afraid that it might somehow overload the server when this page is accessed multiple times by different people

$sectionA = $connect->query("SELECT * FROM Main_Section WHERE section = `A`
");
while ($row = $sectionA->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_a = $sec_result_a.'
'.$id.'

'.$name.'
';
}

$sectionB = $connect->query("SELECT * FROM Main_Section WHERE section = `B` ");
while ($row = $sectionB->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_b = $sec_result_b.'
'.$id.'

'.$name.'
';
}

$sectionC = $connect->query("SELECT * FROM Main_Section WHERE section = `C` ");
while ($row = $sectionC->fetch_array(MYSQLI_BOTH))
{
    $id = $row["id"];
    $name = $row["name"];
    $sec_result_c= $sec_result_c.'
'.$id.'

'.$name.'
';
}

UP TO section Z

Is there a way I can Optimise this properly?

Body:
Unless there's more to the picture, why not just query everything, ordered by section, to have the A-Z:

SELECT * FROM Main_Section ORDER BY section

... and then process the results with one loop, which could look something like this:

$sections = $connect->query("SELECT * FROM Main_Section ORDER BY section");

while ($row = $sections->fetch_array())
{
    echo $row['section'] . ' ' . '<p>' . $row['id'] . '</p><h3>' . $row['firstname'] . ' ' . $row['lastname'] . '</h3>';
}


问:
Why am I getting this error “ValueError: Wrong number of items passed 2, placement implies 4” even the code is fine?
I am using this code and it gives me this error, ValueError: Wrong number of items passed 2, placement implies 4. It is supposed to print the mean, median and mode in a csv file by using the data from the other csv file. When I use this code it prints mean and median to a specified csv file but it does not print the mode. This is the code I am using(below).

```<code>import pandas as pd
df = pd.read_csv('one_hello.csv', names=['teacher', 'student',\
         's.grade', 't.average','t.median','t.mode'])

df['Star Rating'] = df['Star Rating'].astype(int) #convert to integer.

df['t.mean'] = df.groupby('teacher')['s.grade'].transform('mean')
df['t.median'] = df.groupby('teacher')['s.grade'].transform('median')
df['t.mode'] = df.groupby('teacher')['s.grade'].transform(lambda group: group.mode())
df.to_csv('two_hello.csv') #write to file
</code>```

File 'test_one' looks like this:

```<code>teacher         student         student grade
Jon             marin           99
Jon             Rob             81
Jon             marly           90
Jon             Ticy            90
Bon             lue             76
Bon             martin          76
Bon             marie           56
Ton             Seri            43
Ton             Loku            99
</code>```

I want the file "test_two" to look like this:

```<code>teacher         student         s.grade    t.avg    t.median    t.mode
Jon             marin           99          90         90           90
Jon             Rob             81          90          90          90
Jon             marly           90          90          90          90
Jon             Ticy            90          90          90          90
Bon             lue             76          69.3        76          76
Bon             martin          76          69.3        76          76
Bon             marie           56          69.3        76          76
Ton             Seri            43          69.3        71          43
Ton             Loku            99          69.3        71          99
</code>```

But, it only prints 'mean' and 'median' on the other file and gives me error like this.

```<code>`Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pandas/core/groupby.py", line 3049, in transform
    s = klass(res, indexer)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/series.py", line 250, in __init__
    data = SingleBlockManager(data, index, fastpath=True)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 4117, in __init__
    fastpath=True)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 2719, in make_block
    return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 115, in __init__
    len(self.mgr_locs)))
ValueError: Wrong number of items passed 2, placement implies 4`
</code>```

答:
Your error appears to be in naming the columns of your DataFrame in creation, you're trying to name more columns than there actually are.

Another thing, as you can see here, you should explicitly set header to 0 if you want to replace names of your csv_file header.

without further delay, this code did the job:

```<code>import pandas as pd
df = pd.read_csv('one_hello.csv', names=['teacher', 'student','s.grade'],header=0)

df['s.grade'] = df['s.grade'].astype(int) # you mean s.grade ?

df['t.avg'] = df.groupby('teacher')['s.grade'].transform('mean') #unchanged
df['t.median'] = df.groupby('teacher')['s.grade'].transform('median') #unchanged
df['t.mode'] = df.groupby('teacher')['s.grade'].transform(lambda group: group.mode()) #unchanged
df.to_csv('two_hello.csv') #write to file
</code>```

Hope this was helpful.

Body:
I am using this code and it gives me this error, ValueError: Wrong number of items passed 2, placement implies 4. It is supposed to print the mean, median and mode in a csv file by using the data from the other csv file. When I use this code it prints mean and median to a specified csv file but it does not print the mode. This is the code I am using(below).

import pandas as pd
df = pd.read_csv('one_hello.csv', names=['teacher', 'student',\
         's.grade', 't.average','t.median','t.mode'])

df['Star Rating'] = df['Star Rating'].astype(int) #convert to integer.

df['t.mean'] = df.groupby('teacher')['s.grade'].transform('mean')
df['t.median'] = df.groupby('teacher')['s.grade'].transform('median')
df['t.mode'] = df.groupby('teacher')['s.grade'].transform(lambda group: group.mode())
df.to_csv('two_hello.csv') #write to file

File 'test_one' looks like this:

teacher         student         student grade
Jon             marin           99
Jon             Rob             81
Jon             marly           90
Jon             Ticy            90
Bon             lue             76
Bon             martin          76
Bon             marie           56
Ton             Seri            43
Ton             Loku            99

I want the file "test_two" to look like this:

teacher         student         s.grade    t.avg    t.median    t.mode
Jon             marin           99          90         90           90
Jon             Rob             81          90          90          90
Jon             marly           90          90          90          90
Jon             Ticy            90          90          90          90
Bon             lue             76          69.3        76          76
Bon             martin          76          69.3        76          76
Bon             marie           56          69.3        76          76
Ton             Seri            43          69.3        71          43
Ton             Loku            99          69.3        71          99

But, it only prints 'mean' and 'median' on the other file and gives me error like this.

`Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/pandas/core/groupby.py", line 3049, in transform
    s = klass(res, indexer)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/series.py", line 250, in __init__
    data = SingleBlockManager(data, index, fastpath=True)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 4117, in __init__
    fastpath=True)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 2719, in make_block
    return klass(values, ndim=ndim, fastpath=fastpath, placement=placement)
  File "/usr/local/lib/python2.7/site-packages/pandas/core/internals.py", line 115, in __init__
    len(self.mgr_locs)))
ValueError: Wrong number of items passed 2, placement implies 4`

Body:
Your error appears to be in naming the columns of your DataFrame in creation, you're trying to name more columns than there actually are.

Another thing, as you can see here, you should explicitly set header to 0 if you want to replace names of your csv_file header.

without further delay, this code did the job:

import pandas as pd
df = pd.read_csv('one_hello.csv', names=['teacher', 'student','s.grade'],header=0)

df['s.grade'] = df['s.grade'].astype(int) # you mean s.grade ?

df['t.avg'] = df.groupby('teacher')['s.grade'].transform('mean') #unchanged
df['t.median'] = df.groupby('teacher')['s.grade'].transform('median') #unchanged
df['t.mode'] = df.groupby('teacher')['s.grade'].transform(lambda group: group.mode()) #unchanged
df.to_csv('two_hello.csv') #write to file

Hope this was helpful.


问:
vtable in case of virtual inheritance
What is the use of vtable (or why is vtable required ) in case of virtual inheritance ? what does this vtable points to in this case.

example:

```<code>class A
{
    void show()
    { }
};

class B : virtual A
{
    void disp()
    { }
};
</code>```

In the above example the size of class B is 8 bytes. which means class B has vptr pointing to a Vtable. What does this vtable point to .

答:
A vtable is the most common way of implementing the virtual keyword in C++ -- any class that uses the virtual keyword will have a vtable created for it and every instance of that class will contain a pointer to that (single) vtable.  The vtable contains information on the dynamic class of the object (to support dynamic_cast and typeinfo) as well as information as to where virtual base classes and functions of the class are located.

In this specific case, the vtable for B will likely contain just dynamic class info, as A has no data members or virtual functions.

Title: vtable in case of virtual inheritance

Body:
What is the use of vtable (or why is vtable required ) in case of virtual inheritance ? what does this vtable points to in this case.

example:

class A
{
    void show()
    { }
};

class B : virtual A
{
    void disp()
    { }
};

In the above example the size of class B is 8 bytes. which means class B has vptr pointing to a Vtable. What does this vtable point to .


问:
Flutter - Transform scale in center of Container
I'm trying to create a flip effect, but before starting with the animation I'm trying to make the transformation stay in the center of the container.

But even using FractionalOffset(0.5, 0.5) or Center() wrapping the Transform() result remains on the top of the Container, as in the image below.

Could you help me leave it in the center of the container?

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Container(
              alignment: new FractionalOffset(0.5, 0.5),
              height: 144.0,
              width: 360.0,
              decoration: new BoxDecoration(
                border: new Border.all(color: new Color(0xFF9E9E9E))
              ),
              child: new Transform(
                transform: new Matrix4.identity()..scale(1.0, 0.05),
                  child: new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFF005CA9),
                  ),
                ),
              )
            )
          ],
        ),
      ),
    );
  }
}
</code>```

答:
Transform doesn't affect the layout of its child, it only affects how the child is painted.

If you want to do the scaling with your Transform, you can pass an alignment: FractionalOffset.center.

If you want to center the item with layout primitives instead, you can use FractionallySizedBox instead of Transform.

For a full example of how to animate a flip effect, see my answer to your other question.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Container(
              alignment: new FractionalOffset(0.5, 0.5),
              height: 144.0,
              width: 360.0,
              decoration: new BoxDecoration(
                border: new Border.all(color: new Color(0xFF9E9E9E))
              ),
              child: new Transform(
                alignment: FractionalOffset.center,
                transform: new Matrix4.identity()..scale(1.0, 0.05),
                child: new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFF005CA9),
                  ),
                ),
              )
            )
          ],
        ),
      ),
    );
  }
}
</code>```

Body:
I'm trying to create a flip effect, but before starting with the animation I'm trying to make the transformation stay in the center of the container.

But even using FractionalOffset(0.5, 0.5) or Center() wrapping the Transform() result remains on the top of the Container, as in the image below.

Could you help me leave it in the center of the container?

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Container(
              alignment: new FractionalOffset(0.5, 0.5),
              height: 144.0,
              width: 360.0,
              decoration: new BoxDecoration(
                border: new Border.all(color: new Color(0xFF9E9E9E))
              ),
              child: new Transform(
                transform: new Matrix4.identity()..scale(1.0, 0.05),
                  child: new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFF005CA9),
                  ),
                ),
              )
            )
          ],
        ),
      ),
    );
  }
}

Body:
Transform doesn't affect the layout of its child, it only affects how the child is painted.

If you want to do the scaling with your Transform, you can pass an alignment: FractionalOffset.center.

If you want to center the item with layout primitives instead, you can use FractionallySizedBox instead of Transform.

For a full example of how to animate a flip effect, see my answer to your other question.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Container(
              alignment: new FractionalOffset(0.5, 0.5),
              height: 144.0,
              width: 360.0,
              decoration: new BoxDecoration(
                border: new Border.all(color: new Color(0xFF9E9E9E))
              ),
              child: new Transform(
                alignment: FractionalOffset.center,
                transform: new Matrix4.identity()..scale(1.0, 0.05),
                child: new Container(
                  decoration: new BoxDecoration(
                    color: new Color(0xFF005CA9),
                  ),
                ),
              )
            )
          ],
        ),
      ),
    );
  }
}


问:
Check if Office.js is loaded outside of Office client
If we load a webpage referencing office.js outside Office client, we will get a warning: Office.js is loaded outside of Office client.

This information is useful.

Does anyone know if there is an API to check that inside my code?

Edit 1:

I explain a little bit my scenario and why I ask this question. I am making an application with angularjs which can be loaded in a browser as a web page or in Office as an add-in. And I realise that we should not do  and angular.bootstrap(document, ['myApp']) together, otherwise controllers will execute twice. So I decided to not write  and always use angular.bootstrap in both cases (ie, web page & add-in).

So for a web page, I could write:

```<code>$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
...
</code>```

So for a web page, I need to write angular.bootstrap inside Office.initialize, and share other code with the case of add-in:

```<code>Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    });
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
// share the same code
</code>```

However, if I write these two cases together as follows, it works for a web page, whereas I gives Error: ng:btstrpd
App Already Bootstrapped with this Element for add-in.

```<code>$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
        console.log("bootstrapped inside Office.initialize")
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap']).
</code>```

If I set a flag, console will display bootstrapped outside Office.initialize followed by isBootstrapped, then running the code will show that Office.context or Office.context.document is undefined:

```<code>var isBootstrapped = false;

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    isBootstrapped = true
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        if (isBootstrapped) console.log("isBootstrapped")
        else {
            angular.bootstrap(document, ['myApp'])
            console.log("bootstrapped inside Office.initialize")
        }
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
</code>```

So I really need an efficient way to check if Office.js is loaded outside of Office client (ie, whether it is a web page or an add-in), to decide which piece of angular.bootstrap should be executed.

答:
There is no such API at the moment, though we've internally talked about having an Office.ready() (similar in spirit to $(document).ready(...)), that would fire whenever Office.js is done initializing (whether in the add-in or not).

You are welcome to suggest it on https://github.com/OfficeDev/office-js, and post a link here. My thought on the API is that it would take in a callback (just like $(document).ready(...) that it would fire when ready, and would also be available in promise form (so you can do await Office.ready()).  Do you think that works for your scenario?

FWIW: As a workaround, for Script Lab, we wrap a Promise around Office.initialized (and make sure to do it early on in the loading of the application, else it won't fire if it's much later), wait for it, and if we don't receive anything in the first 3 seconds we show a set of buttons to let the user help disambiguate for us.  See https://script-lab.azureedge.net/ for an example of what that looks like.  Not perfect, but was OK-ish for our scenario.  I do encourage you to file a suggestion bug on the office-js repo, though, adding your concrete scenario to back it.

Body:
If we load a webpage referencing office.js outside Office client, we will get a warning: Office.js is loaded outside of Office client.

This information is useful.

Does anyone know if there is an API to check that inside my code?

Edit 1:

I explain a little bit my scenario and why I ask this question. I am making an application with angularjs which can be loaded in a browser as a web page or in Office as an add-in. And I realise that we should not do  and angular.bootstrap(document, ['myApp']) together, otherwise controllers will execute twice. So I decided to not write  and always use angular.bootstrap in both cases (ie, web page & add-in).

So for a web page, I could write:

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
})

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
...

So for a web page, I need to write angular.bootstrap inside Office.initialize, and share other code with the case of add-in:

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
    });
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])
// share the same code

However, if I write these two cases together as follows, it works for a web page, whereas I gives Error: ng:btstrpd
App Already Bootstrapped with this Element for add-in.

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        angular.bootstrap(document, ['myApp'])
        console.log("bootstrapped inside Office.initialize")
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap']).

If I set a flag, console will display bootstrapped outside Office.initialize followed by isBootstrapped, then running the code will show that Office.context or Office.context.document is undefined:

var isBootstrapped = false;

$(document).ready(function () {
    angular.bootstrap(document, ['myApp'])
    isBootstrapped = true
    console.log("bootstrapped outside Office.initialize")
})

Office.initialize = function (reason) {
    $(document).ready(function () {
        if (isBootstrapped) console.log("isBootstrapped")
        else {
            angular.bootstrap(document, ['myApp'])
            console.log("bootstrapped inside Office.initialize")
        }
    })
}

app = angular.module('myApp', ['ui.router', 'ui.bootstrap'])

So I really need an efficient way to check if Office.js is loaded outside of Office client (ie, whether it is a web page or an add-in), to decide which piece of angular.bootstrap should be executed.


答:
You would first need to sort your array to be able to later get the correct matrix out of it. This can be done using numpy.lexsort.

pcolormesh

The reason for there being one row and column less can be found in this question:
Can someone explain this matplotlib pcolormesh quirk?

So you need to decide if the values in the first two columns should denote the edges of the rectangles in the plot or if they are the center. In any case you need one value more than you have colored rectangles to plot the matrix as pcolormesh.

```<code>data = [ (4, 0.7, 0.8530612244898, 0.016579670213527985),
         (4, 0.6, 0.8730158730157779, 0.011562402525241757),
         (6, 0.8, 0.8378684807257778, 0.018175985875060037),
         (4, 0.8, 0.8605442176870833, 0.015586992159716321),
         (2, 0.8, 0.8537414965986667, 0.0034013605443334316),
         (2, 0.7, 0.843537414966, 0.006802721088333352),
         (6, 0.6, 0.8480725623582223, 0.01696896774039503),
         (2, 0.6, 0.84693877551025, 0.010204081632749995),
         (6, 0.7, 0.8577097505669444, 0.019873637350220318)]

import numpy as np
import matplotlib.pyplot as plt

# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]

#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
# if values are centers of rectangles:
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.
# if values are edges of rectanges:
# x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])
# y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])
X,Y = np.meshgrid(x,y)

#reshape third column to match
Z = data[:,2].reshape(3,3)

plt.pcolormesh(X,Y,Z, cmap="jet")
plt.colorbar()

plt.show()
</code>```

imshow

The same plot can be optained using imshow, where you wouldn't need a grid, but rather specify the extent of the plot.

```<code>import numpy as np
import matplotlib.pyplot as plt

# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]

#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.

#reshape third column to match
Z = data[:,2].reshape(3,3)

plt.imshow(Z, extent=[x[0],x[-1],y[0],y[-1]], cmap="jet",
           aspect="auto", origin="lower")
plt.colorbar()

plt.show()
</code>```

Title: Heatmap with matplotlib

Body:
I have a set of 3-tuples, each 3-tuple consists of (var1, var2, result).
Example of a list of 9 3-tuples:

<type 'list'>:
[(4, 0.7, 0.8530612244898, 0.016579670213527985),
 (4, 0.6, 0.8730158730157779, 0.011562402525241757),
 (6, 0.8, 0.8378684807257778, 0.018175985875060037),
 (4, 0.8, 0.8605442176870833, 0.015586992159716321),
 (2, 0.8, 0.8537414965986667, 0.0034013605443334316),
 (2, 0.7, 0.843537414966, 0.006802721088333352),
 (6, 0.6, 0.8480725623582223, 0.01696896774039503),
 (2, 0.6, 0.84693877551025, 0.010204081632749995),
 (6, 0.7, 0.8577097505669444, 0.019873637350220318)]

Now I'd like to create a heatmap out of this.
Var1 can be values [2,4,6] and Var2 can be [0.6, 0.7, 0.8]. There's a total of 9 results.

This is the code I use to plot a heatmap:

    # list of 3-tuples to 3 lists: x, y and weights
    # x (var1) = [2,4,6]
    # y (var2) = [0.6, 0.7, 0.8]
    # weights (res) = [....] (9 values)

    x, y = np.meshgrid(x, y)
    intensity = np.array(weights)

    plt.pcolormesh(x, y, intensity)
    plt.colorbar()  # need a colorbar to show the intensity scale
    plt.show()

Which leads to this graph:

What I find weird is that there's only 4 sections, but I expected there to be 9 (3x3). Can someone shed some light on what I did wrong here?

Body:
You would first need to sort your array to be able to later get the correct matrix out of it. This can be done using numpy.lexsort.

pcolormesh

The reason for there being one row and column less can be found in this question:
Can someone explain this matplotlib pcolormesh quirk?

So you need to decide if the values in the first two columns should denote the edges of the rectangles in the plot or if they are the center. In any case you need one value more than you have colored rectangles to plot the matrix as pcolormesh.

data = [ (4, 0.7, 0.8530612244898, 0.016579670213527985),
         (4, 0.6, 0.8730158730157779, 0.011562402525241757),
         (6, 0.8, 0.8378684807257778, 0.018175985875060037),
         (4, 0.8, 0.8605442176870833, 0.015586992159716321),
         (2, 0.8, 0.8537414965986667, 0.0034013605443334316),
         (2, 0.7, 0.843537414966, 0.006802721088333352),
         (6, 0.6, 0.8480725623582223, 0.01696896774039503),
         (2, 0.6, 0.84693877551025, 0.010204081632749995),
         (6, 0.7, 0.8577097505669444, 0.019873637350220318)]

import numpy as np
import matplotlib.pyplot as plt

# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]

#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
# if values are centers of rectangles:
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.
# if values are edges of rectanges:
# x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])
# y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])
X,Y = np.meshgrid(x,y)

#reshape third column to match
Z = data[:,2].reshape(3,3)

plt.pcolormesh(X,Y,Z, cmap="jet")
plt.colorbar()

plt.show()

imshow

The same plot can be optained using imshow, where you wouldn't need a grid, but rather specify the extent of the plot.

import numpy as np
import matplotlib.pyplot as plt

# sort the array
data=np.array(data)
ind = np.lexsort((data[:,0],data[:,1]))
data = data[ind]

#create meshgrid for x and y
xu = np.unique(data[:,0])
yu = np.unique(data[:,1])
x = np.append(xu , [xu[-1]+np.diff(xu)[-1]])-np.diff(xu)[-1]/2.
y = np.append(yu , [yu[-1]+np.diff(yu)[-1]])-np.diff(yu)[-1]/2.

#reshape third column to match
Z = data[:,2].reshape(3,3)

plt.imshow(Z, extent=[x[0],x[-1],y[0],y[-1]], cmap="jet",
           aspect="auto", origin="lower")
plt.colorbar()

plt.show()


问:
Output custom code In a specific WooCommerce product page if out of stock
I'm trying to check if the user is on a specific product page, then if the product is out of stock. If the product is not in stock, I want to display an optional promo image that adds another product to cart.

With the current code I get an error and the page stops rendering when it reaches this snippet.

Right now my code is as follows:

```<code><?php if (! $product->is_in_stock() && is_single('12005') ) { ?>

        <div id="oos-promo">
            <a href="https://example.com/?add-to-cart=11820&quantity=1">
                <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
            </a>
        </div>

    <?php } ?>
</code>```

I'm putting this code in the content-single-product.php file nested immediately inside the "entry-summary" element on this template file.

Thoughts?

答:
Figured it out! My mistake was not pulling in the global $product variable prior to the if statement, see final code below:</p>

```<code><?php global $product; if (! $product->is_in_stock() && is_single('12005') ) { ?>

    <div id="oos-promo">
        <a href="https://example.com/?add-to-cart=11820&quantity=1">
            <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
        </a>
    </div>

<?php } ?>
</code>```

Body:
I'm trying to check if the user is on a specific product page, then if the product is out of stock. If the product is not in stock, I want to display an optional promo image that adds another product to cart.

With the current code I get an error and the page stops rendering when it reaches this snippet.

Right now my code is as follows:

<?php if (! $product->is_in_stock() && is_single('12005') ) { ?>

    <?php } ?>

I'm putting this code in the content-single-product.php file nested immediately inside the "entry-summary" element on this template file.

Thoughts?

Body:
Figured it out! My mistake was not pulling in the global $product variable prior to the if statement, see final code below:

<?php global $product; if (! $product->is_in_stock() && is_single('12005') ) { ?>

    <div id="oos-promo">
        <a href="https://example.com/?add-to-cart=11820&quantity=1">
            <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
        </a>
    </div>

<?php } ?>


问:
Ajax Autocomplete Webservice Call - Service Method, am I calling this correctly?
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

```<code>ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
</code>```

where subCategory is a page property that looks like this:

```<code>protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}
</code>```

答: You could use the AutoCompleteExtender's ContextKey parameter to use a single web method that accepted a type name as its context key.  Then in the web method, use reflection and that parameter to return the desired string[].</p>

OwnerDisplayName: Sara Chipps

Body:
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:

ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"

where subCategory is a page property that looks like this:

protected SubCategory subCategory
{
    get
    {
        var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
        return subCategory;
    }
}

OwnerDisplayName: Dave Ward


问:
Assigning the last iterated value to a variable in python
I have the last set of values of an iteration: y1[i],y2[i],y3[i](which was obtained by doing the integration of coupled ODE)
Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again).
This is part of my code:

```<code>#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))

#for iteration
p = 0.0
q = 1.0
n = 10000.0

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.
</code>```

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'

keeps showing up.
The link to the complete code is here:
https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)

I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.

答:
You have an error in line 57:

```<code>def F(Y1,Y2,Y3):
    return Y1*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**(1.0/2.0)
</code>```

in expression H**2, where H is defined as a function in line 62:

```<code>def H(Y1,Y2,Y3):
    ...
</code>```

I'm guessing you really meant to say: H(Y1,Y2,Y3)**2.

But that's not all. Line 52:

```<code>y1 == y1.append(y1[j] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))
</code>```

No need to test for equivalence between y1 and None (that's what append() returns). I'm not sure what you tried to achieve here, maybe this?

```<code>y1.append(y1[-1] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))
</code>```

Also, to access the last element of y1 (line 66), you can use a negative index:

```<code>Y1 = [y1[-1]]   # instead of: Y1 = [y1[j]]
</code>```

Body:
I have the last set of values of an iteration: y1[i],y2[i],y3[i](which was obtained by doing the integration of coupled ODE)
Now I need to assign these values to another variables : Y1,Y2,Y3 and then use these variables in a function f(y,t) (ODEs that has to be integrated again).
This is part of my code:

#constants used
H = 2.27e-18
l = 1.5
G = 6.637*(10**(-11))
k = (8*3.14*G)**0.5
om_de = 0.75
omega_matter = 1 - om_de
w0 = -0.85
rho_c = 3*(H**2)/(k**2)
c = ((om_de*(1 + w0)*rho_c)/(H**2))**0.5
v0 = (om_de*(1 - w0)*rho_c)/(2*np.exp(-l*k))

#for iteration
p = 0.0
q = 1.0
n = 10000.0

def H(Y1,Y2,Y3):
    return -3*Y3*(H**2)*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**0.5 + (l*k*v0*np.exp(-l*Y2*k))/(H**2)

dH = (q-p)/n
Y1 = [y1[j]]
Y2 = [y2[j]]
Y3 = [y3[j]]
But I am not able to do any further operations on them.

TypeError: unsupported operand type(s) for ** or pow(): 'function' and
  'int'

keeps showing up.
The link to the complete code is here:
https://pastebin.com/mdQE29N9 (might help in understanding what I am trying to achieve and the code is too lengthy to be posted here)

I think the problem is with the way I have assigned the values,but am not so sure. Any help here as to what is causing this and how I am supposed to solve this would be great.

Body:
You have an error in line 57:

def F(Y1,Y2,Y3):
    return Y1*(omega_matter/(Y1**3) + (H**2)*(Y3**2)/(2.0*rho_c) + (v0*np.exp(-l*Y2*k))/(rho_c))**(1.0/2.0)

in expression H**2, where H is defined as a function in line 62:

def H(Y1,Y2,Y3):
    ...

I'm guessing you really meant to say: H(Y1,Y2,Y3)**2.

But that's not all. Line 52:

y1 == y1.append(y1[j] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))

No need to test for equivalence between y1 and None (that's what append() returns). I'm not sure what you tried to achieve here, maybe this?

y1.append(y1[-1] + (dh/6.0)*(k1 + 2.0*k2 + 2.0*k3 + k4))

Also, to access the last element of y1 (line 66), you can use a negative index:

Y1 = [y1[-1]]   # instead of: Y1 = [y1[j]]


问:
two dimentional array in smarty
I am trying to display a two dimensional array in smarty like this

Smarty HTML

```<code><table>
{foreach from=$periods item=table}
  <tr>
  {foreach from=$table item=val}
    <td>{$val}</td>
  {/foreach}
  </tr>
{/foreach}
</table>
</code>```

PHP

```<code>$membership=array();
  $i=0;
  while ($dao->fetch()) {
    $membership[]['sno']=++$i;
    $membership[]['start_date']=$dao->start_date;
    $membership[]['end_date']=$dao->end_date;
    $membership[]['total_amount']=$dao->total_amount;
    $membership[]['membership_id']=$dao->membership_id;
    }
    $this->assign('periods',$membership);
</code>```

Each row should display 5 columns(td). But this code displays one td per row

答:
Change your while loop to:

```<code>while ($dao->fetch()) {
    $m = [];
    $m['sno']=++$i;
    $m['start_date']=$dao->start_date;
    $m['end_date']=$dao->end_date;
    $m['total_amount']=$dao->total_amount;
    $m['membership_id']=$dao->membership_id;
    $membership[] = $m;
}
</code>```

In your version of the loop, you were creating five "rows" in the membership array per iteration, instead of one "row" with five "columns".

Title: two dimentional array in smarty

Body:
I am trying to display a two dimensional array in smarty like this

Smarty HTML

{foreach from=$periods item=table}

  {foreach from=$table item=val}
    {$val}
  {/foreach}

{/foreach}

PHP

$membership=array();
  $i=0;
  while ($dao->fetch()) {
    $membership[]['sno']=++$i;
    $membership[]['start_date']=$dao->start_date;
    $membership[]['end_date']=$dao->end_date;
    $membership[]['total_amount']=$dao->total_amount;
    $membership[]['membership_id']=$dao->membership_id;
    }
    $this->assign('periods',$membership);

Each row should display 5 columns(td). But this code displays one td per row

Body:
Change your while loop to:

while ($dao->fetch()) {
    $m = [];
    $m['sno']=++$i;
    $m['start_date']=$dao->start_date;
    $m['end_date']=$dao->end_date;
    $m['total_amount']=$dao->total_amount;
    $m['membership_id']=$dao->membership_id;
    $membership[] = $m;
}

In your version of the loop, you were creating five "rows" in the membership array per iteration, instead of one "row" with five "columns".


答:
Instead of overriding WooCommerce templates you should embed your code in a function hooked in woocommerce_single_product_summary action hook, this way:

```<code>add_action( 'woocommerce_single_product_summary', 'out_of_stock_custom_code', 3 );
function out_of_stock_custom_code() {
    // Including the WC_Product object
    global $product;

    if ( ! $product->is_in_stock() && $product->get_id() == 12005 ) {
        ?>
        <div id="oos-promo">
            <a href="?add-to-cart=11820&quantity=1">
                <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
            </a>
        </div>
        <?php
    }
}
</code>```

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

This code Is tested and works.

Title: Output custom code In a specific WooCommerce product page if out of stock

Body:
Instead of overriding WooCommerce templates you should embed your code in a function hooked in woocommerce_single_product_summary action hook, this way:

add_action( 'woocommerce_single_product_summary', 'out_of_stock_custom_code', 3 );
function out_of_stock_custom_code() {
    // Including the WC_Product object
    global $product;

    if ( ! $product->is_in_stock() && $product->get_id() == 12005 ) {
        ?>
        <div id="oos-promo">
            <a href="?add-to-cart=11820&quantity=1">
                <img src="https://example.com/wp-content/uploads/2017/07/product.jpg" alt="Promo" class="img-responsive">
            </a>
        </div>
        <?php
    }
}

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

This code Is tested and works.