问:
Calculate elevation angle between two lat/long/alt points using cesiumjs
Using cesiumjs, I'd like to calculate the elevation angle between two points as though we were standing on a hot air balloon at the first point. The points are simple cartographic points (lat, long, altitude).

This picture sums it up nicely

After some researching, this was a suggested approach:

To transform your target point in the Earth-fixed frame to this local
  horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
  That returns a Matrix4, which you then multiply your target point
  vector by, yielding a new vector.  Normalize that vector, and then the
  elevation angle is simply asin(z) of the normalized vector.

This is the code I've put together, but it returns NaN for the multiplication. Any suggestions would be greatly appreciated.

```<code>var Cesium = require('cesium');

var startPoint = new Cesium.Cartesian3.fromDegrees(-107, 30, 3000);
var endPoint = new Cesium.Cartesian3.fromDegrees(-112, 25, 1000000);

//To transform your target point in the Earth-fixed frame to this local horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
var effTarget = Cesium.Transforms.eastNorthUpToFixedFrame(endPoint)
console.log("Earth-fixed frame (target): " + effTarget);

//That returns a Matrix4, which you then multiply your target point vector by, yielding a new vector.
var multiplicationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.multiplyComponents(effTarget, endPoint, multiplicationResult)
console.log("Multiplication result: " + multiplicationResult)

//Normalize that vector
var normalizationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.normalize(multiplicationResult, normalizationResult);
console.log("Normalize result: " + normalizationResult)

//and then the elevation angle is simply asin(z) of the normalized vector.
var elevationAngle = Math.asin(normalizationResult.z)
console.log("Elevation angle: " + elevationAngle)
</code>```

答:
This is heading in the right direction, but isn't quite right yet:</p>

```<code>var startPoint = new Cesium.Cartesian3.fromDegrees(-107, 30, 3000);
var endPoint = new Cesium.Cartesian3.fromDegrees(-112, 25, 1000000);

//To transform your target point in the Earth-fixed frame to this local horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
var effTarget = Cesium.Transforms.eastNorthUpToFixedFrame(endPoint);
console.log("Earth-fixed frame (target): " + effTarget);

//That returns a Matrix4, which you then multiply your target point vector by, yielding a new vector.
var multiplicationResult = Cesium.Matrix4.multiplyByPointAsVector(effTarget, startPoint, new Cesium.Cartesian3());
console.log("Multiplication result: " + multiplicationResult);

//Normalize that vector
var normalizationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.normalize(multiplicationResult, normalizationResult);
console.log("Normalize result: " + normalizationResult);

//and then the elevation angle is simply asin(z) of the normalized vector.
var elevationAngle = Math.asin(normalizationResult.z);
console.log("Elevation angle: " + Cesium.Math.toDegrees(elevationAngle));
</code>```

Body:
Using cesiumjs, I'd like to calculate the elevation angle between two points as though we were standing on a hot air balloon at the first point. The points are simple cartographic points (lat, long, altitude).

This picture sums it up nicely

After some researching, this was a suggested approach:

To transform your target point in the Earth-fixed frame to this local
  horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
  That returns a Matrix4, which you then multiply your target point
  vector by, yielding a new vector.  Normalize that vector, and then the
  elevation angle is simply asin(z) of the normalized vector.

This is the code I've put together, but it returns NaN for the multiplication. Any suggestions would be greatly appreciated.

var Cesium = require('cesium');

var startPoint = new Cesium.Cartesian3.fromDegrees(-107, 30, 3000);
var endPoint = new Cesium.Cartesian3.fromDegrees(-112, 25, 1000000);

//To transform your target point in the Earth-fixed frame to this local horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
var effTarget = Cesium.Transforms.eastNorthUpToFixedFrame(endPoint)
console.log("Earth-fixed frame (target): " + effTarget);

//That returns a Matrix4, which you then multiply your target point vector by, yielding a new vector.
var multiplicationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.multiplyComponents(effTarget, endPoint, multiplicationResult)
console.log("Multiplication result: " + multiplicationResult)

//Normalize that vector
var normalizationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.normalize(multiplicationResult, normalizationResult);
console.log("Normalize result: " + normalizationResult)

//and then the elevation angle is simply asin(z) of the normalized vector.
var elevationAngle = Math.asin(normalizationResult.z)
console.log("Elevation angle: " + elevationAngle)

Body:
This is heading in the right direction, but isn't quite right yet:

var startPoint = new Cesium.Cartesian3.fromDegrees(-107, 30, 3000);
var endPoint = new Cesium.Cartesian3.fromDegrees(-112, 25, 1000000);

//To transform your target point in the Earth-fixed frame to this local horizontal plane, you can use Transforms.eastNorthUpToFixedFrame.
var effTarget = Cesium.Transforms.eastNorthUpToFixedFrame(endPoint);
console.log("Earth-fixed frame (target): " + effTarget);

//That returns a Matrix4, which you then multiply your target point vector by, yielding a new vector.
var multiplicationResult = Cesium.Matrix4.multiplyByPointAsVector(effTarget, startPoint, new Cesium.Cartesian3());
console.log("Multiplication result: " + multiplicationResult);

//Normalize that vector
var normalizationResult = new Cesium.Cartesian3();
Cesium.Cartesian3.normalize(multiplicationResult, normalizationResult);
console.log("Normalize result: " + normalizationResult);

//and then the elevation angle is simply asin(z) of the normalized vector.
var elevationAngle = Math.asin(normalizationResult.z);
console.log("Elevation angle: " + Cesium.Math.toDegrees(elevationAngle));


来源: stackexchange

问:
Column with difference between two timestamps
I have a pandas dataframe which looks like this :

```<code>userID     timestamp                 other_data
1          2017-06-19 17:14:00.000   foo
1          2017-06-19 19:16:00.000   bar
1          2017-06-19 23:26:00.000   ter
1          2017-06-20 01:16:00.000   lol
2          2017-06-20 12:00:00.000   ter
2          2017-06-20 13:15:00.000   foo
2          2017-06-20 17:15:00.000   bar
</code>```

I'd like to add two columns, time_since_previous_point and time_until_next_point, but only between points of each user of course. I don't really care about the unit/format for now (as long as I can switch easily between them) :

```<code>userID     timestamp                 time_since_previous   time_until_next  other data
1          2017-06-19 17:14:00.000                         02:02:00.000     foo
1          2017-06-19 19:16:00.000   02:02:00.000          04:10:00.000     bar
1          2017-06-19 23:26:00.000   04:10:00.000          01:50:00.000     ter
1          2017-06-20 01:16:00.000   01:50:00.000                           lol
2          2017-06-20 12:00:00.000                         01:15:00.000     ter
2          2017-06-20 13:15:00.000   01:15:00.000          04:00:00.000     foo
2          2017-06-20 17:15:00.000   04:00:00.000                           bar
</code>```

How can I do that ? (The cells that are empty can be either empty, NaN, None, depending on what seems best to you, knowing that next, I will be doing descriptive statistics on time_since_previous and time_until_next)

Please note that here, I denoted the userID as being just one column, but in reality, my unique way to identify user is a combination of columns (country + userID)

ContentLicense: CC BY-SA 3.0

Body:
I have a pandas dataframe which looks like this :

userID     timestamp                 other_data
1          2017-06-19 17:14:00.000   foo
1          2017-06-19 19:16:00.000   bar
1          2017-06-19 23:26:00.000   ter
1          2017-06-20 01:16:00.000   lol
2          2017-06-20 12:00:00.000   ter
2          2017-06-20 13:15:00.000   foo
2          2017-06-20 17:15:00.000   bar

I'd like to add two columns, time_since_previous_point and time_until_next_point, but only between points of each user of course. I don't really care about the unit/format for now (as long as I can switch easily between them) :

userID     timestamp                 time_since_previous   time_until_next  other data
1          2017-06-19 17:14:00.000                         02:02:00.000     foo
1          2017-06-19 19:16:00.000   02:02:00.000          04:10:00.000     bar
1          2017-06-19 23:26:00.000   04:10:00.000          01:50:00.000     ter
1          2017-06-20 01:16:00.000   01:50:00.000                           lol
2          2017-06-20 12:00:00.000                         01:15:00.000     ter
2          2017-06-20 13:15:00.000   01:15:00.000          04:00:00.000     foo
2          2017-06-20 17:15:00.000   04:00:00.000                           bar

How can I do that ? (The cells that are empty can be either empty, NaN, None, depending on what seems best to you, knowing that next, I will be doing descriptive statistics on time_since_previous and time_until_next)

Please note that here, I denoted the userID as being just one column, but in reality, my unique way to identify user is a combination of columns (country + userID)

Body:
I think what you are missing is a pandas shift function  and this answer:  Pandas: Shift down values by one row within a group.

Combining both together you can do it like this:

from io import StringIO
import pandas as pd
csv = """userID,timestamp,other_data
1,2017-06-19 17:14:00.000,foo
1,2017-06-19 19:16:00.000,bar
1,2017-06-19 23:26:00.000,ter
1,2017-06-20 01:16:00.000,lol
2,2017-06-20 12:00:00.000,ter
2,2017-06-20 13:15:00.000,foo
2,2017-06-20 17:15:00.000,bar
"""

df = pd.read_csv(StringIO(csv))

gives:

   userID                timestamp other_data
0       1  2017-06-19 17:14:00.000        foo
1       1  2017-06-19 19:16:00.000        bar
2       1  2017-06-19 23:26:00.000        ter
3       1  2017-06-20 01:16:00.000        lol
4       2  2017-06-20 12:00:00.000        ter
5       2  2017-06-20 13:15:00.000        foo
6       2  2017-06-20 17:15:00.000        bar

First, you need to convert timestamp to datetime column:

df['timestamp'] = pd.to_datetime(df.timestamp)

And then combine groupby and shift methods:

df['time_since_previous'] = df['timestamp'] - df.groupby('userID')['timestamp'].shift(1)
df['time_until_next'] = df.groupby('userID')['timestamp'].shift(-1) - df['timestamp']

Which, ultimately, give you what you want:

userID           timestamp other_data  time_since_previous  time_until_next
0       1 2017-06-19 17:14:00        foo                  NaT         02:02:00
1       1 2017-06-19 19:16:00        bar             02:02:00         04:10:00
2       1 2017-06-19 23:26:00        ter             04:10:00         01:50:00
3       1 2017-06-20 01:16:00        lol             01:50:00              NaT
4       2 2017-06-20 12:00:00        ter                  NaT         01:15:00
5       2 2017-06-20 13:15:00        foo             01:15:00         04:00:00
6       2 2017-06-20 17:15:00        bar             04:00:00              NaT

The only thing left for you is to deal with NaTs.


问:
How can I avoid a ripple effect from changing a concrete struct to generic?
I have a configuration struct that looks like this:

```<code>struct Conf {
    list: Vec<String>,
}
</code>```

The implementation was internally populating the list member, but now I have decided that I want to delegate that task to another object.  So I have:

```<code>trait ListBuilder {
    fn build(&self, list: &mut Vec<String>);
}

struct Conf<T: Sized + ListBuilder> {
    list: Vec<String>,
    builder: T,
}

impl<T> Conf<T>
where
    T: Sized + ListBuilder,
{
    fn init(&mut self) {
        self.builder.build(&mut self.list);
    }
}

impl<T> Conf<T>
where
    T: Sized + ListBuilder,
{
    pub fn new(lb: T) -> Self {
        let mut c = Conf {
            list: vec![],
            builder: lb,
        };
        c.init();
        c
    }
}
</code>```

That seems to work fine, but now everywhere that I use Conf, I have to change it:

```<code>fn do_something(c: &Conf) {
    // ...
}
</code>```

becomes

```<code>fn do_something<T>(c: &Conf<T>)
where
    T: ListBuilder,
{
    // ...
}
</code>```

Since I have many such functions, this conversion is painful, especially since most usages of the Conf class don't care about the ListBuilder - it's an implementation detail. I'm concerned that if I add another generic type to Conf, now I have to go back and add another generic parameter everywhere.  Is there any way to avoid this?

I know that I could use a closure instead for the list builder, but I have the added constraint that my Conf struct needs to be Clone, and the actual builder implementation is more complex and has several functions and some state in the builder, which makes a closure approach unwieldy.

答:
You can use the trait object Box<dyn ListBuilder> to hide the type of the builder. Some of the consequences are dynamic dispatch (calls to the build method will go through a virtual function table), additional memory allocation (boxed trait object), and some restrictions on the trait  ListBuilder.

```<code>trait ListBuilder {
    fn build(&self, list: &mut Vec<String>);
}

struct Conf {
    list: Vec<String>,
    builder: Box<dyn ListBuilder>,
}

impl Conf {
    fn init(&mut self) {
        self.builder.build(&mut self.list);
    }
}

impl Conf {
    pub fn new<T: ListBuilder + 'static>(lb: T) -> Self {
        let mut c = Conf {
            list: vec![],
            builder: Box::new(lb),
        };
        c.init();
        c
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a configuration struct that looks like this:

struct Conf {
    list: Vec<String>,
}

The implementation was internally populating the list member, but now I have decided that I want to delegate that task to another object.  So I have:

trait ListBuilder {
    fn build(&self, list: &mut Vec<String>);
}

struct Conf<T: Sized + ListBuilder> {
    list: Vec<String>,
    builder: T,
}

impl<T> Conf<T>
where
    T: Sized + ListBuilder,
{
    fn init(&mut self) {
        self.builder.build(&mut self.list);
    }
}

impl<T> Conf<T>
where
    T: Sized + ListBuilder,
{
    pub fn new(lb: T) -> Self {
        let mut c = Conf {
            list: vec![],
            builder: lb,
        };
        c.init();
        c
    }
}

That seems to work fine, but now everywhere that I use Conf, I have to change it:

fn do_something(c: &Conf) {
    // ...
}

becomes

fn do_something<T>(c: &Conf<T>)
where
    T: ListBuilder,
{
    // ...
}

Since I have many such functions, this conversion is painful, especially since most usages of the Conf class don't care about the ListBuilder - it's an implementation detail. I'm concerned that if I add another generic type to Conf, now I have to go back and add another generic parameter everywhere.  Is there any way to avoid this?

I know that I could use a closure instead for the list builder, but I have the added constraint that my Conf struct needs to be Clone, and the actual builder implementation is more complex and has several functions and some state in the builder, which makes a closure approach unwieldy.

Body:
You can use the trait object Box<dyn ListBuilder> to hide the type of the builder. Some of the consequences are dynamic dispatch (calls to the build method will go through a virtual function table), additional memory allocation (boxed trait object), and some restrictions on the trait  ListBuilder.

trait ListBuilder {
    fn build(&self, list: &mut Vec<String>);
}

struct Conf {
    list: Vec<String>,
    builder: Box<dyn ListBuilder>,
}

impl Conf {
    fn init(&mut self) {
        self.builder.build(&mut self.list);
    }
}

impl Conf {
    pub fn new<T: ListBuilder + 'static>(lb: T) -> Self {
        let mut c = Conf {
            list: vec![],
            builder: Box::new(lb),
        };
        c.init();
        c
    }
}


问:
Logstash kafka topic as part of elasticsearch indexname
I want to use kafka topic as part of es-indexname. Here is my example, but this does not work:

```<code>input {
  kafka {
    ...
    decorate_events => true
  }
}

filter {
  mutate {
    add_field => {"[@metadata][index]" => "[kafka][topic]"}
  }
}

output {
  elasticsearch {
    index => "kafka-%{[@metadata][index]}-%{+YYYY.MM.dd}"
    ...
  }
}
</code>```

Can someone find the problem in this logstash.conf?

答:
hello this is working config:</p>

```<code>input {
  kafka {
    ...
    decorate_events => true
  }
}

filter {
  mutate {
    add_field => {"[@metadata][index]" => "%{[kafka][topic]}"}
  }
}

output {
  elasticsearch {
    index => "kafka-%{[@metadata][index]}-%{+YYYY.MM.dd}"
    ...
  }
}
</code>```

Body:
I want to use kafka topic as part of es-indexname. Here is my example, but this does not work:

input {
  kafka {
    ...
    decorate_events => true
  }
}

filter {
  mutate {
    add_field => {"[@metadata][index]" => "[kafka][topic]"}
  }
}

output {
  elasticsearch {
    index => "kafka-%{[@metadata][index]}-%{+YYYY.MM.dd}"
    ...
  }
}

Can someone find the problem in this logstash.conf?

Body:
hello this is working config:

input {
  kafka {
    ...
    decorate_events => true
  }
}

filter {
  mutate {
    add_field => {"[@metadata][index]" => "%{[kafka][topic]}"}
  }
}

output {
  elasticsearch {
    index => "kafka-%{[@metadata][index]}-%{+YYYY.MM.dd}"
    ...
  }
}


问:
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?

答:
maybe you can try this:

namespace :spree do
  namespace :api do
    resources :aramex_address, only: [] do
      get :validate_address_with_aramex
      get :fetch_cities_from_aramex_address
    end
  end
end

words of advice I think it's better if you rename the fetch_cities_from_aramex_address with show method, so it still follow rails convenience

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?


问:
React, Redux and Axios - trying to make API call
It's my first experience with React, Redux and I am totally lost. The problem is my action :

```<code>import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}
</code>```

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only

答:
You are performing async request using axios. You should dispatch your action using redux-thunk. Installation is easy, read more about thunk here.

Then your action should look like this:

```<code>export function fetchMovies(pop) {
  return dispatch => {
    const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
    axios.get(url)
    .then(function (response) {
      console.log("response is",response);

      dispatch({
        type:  FETCH_MOVIE,
        payload: response.data
      });

    })
    .catch(function (error) {
      console.log(error);
      // You can dispatch here error
      // Example
      dispatch({
        type:  FETCH_MOVIE_FAILED,
        payload: error
      });
    });

  }
}
</code>```

Body:
It's my first experience with React, Redux and I am totally lost. The problem is my action :

import axios from 'axios';
import { FETCH_MOVIE } from '../constants/actionTypes';
const API_KEY = <API_KEY>;
const ROOT_URL = `<API_URL>`;

export function fetchMovies(pop){

  const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
  axios.get(url)
  .then(function (response) {
    console.log("response is",response)
  })
  .catch(function (error) {
    console.log(error);
  });

  return{
    type:  FETCH_MOVIE,
    payload: response.data
  };
}

On Console.log it seems just fine - I can see the response has the data I need. But when I am trying to send response.data to payload it returns the error -  response is not defined. What am I doing wrong?

P.s. I also tried to create  const result = [] and than result = [...response.data]. The error was - SyntaxError: "result" is read-only

Body:
You are performing async request using axios. You should dispatch your action using redux-thunk. Installation is easy, read more about thunk here.

Then your action should look like this:

export function fetchMovies(pop) {
  return dispatch => {
    const url = `${ROOT_URL}?api_key=${API_KEY}&sort_by=${pop}`;
    axios.get(url)
    .then(function (response) {
      console.log("response is",response);

      dispatch({
        type:  FETCH_MOVIE,
        payload: response.data
      });

    })
    .catch(function (error) {
      console.log(error);
      // You can dispatch here error
      // Example
      dispatch({
        type:  FETCH_MOVIE_FAILED,
        payload: error
      });
    });

  }
}


问:
missing data in gridview
I've created

```<code>        DataTable dt = new DataTable();

        dt.Columns.Add("Type");
        dt.Columns.Add("Address1");
        dt.Columns.Add("Address2");
        dt.Columns.Add("PostalCode");
        dt.Columns.Add("Country");

        DataRow drow = dt.NewRow();

        drow["Type"] = ddlAddressType.SelectedItem.ToString();
        drow["Address1"] = txtAddress1.Text;
        drow["Address2"] = txtAddress2.Text;
        drow["PostalCode"] = txtPostalCode.Text;
        drow["Country"] = ddlCountry.SelectedItem.ToString();

        dt.Rows.Add(drow);

        Session["Address"] = dt;
</code>```

tried to add the value into a gridview using the following code:

```<code>public void populateAddressGridView()
{
    if (Session["Address"] != null)
    {
        DataTable dt = (DataTable)Session["Address"];

        if ((dt != null) && (dt.Rows.Count > 0))
        {
            AddressGridView.Visible = true;
            AddressGridView.DataSource = dt;
            AddressGridView.DataBind();
        }
        else
        {
            AddressGridView.Visible = false;
        }
    }
</code>```

but the fields are empty without any value after adding a new data row.
if i enable autogeneration of fields, i am able to view the generated data.

how do i go about solving this problem?

答:
Sounds to me like you need to set AutoGenerateColumns="false" and then specify the columns to show in the gridview:</p>

```<code><asp:GridView ID="AddressGridView" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText="Type" DataField="Type" />
    <asp:BoundField HeaderText="Address1" DataField="Address1" />
    <asp:BoundField HeaderText="Address2" DataField="Address2" />
    <asp:BoundField HeaderText="PostalCode" DataField="PostalCode" />
    <asp:BoundField HeaderText="Country" DataField="Country" />
</Columns>
<EmptyDataTemplate>
    No records were found matching your search criteria
</EmptyDataTemplate>
</asp:GridView>
</code>```

OwnerDisplayName: Hector

ContentLicense: CC BY-SA 2.5

Title: missing data in gridview

Body:
I've created

        DataTable dt = new DataTable();

        dt.Columns.Add("Type");
        dt.Columns.Add("Address1");
        dt.Columns.Add("Address2");
        dt.Columns.Add("PostalCode");
        dt.Columns.Add("Country");

        DataRow drow = dt.NewRow();

        drow["Type"] = ddlAddressType.SelectedItem.ToString();
        drow["Address1"] = txtAddress1.Text;
        drow["Address2"] = txtAddress2.Text;
        drow["PostalCode"] = txtPostalCode.Text;
        drow["Country"] = ddlCountry.SelectedItem.ToString();

        dt.Rows.Add(drow);

        Session["Address"] = dt;

tried to add the value into a gridview using the following code:

public void populateAddressGridView()
{
    if (Session["Address"] != null)
    {
        DataTable dt = (DataTable)Session["Address"];

        if ((dt != null) && (dt.Rows.Count > 0))
        {
            AddressGridView.Visible = true;
            AddressGridView.DataSource = dt;
            AddressGridView.DataBind();
        }
        else
        {
            AddressGridView.Visible = false;
        }
    }

but the fields are empty without any value after adding a new data row.
if i enable autogeneration of fields, i am able to view the generated data.

how do i go about solving this problem?

Body:
Sounds to me like you need to set AutoGenerateColumns="false" and then specify the columns to show in the gridview:

<asp:GridView ID="AddressGridView" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText="Type" DataField="Type" />
    <asp:BoundField HeaderText="Address1" DataField="Address1" />
    <asp:BoundField HeaderText="Address2" DataField="Address2" />
    <asp:BoundField HeaderText="PostalCode" DataField="PostalCode" />
    <asp:BoundField HeaderText="Country" DataField="Country" />
</Columns>
<EmptyDataTemplate>
    No records were found matching your search criteria
</EmptyDataTemplate>
</asp:GridView>


问:
Best class structure practice for step by step object manipulation in python
Hi I want to create a class with multiple methods. Each method depends on the result of another method. A simplified example looks like:

```<code>class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = 0

def method1(self):
    self.results = self.x + self.y
    return self.results

def method2(self):
    self.results = math.sqrt(self.results)
    return self.results
</code>```

method2 should called only after method1. i.e:

```<code>>>> b=klass(3.0, 4.0)
>>> b.method1()
7.0
>>> b.method2()
2.6457513110645907
</code>```

The idea is that someone may need only the result of method1 and someone else may need the result of method2 as well. So the first person needs to run only method1 and the second person needs to run method1 and then method2.

What is the best(most readable and simplest) way  to do that.

Note that this is a much more simple version of a complex class

答:
Correct me if I'm getting this wrong, but couldn't you just call method1 in method2 like this:</p>

```<code>def method2(self):
    self.method1()
    self.results = math.sqrt(self.results)
    return self.results
</code>```

Body:
Hi I want to create a class with multiple methods. Each method depends on the result of another method. A simplified example looks like:

class klass(object):
def __init__(self, x, y):
    self.x = x
    self.y = y
    self.results = 0

def method1(self):
    self.results = self.x + self.y
    return self.results

def method2(self):
    self.results = math.sqrt(self.results)
    return self.results

method2 should called only after method1. i.e:

>>> b=klass(3.0, 4.0)
>>> b.method1()
7.0
>>> b.method2()
2.6457513110645907

The idea is that someone may need only the result of method1 and someone else may need the result of method2 as well. So the first person needs to run only method1 and the second person needs to run method1 and then method2.

What is the best(most readable and simplest) way  to do that.

Note that this is a much more simple version of a complex class

Body:
Correct me if I'm getting this wrong, but couldn't you just call method1 in method2 like this:

def method2(self):
    self.method1()
    self.results = math.sqrt(self.results)
    return self.results


问:
Hive QL Collection items terminated by '$'
I am creating an external table customer with customer id, name and spouse name.

```<code> CREATE TABLE customer(cust id, name struct<fname:string,lname:string>,spouse_name struct<fname:string,lname:string>
    )row format delimited
    fields terminated by ','
    collection items terminated by '$';
</code>```

I am wondering what if incoming data comes something like this

```<code>1,FNAME1$LNAME1,SPOUSE_FNAME1#SPOUSE_LNAME1
2,FNAME2$LNAME2,SPOUSE_FNAME2#SPOUSE_LNAME2
</code>```

I cannot have two delimiters in 'collection items' statement. '$' delimiter would only separate FNAME* and LNAME*. It won't do anything with SPOUSE_FNAME* and SPOUSE_LNAME*. Do we need to write a custom serde for this? I am not sure how data would look like in real world but it is very possible that at some point of time we can get data like this.

答:
Try this

```<code>CREATE TABLE customer(cust_id int, name String, spouse_name string) row format delimited fields terminated by ',' stored as textfile;
load data inpath '<hdfs path of input file>' overwrite into table customer;

CREATE external TABLE customer_tmp(cust_id int, name string,spouse_name string)
row format delimited
fields terminated by ','
stored as textfile location '/hdfs_location_of_customer_tmp';

insert overwrite table customer_tmp
select cust_id,regexp_replace(name,'\\W\\b',':') as name,regexp_replace(spouse_name,'\\W\\b',':') as spouse_name from customer;

CREATE TABLE customer_final(cust_id int, name struct<fname:string,lname:string>,spouse_name struct<fname:string,lname:string>)
row format delimited
fields terminated by ','
collection items terminated by ':'
stored as textfile;

load data inpath '/hdfs_location_of_customer_tmp/*' overwrite into table customer_final;
</code>```

Kindly don't forget to let us know if it worked :)

Body:
I am creating an external table customer with customer id, name and spouse name.

 CREATE TABLE customer(cust id, name struct<fname:string,lname:string>,spouse_name struct<fname:string,lname:string>
    )row format delimited
    fields terminated by ','
    collection items terminated by '$';

I am wondering what if incoming data comes something like this

1,FNAME1$LNAME1,SPOUSE_FNAME1#SPOUSE_LNAME1
2,FNAME2$LNAME2,SPOUSE_FNAME2#SPOUSE_LNAME2

I cannot have two delimiters in 'collection items' statement. '$' delimiter would only separate FNAME* and LNAME*. It won't do anything with SPOUSE_FNAME* and SPOUSE_LNAME*. Do we need to write a custom serde for this? I am not sure how data would look like in real world but it is very possible that at some point of time we can get data like this.

Body:
Try this

CREATE TABLE customer(cust_id int, name String, spouse_name string) row format delimited fields terminated by ',' stored as textfile;
load data inpath '<hdfs path of input file>' overwrite into table customer;

CREATE external TABLE customer_tmp(cust_id int, name string,spouse_name string)
row format delimited
fields terminated by ','
stored as textfile location '/hdfs_location_of_customer_tmp';

insert overwrite table customer_tmp
select cust_id,regexp_replace(name,'\\W\\b',':') as name,regexp_replace(spouse_name,'\\W\\b',':') as spouse_name from customer;

CREATE TABLE customer_final(cust_id int, name struct<fname:string,lname:string>,spouse_name struct<fname:string,lname:string>)
row format delimited
fields terminated by ','
collection items terminated by ':'
stored as textfile;

load data inpath '/hdfs_location_of_customer_tmp/*' overwrite into table customer_final;

Kindly don't forget to let us know if it worked :)


问:
Boolean false echoes an empty string
I've tried everything! I'm trying to find if the user "sales administrator" is allowed in the string. I've tried exploding the string & putting it in an array, i've tried strpos (in code below), preg match and even if (strpos($userAllowedString, $userRole) > -1). The result is always empty. The result should be false, but it's not giving back anything.

```<code>$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";

if(strpos($userAllowedString,$userRole) !== false) {
     $userAllowed= true;
} else {
     $userAllowed = false;
}
</code>```

Any advice?

答:
I would like to recommend php builtin function in_array() for this task. As already said in the comment i want to add this as answer with details</p>

```<code>$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowedString = explode(',', $userAllowedString);

if(in_array($userRole, $userAllowedString)) {
     // True
     $userAllowed= 'true';
} else {
     // False
     $userAllowed = 'false';
}

 echo $userAllowed; //false
</code>```

Title: Boolean false echoes an empty string

Body:
I've tried everything! I'm trying to find if the user "sales administrator" is allowed in the string. I've tried exploding the string & putting it in an array, i've tried strpos (in code below), preg match and even if (strpos($userAllowedString, $userRole) > -1). The result is always empty. The result should be false, but it's not giving back anything.

$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";

if(strpos($userAllowedString,$userRole) !== false) {
     $userAllowed= true;
} else {
     $userAllowed = false;
}

Any advice?

Body:
I would like to recommend php builtin function in_array() for this task. As already said in the comment i want to add this as answer with details

$userAllowedString = "Sales Manager,Sales Director,Project Manager,Developer";
$userRole = "Sales Administrator";
$userAllowedString = explode(',', $userAllowedString);

if(in_array($userRole, $userAllowedString)) {
     // True
     $userAllowed= 'true';
} else {
     // False
     $userAllowed = 'false';
}

 echo $userAllowed; //false


问:
Add SUM of values of two LISTS into new LIST
I have the following two lists:

```<code>first = [1,2,3,4,5]
second = [6,7,8,9,10]
</code>```

Now I want to add the items from both of these lists into a new list.

output should be

```<code>third = [7,9,11,13,15]
</code>```

答:
```<code>    first = [1,2,3,4,5]
    second = [6,7,8,9,10]
    #one way
    third = [x + y for x, y in zip(first, second)]
    print("third" , third)
    #otherway
    fourth = []
    for i,j in zip(first,second):
        global fourth
        fourth.append(i + j)
    print("fourth" , fourth )
#third [7, 9, 11, 13, 15]
#fourth [7, 9, 11, 13, 15]
</code>```

Body:
I have the following two lists:

first = [1,2,3,4,5]
second = [6,7,8,9,10]

Now I want to add the items from both of these lists into a new list.

output should be

third = [7,9,11,13,15]


问:
BeginReceive in a separate thread
For some reason, I need to do BeginReceive on a separate thread, much like this example :

```<code>    public void WaitForData()
    {
        Thread t = new Thread(WaitForDataThread);
        t.Start();
    }

    public void WaitForDataThread()
    {
        try
        {
            CSocketPacket theSocPkt = new CSocketPacket();
            theSocPkt.thisSocket = m_socClient;
            m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, OnDataReceived, theSocPkt);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }
</code>```

But I've always received error right after the BeginReceive call, the OnDataReceived is instantly raised, in that event it will call the EndReceive method, and this error is always thrown : "The I/O operation has been aborted because of either a thread exit or an application request".

But if I remove the separate-thread part (like directly call the WaitForDataThread(), without going through the WaitForData() method), everything works fine.

If you are wondering why would I need to create a separate thread, it is because I need to call the BeginReceive during an event that will be generated from a different thread from a different class. This is pretty much the same like creating a new thread like the sample above, and I need to make it work.

Is there a way that I can do this??

答:
Found the answer on msdn (documentation of Socket.EndReceive):

All I/O initiated by a given thread is
  canceled when that thread exits. A
  pending asynchronous operation can
  fail if the thread exits before the
  operation completes.

You have to make sure, that your thread where you start your socket-operation does not exit until you are done with your socket I/O.

A workaround is to use a threadpool thread, as described here.

Title: BeginReceive in a separate thread

Body:
For some reason, I need to do BeginReceive on a separate thread, much like this example :

    public void WaitForData()
    {
        Thread t = new Thread(WaitForDataThread);
        t.Start();
    }

    public void WaitForDataThread()
    {
        try
        {
            CSocketPacket theSocPkt = new CSocketPacket();
            theSocPkt.thisSocket = m_socClient;
            m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, OnDataReceived, theSocPkt);
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }

But I've always received error right after the BeginReceive call, the OnDataReceived is instantly raised, in that event it will call the EndReceive method, and this error is always thrown : "The I/O operation has been aborted because of either a thread exit or an application request".

But if I remove the separate-thread part (like directly call the WaitForDataThread(), without going through the WaitForData() method), everything works fine.

If you are wondering why would I need to create a separate thread, it is because I need to call the BeginReceive during an event that will be generated from a different thread from a different class. This is pretty much the same like creating a new thread like the sample above, and I need to make it work.

Is there a way that I can do this??


问:
deleting nested categories from a table
I have a table called categories which looks like this

```<code>+-------------+--------------+---------------+
|  id         |  catName     |  parentId     |
+-------------+--------------+---------------+
|  1          | Category 1   |  0            |
|  2          | Category 2   |  0            |
|  3          | Sub Cat 1    |  1            |
|  4          | Sub Cat 2    |  1            |
|  5          | Sub sub cat 1|  4            |
|  6          | Sub sub cat 2|  4            |
|  7          | Category 2   |  0            |
+-------------+--------------+---------------+
</code>```

It would be easy to delete a category and its direct child:

```<code>mysql_query("DELETE FROM `categories` WHERE `id`='$id'");
mysql_query("DELETE FROM `categories` WHERE `parentId`='$id'");
</code>```

However I need to be able to delete ALL children of a category. For example if Category 1 was deleted Sub Cat 1, Sub Cat 2, Sub sub cat 1, Sub sub cat 2 will be deleted

Any help appreciated.

答:
You can use following Function in model for deleted nested categories:</p>

```<code> public function delete_by_id($cat_id)
{
     $this->db->delete('Categories', ['cat_id' => $cat_id]);
            $q = $this->db->where('parent_id', $cat_id)->get('Categories');
        foreach( $q->result() as $Child ) {
            $this->delete_by_id($Child->cat_id);
        }
}
</code>```

Title: deleting nested categories from a table

Body:
I have a table called categories which looks like this

+-------------+--------------+---------------+
|  id         |  catName     |  parentId     |
+-------------+--------------+---------------+
|  1          | Category 1   |  0            |
|  2          | Category 2   |  0            |
|  3          | Sub Cat 1    |  1            |
|  4          | Sub Cat 2    |  1            |
|  5          | Sub sub cat 1|  4            |
|  6          | Sub sub cat 2|  4            |
|  7          | Category 2   |  0            |
+-------------+--------------+---------------+

It would be easy to delete a category and its direct child:

mysql_query("DELETE FROM `categories` WHERE `id`='$id'");
mysql_query("DELETE FROM `categories` WHERE `parentId`='$id'");

However I need to be able to delete ALL children of a category. For example if Category 1 was deleted Sub Cat 1, Sub Cat 2, Sub sub cat 1, Sub sub cat 2 will be deleted

Any help appreciated.

Body:
You can use following Function in model for deleted nested categories:

 public function delete_by_id($cat_id)
{
     $this->db->delete('Categories', ['cat_id' => $cat_id]);
            $q = $this->db->where('parent_id', $cat_id)->get('Categories');
        foreach( $q->result() as $Child ) {
            $this->delete_by_id($Child->cat_id);
        }
}


问:
How can I instantiate singleton class implemented in Bill Pugh method?
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?</p>

```<code>    public class BillPughSingleton {

    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}
</code>```

答:
Try with:</p>

```<code>BillPughSingleton bill = BillPughSingleton.getInstance();
</code>```

Body:
Hi Can please someone tell me the correct way how I can instantiate the below given singleton class?

    public class BillPughSingleton {

    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}

Body:
Try with:

BillPughSingleton bill = BillPughSingleton.getInstance();


问:
printing page with text cut off on right side
when i give the page to print...
the text on the right hand side of the page gets cut off....
i gave text align left in print css but still not working...
providing my code below....

http://jsfiddle.net/jjnKP/

```<code>@media print {
  body {
    margin:0;
    padding:0;
    line-height: 1.4em;
    word-spacing:1px;
    letter-spacing:0.2px;
    font: 17px Arial, Helvetica,"Lucida Grande", serif;
    color: #000;
  }

  .mainDiv, .navbar,
  .copyright  {
    display: none;
  }

  #templateTwoPadding {
    padding: 0 0;
  }

  #tableHeadingLastDF {
    text-align: left;
    width: 134px;
    border:1px solid white;
  }

  #makeLeftDF {
    text-align: left;
  }

  .jumbotron .lead {
    font-size: 12px;
  }
}
</code>```

答:
I had same problem with SVG graphs, below css is worked for me.</p>

```<code>@media print {
    body {transform: scale(.6);}
}
</code>```

Body:
when i give the page to print...
the text on the right hand side of the page gets cut off....
i gave text align left in print css but still not working...
providing my code below....

http://jsfiddle.net/jjnKP/

@media print {
  body {
    margin:0;
    padding:0;
    line-height: 1.4em;
    word-spacing:1px;
    letter-spacing:0.2px;
    font: 17px Arial, Helvetica,"Lucida Grande", serif;
    color: #000;
  }

  .mainDiv, .navbar,
  .copyright  {
    display: none;
  }

  #templateTwoPadding {
    padding: 0 0;
  }

  #tableHeadingLastDF {
    text-align: left;
    width: 134px;
    border:1px solid white;
  }

  #makeLeftDF {
    text-align: left;
  }

  .jumbotron .lead {
    font-size: 12px;
  }
}

Body:
I had same problem with SVG graphs, below css is worked for me.

@media print {
    body {transform: scale(.6);}
}


问:
JQuery Full Calendar with Spring MVC
let me give answer am not using Json i dont no how to use i want
    to dispaly my events in calender pls help me out"  My db values is need to
    display as per date and with total count in particular date ",
     This is my jsp code

```<code>                        <div class="col-md-12">
                            <div class="card-box">

                                <div id="calendar"></div>

                            </div>
                        </div> <!-- end col -->
                    </div>  <!-- end row -->
</code>```

This is my full calender script am using in jsp page only :

```<code><script type="text/javascript">

$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
url: '/leavecalender';  /* might be this is wrong ? */
var calendar = $('#calendar').fullCalendar({
    header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,agendaWeek,agendaDay'
    },
    selectable: true,
    selectHelper: true,
    select: function(start, end, allDay) {
        var title = prompt('Event Title:');
        if (title) {
            calendar.fullCalendar('renderEvent',
            {
                title: title,
                start: start,
                end: end,
                allDay: allDay
            },
                    true // make the event "stick"
                    );
        }
        calendar.fullCalendar('unselect');
    },
    editable: true,
    events:[data]
   });
    });
  </script>
</code>```

And this is my controller :

```<code>@RequestMapping(value = "/leavecalender")
public ModelAndView leave(ModelMap model)
{
TeleCallRecordIdTO telecall = new TeleCallRecordIdTO();
List<TeleCallRecordIdTO> allcall = hrService.getallcalls();

model.addAttribute("allcall", allcall);

return new ModelAndView("HR/hr/leavesCalender","leavecalender",telecall);
}
</code>```

this is my service :

```<code>public List<TeleCallRecordIdTO> getallcalls();
</code>```

this is my serviceImplementation :

```<code>@Override
public List<TeleCallRecordIdTO> getallcalls() {
    return hrDao.getallcalls();
}
</code>```

This is my Dao :

```<code>public List<TeleCallRecordIdTO> getallcalls();
</code>```

This is myDaoImplementation :

```<code>@Override
public List<TeleCallRecordIdTO> getallcalls() {

List<TeleCallRecordIdTO> list = new ArrayList<>();
try {
    String s = "SELECT DATE(call_date) AS 'Date', COUNT(1) AS 'TotalCalls'
     FROM tele_call_record GROUP BY DATE(call_date)";
    Connection connection=sessionFactory.getCurrentSession().connection();
    PreparedStatement preparedStatement;
    preparedStatement=connection.prepareStatement(s);
    ResultSet rs= preparedStatement.executeQuery();
    while(rs.next())
    {
        TeleCallRecordIdTO tel=new TeleCallRecordIdTO();
        tel.setCallDate(rs.getString("Date"));
        /*tel.setExtensionNo(rs.getString("extension_no"));
        tel.setPhoneNo(rs.getString("phone_no"));*/
        tel.setSrNo(rs.getInt("TotalCalls"));
        list.add(tel);
    }

} catch (Exception e) {
    e.printStackTrace();
}

    return list;
}
</code>```

答:
If I understood your problem you need to try this

replace

```<code>events:[data]
</code>```

with

```<code>events: function(start, end, timezone, callback) {
    $.ajax({
        url: '${pageContext.request.contextPath}/leavecalender',
        //data: {
            // data if you are passing
        //},
        success: function(data) {
            var events = [];
            $.each(data, function(index) {
                events.push({
                    title: data[index].srNo,
                    start: data[index].callDate,
                    //end:   data.end
                });
            });
            callback(events);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log( textStatus +" - "+ errorThrown );
        }
    });
}
</code>```

Change your controller method also:

```<code>@RequestMapping(value = "/leavecalender", method=RequestMethod.GET)
@ResponseBody
public List<TeleCallRecordIdTO> leave() {
    return hrService.getallcalls();;
}
</code>```

Title: JQuery Full Calendar with Spring MVC

Body:
let me give answer am not using Json i dont no how to use i want
    to dispaly my events in calender pls help me out"  My db values is need to
    display as per date and with total count in particular date ",
     This is my jsp code

This is my full calender script am using in jsp page only :

And this is my controller :

@RequestMapping(value = "/leavecalender")
public ModelAndView leave(ModelMap model)
{
TeleCallRecordIdTO telecall = new TeleCallRecordIdTO();
List<TeleCallRecordIdTO> allcall = hrService.getallcalls();

model.addAttribute("allcall", allcall);

return new ModelAndView("HR/hr/leavesCalender","leavecalender",telecall);
}

this is my service :

public List<TeleCallRecordIdTO> getallcalls();

this is my serviceImplementation :

@Override
public List<TeleCallRecordIdTO> getallcalls() {
    return hrDao.getallcalls();
}

This is my Dao :

public List<TeleCallRecordIdTO> getallcalls();

This is myDaoImplementation :

@Override
public List<TeleCallRecordIdTO> getallcalls() {

List<TeleCallRecordIdTO> list = new ArrayList<>();
try {
    String s = "SELECT DATE(call_date) AS 'Date', COUNT(1) AS 'TotalCalls'
     FROM tele_call_record GROUP BY DATE(call_date)";
    Connection connection=sessionFactory.getCurrentSession().connection();
    PreparedStatement preparedStatement;
    preparedStatement=connection.prepareStatement(s);
    ResultSet rs= preparedStatement.executeQuery();
    while(rs.next())
    {
        TeleCallRecordIdTO tel=new TeleCallRecordIdTO();
        tel.setCallDate(rs.getString("Date"));
        /*tel.setExtensionNo(rs.getString("extension_no"));
        tel.setPhoneNo(rs.getString("phone_no"));*/
        tel.setSrNo(rs.getInt("TotalCalls"));
        list.add(tel);
    }

} catch (Exception e) {
    e.printStackTrace();
}

    return list;
}

Body:
If I understood your problem you need to try this

replace

events:[data]

with

events: function(start, end, timezone, callback) {
    $.ajax({
        url: '${pageContext.request.contextPath}/leavecalender',
        //data: {
            // data if you are passing
        //},
        success: function(data) {
            var events = [];
            $.each(data, function(index) {
                events.push({
                    title: data[index].srNo,
                    start: data[index].callDate,
                    //end:   data.end
                });
            });
            callback(events);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log( textStatus +" - "+ errorThrown );
        }
    });
}

Change your controller method also:

@RequestMapping(value = "/leavecalender", method=RequestMethod.GET)
@ResponseBody
public List<TeleCallRecordIdTO> leave() {
    return hrService.getallcalls();;
}


问:
How do I create a fixed navigation bar using md-toolabr in vue material?
I want to create a fixed to nav bar using the vue material framework. How do I do that? </p>

```<code><md-whiteframe md-elevation = "3" class = "main-toolbar">

    <md-toolbar class = "flex: 1">

    </md-toolbar>

  </md-whiteframe>
</code>```

<p>I began with this outline but I cannot seem to make it fixed no matter what I do. </p>

答:
You need to add sticky positioning from css. See this codepen for an example: https://codepen.io/aprouja1/pen/awKavJ</p>

```<code>#toolbar{
    position:sticky;
    top:1px;
}
</code>```

Body:
I want to create a fixed to nav bar using the vue material framework. How do I do that?

<md-whiteframe md-elevation = "3" class = "main-toolbar">

    <md-toolbar class = "flex: 1">

    </md-toolbar>

  </md-whiteframe>

I began with this outline but I cannot seem to make it fixed no matter what I do.

Body:
You need to add sticky positioning from css. See this codepen for an example: https://codepen.io/aprouja1/pen/awKavJ

#toolbar{
    position:sticky;
    top:1px;
}


问:
Remapping issue Autohotkey
Please, bear with me, I'm a autohotkey noob. I want left: control and shift to switch from their current key value to arrow: down and up respectively when pressing the F2 key. And when the F2 key is pressed again, I want left: control and shift to return to their original key value. This is my code so far:

```<code>F2::
{
    if LShift = Up
    {
        LShift::Send {LShift}
    }
    else
    {
       LShift::Send {Up}
    }
    if LControl = Down
    {
       LControl::Send {LControl}
    }
   else
   {
      LControl::Send {Down}
   }
}
</code>```

Regrettably I haven't been able to make it work. Any help will be truly appreciated.

答:
Hotkeys that go over multiple lines don't use curly braces. They
start with the hotkey label and end with a simple Return.

You can't enclose hotkey labels by normal if statements. You have to use
special #If statements instead.

Nesting hotkeys is also definitely not what you want to do.

To remap a key you can use the single line hotkey syntax.

You can pretty much short your code down to:

```<code>F2::(F2Toggle:=!F2Toggle)

#If F2Toggle
    LShift::Up
    LControl::Down
#If
</code>```

Pressing F2 will toggle the variable F2Toggle between true and false. #If F2Toggle means if the variable F2Toggle is currently set to True then enable the hotkeys below. #If marks the end of the special #If statement.

Title: Remapping issue Autohotkey

Body:
Please, bear with me, I'm a autohotkey noob. I want left: control and shift to switch from their current key value to arrow: down and up respectively when pressing the F2 key. And when the F2 key is pressed again, I want left: control and shift to return to their original key value. This is my code so far:

F2::
{
    if LShift = Up
    {
        LShift::Send {LShift}
    }
    else
    {
       LShift::Send {Up}
    }
    if LControl = Down
    {
       LControl::Send {LControl}
    }
   else
   {
      LControl::Send {Down}
   }
}

Regrettably I haven't been able to make it work. Any help will be truly appreciated.

Body:
Hotkeys that go over multiple lines don't use curly braces. They
start with the hotkey label and end with a simple Return.

You can't enclose hotkey labels by normal if statements. You have to use
special #If statements instead.

Nesting hotkeys is also definitely not what you want to do.

To remap a key you can use the single line hotkey syntax.

You can pretty much short your code down to:

F2::(F2Toggle:=!F2Toggle)

#If F2Toggle
    LShift::Up
    LControl::Down
#If

Pressing F2 will toggle the variable F2Toggle between true and false. #If F2Toggle means if the variable F2Toggle is currently set to True then enable the hotkeys below. #If marks the end of the special #If statement.


问:
Sign data in ASPX on client side
In my application, the client must sign (using a certificate) and send data to the server.
My doubt is how should I do it?

To sign on the client side, I should use ActiveX right? My problem is that firefox doesn't support it.
Signing on the server side I have two options:

Save the private key on the server and use it when necessary (if the data is modified during the transaction it will sign false data)

Send the private key when necessary (may comprise the key)

Despite using SSL, I'm not very confortable with any of the two options for signing on the server side...
Using ActiveX may cause my application more vulnerable, right?

Hope you can help me :)

答:
There's no single solution for client-side signing in all browsers, unfortunately. We are currently working on distributed signature components for our SecureBlackbox product, and we've created Java applet, ActiveX control and Flex script to perform signing. However, all variants have shortcomings. For example, only ActiveX control can access windows certificate store. With other module types the user would need to load the certificate from PFX (PKCS#12) file.

Uploading and signing on the server won't work because the private key is not always exportable on the client (it can reside on cryptotoken or smartcard, or just be non-exportable), and also this approach makes the whole process useless as it significantly lowers security.

Update: SecureBlackbox 9 is in public beta now, with support for client-side signing (we provide ActiveX, Java and Flash modules for this).

Title: Sign data in ASPX on client side


问:
How to check if case class parameter has value or not in Scala
I have a case class QueryParamsas follows:

```<code>case class QueryParams(
limit: Option[Integer] = None,
refresh: Option[Boolean] = None,
organisationalUnit: Option[String] = None)
</code>```

These values limit,refresh,organisationalUnit are actually passed as query parameters in request url for play application.
I need to write a code to check if request URL contains any value for organisationalUnit and if yes I need to throw error .If no, I need to proceed with further operations.
Can anyone help me here

答:
The answer from stefanobaghino is good but I prefer pattern matching for such cases:

```<code>params.organisationalUnit match {
  case Some(_) => // processing
  case _ => //logging
}
</code>```

If you need other values you can match the whole instance

```<code>params match {
  case QueryParams(Some(limit), Some(refresh), Some(organisationalUnit)) =>
  case QueryParams(mayBeLimit, mayBeRefresh, Some(organisationalUnit)) =>
  case _ =>
}
</code>```

Body:
I have a case class QueryParamsas follows:

case class QueryParams(
limit: Option[Integer] = None,
refresh: Option[Boolean] = None,
organisationalUnit: Option[String] = None)

These values limit,refresh,organisationalUnit are actually passed as query parameters in request url for play application.
I need to write a code to check if request URL contains any value for organisationalUnit and if yes I need to throw error .If no, I need to proceed with further operations.
Can anyone help me here

Body:
The answer from stefanobaghino is good but I prefer pattern matching for such cases:

params.organisationalUnit match {
  case Some(_) => // processing
  case _ => //logging
}

If you need other values you can match the whole instance

params match {
  case QueryParams(Some(limit), Some(refresh), Some(organisationalUnit)) =>
  case QueryParams(mayBeLimit, mayBeRefresh, Some(organisationalUnit)) =>
  case _ =>
}


问:
Gradle does not download complete dependencies
Im trying to download and build spring-data-hadoop 2.4.0.RELEASE using the following decleration in my dependencies.gradle:

```<code>dependencies {
    ...
//    compile('org.springframework.data:spring-data_hadoop:2.4.0.RELEASE')
    compile group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE'

    ...
}
</code>```

Refreshing gradle now results in downloading the newly added dependency BUT the data is not consistend. I got the following external dependencies after the download:

I thought everything is fine now... but I am wrong. Lets open up one of those and look depper into the packages:

If you compare the content of org.springframework.data.hadoop.config with the official API you will notice, that in this package, there should be much more content. The annotations package for example.

How can it be that gradle is not downloading the complete source?

答:
You are pulling the main jar that should pull the transitive artifacts as well.

the org.springframework.data.hadoop.config.annotation is included inside

```<code>compile group: 'org.springframework.data', name: 'spring-data-hadoop-config', version: '2.4.0.RELEASE'
</code>```

Body:
Im trying to download and build spring-data-hadoop 2.4.0.RELEASE using the following decleration in my dependencies.gradle:

dependencies {
    ...
//    compile('org.springframework.data:spring-data_hadoop:2.4.0.RELEASE')
    compile group: 'org.springframework.data', name: 'spring-data-hadoop', version: '2.4.0.RELEASE'

    ...
}

Refreshing gradle now results in downloading the newly added dependency BUT the data is not consistend. I got the following external dependencies after the download:

I thought everything is fine now... but I am wrong. Lets open up one of those and look depper into the packages:

If you compare the content of org.springframework.data.hadoop.config with the official API you will notice, that in this package, there should be much more content. The annotations package for example.

How can it be that gradle is not downloading the complete source?

Body:
You are pulling the main jar that should pull the transitive artifacts as well.

the org.springframework.data.hadoop.config.annotation is included inside

compile group: 'org.springframework.data', name: 'spring-data-hadoop-config', version: '2.4.0.RELEASE'