问:
I'm making several requests for JSONP data using jQuery, how do I figure out which request goes with which result?
The results comeback out of order from the sequence I made them.  If I wait for each request to finish the results are OK but it takes longer than I'd like.  Is there a way for me to keep track of which result belongs to which request?

EDIT: Per request I'm adding the code that performs the JSON calls.

```<code>for (var i = 0; i < rssLinkDB.length; i++) {
  jQuery.getJSON(encoded, function(data){
    yLinkDB.push(data.query.results.result);
    index++;
    if (index == 10) {
      state = "RequestLikes";
    }
  });
}
</code>```

答:
If you are calling a server side method, you can use a custom HTTP Header as a flag to track the request/response ownership.

Add a custom HTTP Header in the server side method and use its key to get the value from the client side:

```<code>// In Server Side method (e.g ASP.NET Page Method):
HttpContext.Current.Response.AddHeader("MyCustomKey", "TheValue");

// In jQuery callback body:
var myCustomHeader = XMLHttpRequest.getResponseHeader("MyCustomKey");
// now do whatever you want based on myCustomHeader value...
</code>```

Body:
The results comeback out of order from the sequence I made them.  If I wait for each request to finish the results are OK but it takes longer than I'd like.  Is there a way for me to keep track of which result belongs to which request?

EDIT: Per request I'm adding the code that performs the JSON calls.

for (var i = 0; i < rssLinkDB.length; i++) {
  jQuery.getJSON(encoded, function(data){
    yLinkDB.push(data.query.results.result);
    index++;
    if (index == 10) {
      state = "RequestLikes";
    }
  });
}

Body:
If you are calling a server side method, you can use a custom HTTP Header as a flag to track the request/response ownership.

Add a custom HTTP Header in the server side method and use its key to get the value from the client side:

// In Server Side method (e.g ASP.NET Page Method):
HttpContext.Current.Response.AddHeader("MyCustomKey", "TheValue");

// In jQuery callback body:
var myCustomHeader = XMLHttpRequest.getResponseHeader("MyCustomKey");
// now do whatever you want based on myCustomHeader value...


来源: stackexchange

问:
Unparseable date: "Thu, 7 Dec 2017 07:40:40 "
I am getting the above exception while trying to parse. I tried the following date format,</p>

```<code>SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM  yyyy  HH:mm:ss ", Locale.ENGLISH);
</code>```

答:
java.time

The SimpleDateFormat class is not only long outdated, it is also notoriously troublesome. I recommend you stop using it and use java.time the modern Java date and time API also known as JSR-310, instead. It is so much nicer to work with.

```<code>    System.out.println(LocalDateTime.parse("Thu, 7 Dec 2017 07:40:40 ",
            DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss ", Locale.ENGLISH)));
</code>```

This prints the expected date and time:

```<code>2017-12-07T07:40:40
</code>```

What went wrong

In your format pattern string, you’ve got two spaces before and two spaces after yyyy, where it seems that in your date-time string there is only one space in each of those places. While SimpleDateFormat is infamous for parsing strings that it ought to reject, it does object in this case by throwing the ParseException the message of which you quote in the question title.

If you compare my format pattern string to yours, you will notice I use just one d where you use two. SimpleDateFormat parses 7 with dd where the modern classes are stricter: d matches a date-of-month of either 1 or 2 digits. where dd requires two digits. You may of course exploit this for stricter validation if you need it.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.

For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.

ContentLicense: CC BY-SA 3.0

Body:
I am getting the above exception while trying to parse. I tried the following date format,

SimpleDateFormat sdf = new SimpleDateFormat("E, dd MMM  yyyy  HH:mm:ss ", Locale.ENGLISH);

Body:
java.time

The SimpleDateFormat class is not only long outdated, it is also notoriously troublesome. I recommend you stop using it and use java.time the modern Java date and time API also known as JSR-310, instead. It is so much nicer to work with.

    System.out.println(LocalDateTime.parse("Thu, 7 Dec 2017 07:40:40 ",
            DateTimeFormatter.ofPattern("E, d MMM yyyy HH:mm:ss ", Locale.ENGLISH)));

This prints the expected date and time:

2017-12-07T07:40:40

What went wrong

In your format pattern string, you’ve got two spaces before and two spaces after yyyy, where it seems that in your date-time string there is only one space in each of those places. While SimpleDateFormat is infamous for parsing strings that it ought to reject, it does object in this case by throwing the ParseException the message of which you quote in the question title.

If you compare my format pattern string to yours, you will notice I use just one d where you use two. SimpleDateFormat parses 7 with dd where the modern classes are stricter: d matches a date-of-month of either 1 or 2 digits. where dd requires two digits. You may of course exploit this for stricter validation if you need it.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

In Java 8 and later the new API comes built-in.

In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310).

On Android, use the Android edition of ThreeTen Backport. It’s called ThreeTenABP, and there’s a thorough explanation in this question: How to use ThreeTenABP in Android Project.

For learning to use java.time, see the Oracle tutorial or find other resoureces on the net.


问:
Vue.js global event not working
I've got

```<code><component-one></component-one>

<component-two></component-two>
      <component-three></component-three>
</code>```

Component two contains component three.

Currently I emit an event in <component-one> that has to be caught in <component-three>.

In <component-one> I fire the event like this:

```<code>this.$bus.$emit('setSecondBanner', finalBanner);
</code>```

Then in <component-three> I catch it like this:

```<code>mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},
</code>```

But the event is never caught!

I define the bus like this (in my core.js):

```<code>let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});
</code>```

What could be wrong here? When I check vue-dev-tools I can see that the event has fired!

答:
Have you tried registering the listener in created instead of mounted?

Also, why define the bus with defineProperties and not simply:

```<code>Vue.prototype.$bus = new Vue();
</code>```

Title: Vue.js global event not working

Body:
I've got

<component-one></component-one>

<component-two></component-two>
      <component-three></component-three>

Component two contains component three.

Currently I emit an event in <component-one> that has to be caught in <component-three>.

In <component-one> I fire the event like this:

this.$bus.$emit('setSecondBanner', finalBanner);

Then in <component-three> I catch it like this:

mounted() {
    this.$bus.$on('setSecondBanner', (banner) => {
        alert('Caught');
        this.banner = banner;
    });
},

But the event is never caught!

I define the bus like this (in my core.js):

let eventBus = new Vue();

Object.defineProperties(Vue.prototype, {
    $bus: {
        get: () => { return eventBus; }
    }
});

What could be wrong here? When I check vue-dev-tools I can see that the event has fired!

Body:
Have you tried registering the listener in created instead of mounted?

Also, why define the bus with defineProperties and not simply:

Vue.prototype.$bus = new Vue();


问:
Cordova does not "see" Android SDK version
I am in the process of setting up a new Cordova CLI toolchain to build hybrid Android apps that target Android 5.1+.  I am using

Node 8.9.2

Cordova 7.1.0

After issuing a cordova create... command to create a new Cordova project I proceeded to add Android 5.1 using cordova platform add android@5.1.0 which went smoothly.

I have also ensured that I have the relevant Android SDKs available and pointed at properly via ANDROID_HOME.  I currently have SDKs 19 through to 27 installed.

However, when I issue a cordova build android I get the message Error: Android SDK not found.  Strangely enough if I let Cordova install its current default Android version via cordova platform add android which adds Android 6.3.1 it then lets me build the project without any further ado.

Is this a matter of Cordova 7.1.0 simply not wanting to play ball with lower versions of Android or is there something else going on here?  Can I get around this by installing an older version of Cordova via npm?  If so, which version should I install - and how?

答:
Your problem is you're adding an old version of the cordova-android platform project, (v5.1.0) which is over 2 years old and not compatible with the cordova@7.1.0 CLI.

If you want to target Android 5.1+, you don't need to use cordova-android@5.1.0, you need to specify a preference in the config.xml to target Android 5.1 (API 22) and above:

```<code><preference name="android-minSdkVersion" value="22" />
</code>```

You probably want to use the default cordova-android platform version (6.3.1), unless you need to do stuff with Android Studio 3, in which case use cordova platform add android@latest which will add cordova-android@7.0.0 and requires Gradle 4 to build (see here).

Body:
Your problem is you're adding an old version of the cordova-android platform project, (v5.1.0) which is over 2 years old and not compatible with the cordova@7.1.0 CLI.

If you want to target Android 5.1+, you don't need to use cordova-android@5.1.0, you need to specify a preference in the config.xml to target Android 5.1 (API 22) and above:

<preference name="android-minSdkVersion" value="22" />

You probably want to use the default cordova-android platform version (6.3.1), unless you need to do stuff with Android Studio 3, in which case use cordova platform add android@latest which will add cordova-android@7.0.0 and requires Gradle 4 to build (see here).


问:
Android - How to regenerate R class?

Possible Duplicate:

  Developing for Android in Eclipse: R.java not generating

I have imported a project into my Eclipse IDE, but it's giving me an error since R file is not generated automatically.

How can I edit the R file so that it matches my project requirements?

答:
In  another stackoverflow question, somebody answered this : you must get rid of warnings and errors (syntax and links) in your xml files. This plus doing a clean / build project.

Project -> Clean, and choose the option to build the project.

Title: Android - How to regenerate R class?


问:
R: Using a variable with less observations in a regression (plm)
I have been trying to deal with this for a while now with no luck. Essentially, what I am doing is a two-stage least squares on some panel data. To do this I am using the plm package. What I want to do is

Do a 2SLS

Get the residuals from the 2SLS in 1.

Use these residuals as an instrument in a different 2SLS

The issue I have is that in the first 2SLS the number of observations used is less than the total observations in the dataset, so my residuals vector is short and I get the following error

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :
    variable lengths differ (found for 'ivreg.2.a$residuals')

Here is the code I am trying to run for reference, let me know if you need any more details. I really just need my residual vector to be the same length as the data used in the first 2SLS. For reference my data has 1713 observations, however, only 1550 get used in the regression and as a result my residuals vector is length 1550. My code for the two 2SLS regressions is below.

```<code>ivreg.2.a = plm(formula = diff(loda) ~ factor(year)+diff(lgdp) | index_g_l + diff(lcru_l) + diff(lcru_l_sq) + factor(year), index = c("country", "year"), model = "within", data = panel[complete.cases(panel[, c(1,2,3,4,5,7)]),])

 ivreg.2.a = plm(formula = diff(lgdp) ~ factor(year)+index_g_l + diff(lcru_l) + diff(lcru_l_sq) + diff(loda)| index_g_l + diff(lcru_l) + diff(lcru_l_sq) + factor(year) + ivreg.2.a$residuals, index = c("country", "year"), model = "within", data = panel[complete.cases(panel[, c(1,2,3,4,5,7)]),])
</code>```

Let me know if you need anything else.

答:
I assume the 163 observations are dropped because they have NA in one of the relevant variables. Most *lm functions in R have a na.action argument, which can be used to pad the residuals to correct length. E.g., when missing observation 3,

```<code>residuals(lm(formula, data, na.action=na.omit)) # 1 2 4
residuals(lm(formula, data, na.action=na.exclude)) # 1 2 NA 4
</code>```

Documentation of plm, however, says that this argument is "currently not fully supported", so it would be simpler if you just filter those 1550 rows to a new dataframe first, and do all subsequent work on that.

BTW, if plm behaves like lm, you shouldn't need to specify complete.cases for it to work, as it should just skip anything with NAs.

Body:
I have been trying to deal with this for a while now with no luck. Essentially, what I am doing is a two-stage least squares on some panel data. To do this I am using the plm package. What I want to do is

Do a 2SLS

Get the residuals from the 2SLS in 1.

Use these residuals as an instrument in a different 2SLS

The issue I have is that in the first 2SLS the number of observations used is less than the total observations in the dataset, so my residuals vector is short and I get the following error

Error in model.frame.default(terms(formula, lhs = lhs, rhs = rhs, data = data,  :
    variable lengths differ (found for 'ivreg.2.a$residuals')

Here is the code I am trying to run for reference, let me know if you need any more details. I really just need my residual vector to be the same length as the data used in the first 2SLS. For reference my data has 1713 observations, however, only 1550 get used in the regression and as a result my residuals vector is length 1550. My code for the two 2SLS regressions is below.

ivreg.2.a = plm(formula = diff(loda) ~ factor(year)+diff(lgdp) | index_g_l + diff(lcru_l) + diff(lcru_l_sq) + factor(year), index = c("country", "year"), model = "within", data = panel[complete.cases(panel[, c(1,2,3,4,5,7)]),])

 ivreg.2.a = plm(formula = diff(lgdp) ~ factor(year)+index_g_l + diff(lcru_l) + diff(lcru_l_sq) + diff(loda)| index_g_l + diff(lcru_l) + diff(lcru_l_sq) + factor(year) + ivreg.2.a$residuals, index = c("country", "year"), model = "within", data = panel[complete.cases(panel[, c(1,2,3,4,5,7)]),])

Let me know if you need anything else.

Body:
I assume the 163 observations are dropped because they have NA in one of the relevant variables. Most *lm functions in R have a na.action argument, which can be used to pad the residuals to correct length. E.g., when missing observation 3,

residuals(lm(formula, data, na.action=na.omit)) # 1 2 4
residuals(lm(formula, data, na.action=na.exclude)) # 1 2 NA 4

Documentation of plm, however, says that this argument is "currently not fully supported", so it would be simpler if you just filter those 1550 rows to a new dataframe first, and do all subsequent work on that.

BTW, if plm behaves like lm, you shouldn't need to specify complete.cases for it to work, as it should just skip anything with NAs.


问:
How to validate 8 to 10 digit long phone number?
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

```<code>private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}
</code>```

答: Let's try \\d{8,10} instead of \\d{8-10}

Body:
In my android application, phone number field used. 8 to 10 digit input value given by the user. How to validate  8 to 10 digit phone number using PHONE_REGEX?

I have already tried this method,

private static final String PHONE_REGEX = "\\d{8-10}";

  public static boolean isPhoneNumber(EditText editText, boolean required) {
    return isValid(editText, PHONE_REGEX, PHONE_MSG, required);
}


问:
Understanding overload resolution ranking involving user defined conversion
I am trying to understand overload resolution.

First let's consider this first case:

```<code>struct int1{
   int val;
   operator int&()&{
      return val;
      }
   operator const int &() const&{
      return val;
      }
    };

void f(int &){}       //f#1
void f(const int&){}  //f#2

void test1(){
  int1 x;
  f(x);
   //Conversion sequence for f#1:
   //   - int_wrapper& --> int1::operator int&
   //   => Ranking: user defined conversion rank
   //Converison sequence for f#2:
   //   - int1& --> int1::operator int & --> const int&
   //   - int1& --> const int1 &         --> int1::operator const int&
   //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
   //            => user defined conversion rank
   //
   //=> No best viable overload, 2 user defined conversion rank
}
</code>```

Unlike my wrong analysis, compilers agrees: the call to f is not ambiguous. Why?

Now consider this second case, which is very similar, I just replace the int& by int &&:

```<code>struct int2{
   int val;
   operator int&&()&&{
      return std::move(val);
      }
   operator const int &() const&{
      return val;
      }
    };

void g(int &&){}     // g#1
void g(const int&){} // g#2

void test2(){
  int2 x;
  g(std::move(x));
  //Conversions sequence for g#1
  //   - int2&& --> int2::operator int&&
  //   => Ranking: user defined conversion rank
  //Conversion sequence for g#2
  //   - int2&& --> const int2&           --> int2::operator const int&
  //   - int2&& --> int2::operator int&&  --> const int&
  //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
  //            => user defined conversion rank
  //
  //=> No best viable overload, 2 user defined conversion rank
  }
</code>```

My analysis (which is certainly wrong in this case too) concludes similarly that the call to g is ambiguous. Unfortunatly, in this second case, compilers do not agree:

Clang (3.4.1 to 5.0), MSVC 19 2017 RTW, Zapcc 190308 (Clang derivate), ellcc (0.1.33, 0.1.34)(Clang derivate) => call to g is ambiguous;

GCC (4.8.1 to 7.2), icc (16 to 18) => call to g is not ambiguous.

What is the right analysis and which compiler is right?

Could you precise why the rule below does not apply, or when is it applied?

[over.best.ics]/10:

If several different sequences of conversions exist that each convert the argument to the parameter type, the
  implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence
  designated the
  ambiguous conversion sequence
  . For the purpose of ranking implicit conversion sequences as
  described in 16.3.3.2, the ambiguous conversion sequence is treated as a user-defined conversion sequence
  that is indistinguishable from any other user-defined conversion sequence

答:
N4713 16.3.3.2:

3.3
  User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversionsequence of U1 is better than the second standard conversion sequence of U2.
  [Example

```<code>struct A {
    operator short();
} a;
int f(int);
int f(float);
int i = f(a); // calls f(int), because short→int is // better than short →float
</code>```

end example]

So, standard conversion is the key:

3.2
  Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

3.2.3
  S1 and S2 are reference bindings (11.6.3) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference [ Example:

```<code>int i;
int f1();
int&& f2();
int g(const int&);
int g(const int&&);
int j = g(i); // calls g(const int&)
int k = g(f1()); // calls g(const int&&)
int l = g(f2()); // calls g(const int&&)
struct A {
    A& operator<<(int);
    void p() &;
    void p() &&;
};
A& operator<<(A&&, char);
A() << 1; // calls A::operator<<(int)
A() << ’c’; // calls operator<<(A&&, char)
A a;
a << 1; // calls A::operator<<(int)
a << ’c’; // calls A::operator<<(int)
A().p(); // calls A::p()&&
a.p(); // calls A::p()&
</code>```

end example]

3.2.6:
  S1 and S2 are reference bindings (11.6.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.
  [Example:

```<code>int f(const int &);
int f(int &);
int g(const int &);
int g(int);
int i;
int j = f(i); // calls f(int &)
int k = g(i); // ambiguous
struct X {
    void f() const;
    void f();
};
void g(const X& a, X b) {
    a.f(); // calls X::f() const
    b.f(); // calls X::f()
}
</code>```

— end example]

So gcc meets the standards's requirement.

Body:
I am trying to understand overload resolution.

First let's consider this first case:

struct int1{
   int val;
   operator int&()&{
      return val;
      }
   operator const int &() const&{
      return val;
      }
    };

void f(int &){}       //f#1
void f(const int&){}  //f#2

void test1(){
  int1 x;
  f(x);
   //Conversion sequence for f#1:
   //   - int_wrapper& --> int1::operator int&
   //   => Ranking: user defined conversion rank
   //Converison sequence for f#2:
   //   - int1& --> int1::operator int & --> const int&
   //   - int1& --> const int1 &         --> int1::operator const int&
   //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
   //            => user defined conversion rank
   //
   //=> No best viable overload, 2 user defined conversion rank
}

Unlike my wrong analysis, compilers agrees: the call to f is not ambiguous. Why?

Now consider this second case, which is very similar, I just replace the int& by int &&:

struct int2{
   int val;
   operator int&&()&&{
      return std::move(val);
      }
   operator const int &() const&{
      return val;
      }
    };

void g(int &&){}     // g#1
void g(const int&){} // g#2

void test2(){
  int2 x;
  g(std::move(x));
  //Conversions sequence for g#1
  //   - int2&& --> int2::operator int&&
  //   => Ranking: user defined conversion rank
  //Conversion sequence for g#2
  //   - int2&& --> const int2&           --> int2::operator const int&
  //   - int2&& --> int2::operator int&&  --> const int&
  //   => Ranking: ambiguous because 2 conversion sequence [over.best.ics]/10
  //            => user defined conversion rank
  //
  //=> No best viable overload, 2 user defined conversion rank
  }

My analysis (which is certainly wrong in this case too) concludes similarly that the call to g is ambiguous. Unfortunatly, in this second case, compilers do not agree:

Clang (3.4.1 to 5.0), MSVC 19 2017 RTW, Zapcc 190308 (Clang derivate), ellcc (0.1.33, 0.1.34)(Clang derivate) => call to g is ambiguous;

GCC (4.8.1 to 7.2), icc (16 to 18) => call to g is not ambiguous.

What is the right analysis and which compiler is right?

Could you precise why the rule below does not apply, or when is it applied?

[over.best.ics]/10:

If several different sequences of conversions exist that each convert the argument to the parameter type, the
  implicit conversion sequence associated with the parameter is defined to be the unique conversion sequence
  designated the
  ambiguous conversion sequence
  . For the purpose of ranking implicit conversion sequences as
  described in 16.3.3.2, the ambiguous conversion sequence is treated as a user-defined conversion sequence
  that is indistinguishable from any other user-defined conversion sequence

Body:
N4713 16.3.3.2:

3.3
  User-defined conversion sequence U1 is a better conversion sequence than another user-defined conversion sequence U2 if they contain the same user-defined conversion function or constructor or they initialize the same class in an aggregate initialization and in either case the second standard conversionsequence of U1 is better than the second standard conversion sequence of U2.
  [Example

struct A {
    operator short();
} a;
int f(int);
int f(float);
int i = f(a); // calls f(int), because short→int is // better than short →float

end example]

So, standard conversion is the key:

3.2
  Standard conversion sequence S1 is a better conversion sequence than standard conversion sequence S2 if

3.2.3
  S1 and S2 are reference bindings (11.6.3) and neither refers to an implicit object parameter of a non-static member function declared without a ref-qualifier, and S1 binds an rvalue reference to an rvalue and S2 binds an lvalue reference [ Example:

int i;
int f1();
int&& f2();
int g(const int&);
int g(const int&&);
int j = g(i); // calls g(const int&)
int k = g(f1()); // calls g(const int&&)
int l = g(f2()); // calls g(const int&&)
struct A {
    A& operator<<(int);
    void p() &;
    void p() &&;
};
A& operator<<(A&&, char);
A() << 1; // calls A::operator<<(int)
A() << ’c’; // calls operator<<(A&&, char)
A a;
a << 1; // calls A::operator<<(int)
a << ’c’; // calls A::operator<<(int)
A().p(); // calls A::p()&&
a.p(); // calls A::p()&

end example]

3.2.6:
  S1 and S2 are reference bindings (11.6.3), and the types to which the references refer are the same type except for top-level cv-qualifiers, and the type to which the reference initialized by S2 refers is more cv-qualified than the type to which the reference initialized by S1 refers.
  [Example:

int f(const int &);
int f(int &);
int g(const int &);
int g(int);
int i;
int j = f(i); // calls f(int &)
int k = g(i); // ambiguous
struct X {
    void f() const;
    void f();
};
void g(const X& a, X b) {
    a.f(); // calls X::f() const
    b.f(); // calls X::f()
}

— end example]

So gcc meets the standards's requirement.


问:
Arguments object different to arguments
I've hit a really strange issue, with Node & Express.

I have a middleware function, which can either be invoked in three different ways:

```<code>app.get('/', auth, handler)
app.get('/', auth('role'), handler)
app.get('/', auth('role', 'scope'), handler)
</code>```

The obvious way to do this would be like this:

```<code>exports.auth = (a, b, c) => {

    let role, scope;

    switch(arguments.length) {
        case 3:
            // Called directly by express router
            handleAuth(a, b, c);
            break;

        case 2:
        case 1:
            // Called with role/scope, return handler
            // but don't execute
            role = a;
            scope = b;
            return handleAuth;
    }

    function handleAuth(req, res, next) {

        // Do some custom auth handling, can
        // check here if role/scope is set
        return next();

    }
}
</code>```

However, I'm getting some very odd results for arguments.length. When called in the 2nd way, arguments.length == 5, and none of the arguments is role.

```<code>[ '0': '[object Object]',
  '1': 'function require(path) {\n    try {\n      exports.requireDepth += 1;\n      return mod.require(path);\n    } finally {\n      exports.requireDepth -= 1;\n    }\n  }',
  '2': '[object Object]',
  '3': '/Users/redacted/auth/index.js',
  '4': '/Users/redacted/auth' ]
</code>```

If I log a, b, c within the function, I get a: 'role', b: undefined, c: undefined.

I've tried to reproduce it in Runkit, but haven't had any luck: https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

答:
I think that case is broken.

```<code>'use strict';
let express = require('express');
let app = express();

//app.get('/', auth, handler);
app.get('/', auth('role'), handler);
//app.get('/', auth('role', 'scope'), handler);

function auth (a, b, c) {
    let role;
    if (a == 'role') {
        role = 'user';
        return handleAuth;
    }

    if (a != 'role')
        return handleAuth(a, b, c);

    function handleAuth(req, res, next) {
        console.log(role || 'guest');
        next();
    }
}

function handler (req, res, next) {
    res.send('OK');
}

app.listen(3000, () => console.log('Listening on port 3000'));
</code>```

P.S. Imho, this code is knotty.

Title: Arguments object different to arguments

Body:
I've hit a really strange issue, with Node & Express.

I have a middleware function, which can either be invoked in three different ways:

app.get('/', auth, handler)
app.get('/', auth('role'), handler)
app.get('/', auth('role', 'scope'), handler)

The obvious way to do this would be like this:

exports.auth = (a, b, c) => {

    let role, scope;

    switch(arguments.length) {
        case 3:
            // Called directly by express router
            handleAuth(a, b, c);
            break;

        case 2:
        case 1:
            // Called with role/scope, return handler
            // but don't execute
            role = a;
            scope = b;
            return handleAuth;
    }

    function handleAuth(req, res, next) {

        // Do some custom auth handling, can
        // check here if role/scope is set
        return next();

    }
}

However, I'm getting some very odd results for arguments.length. When called in the 2nd way, arguments.length == 5, and none of the arguments is role.

[ '0': '[object Object]',
  '1': 'function require(path) {\n    try {\n      exports.requireDepth += 1;\n      return mod.require(path);\n    } finally {\n      exports.requireDepth -= 1;\n    }\n  }',
  '2': '[object Object]',
  '3': '/Users/redacted/auth/index.js',
  '4': '/Users/redacted/auth' ]

If I log a, b, c within the function, I get a: 'role', b: undefined, c: undefined.

I've tried to reproduce it in Runkit, but haven't had any luck: https://runkit.com/benedictlewis/5a2a6538895ebe00124eb64e

Body:
I think that case is broken.

'use strict';
let express = require('express');
let app = express();

//app.get('/', auth, handler);
app.get('/', auth('role'), handler);
//app.get('/', auth('role', 'scope'), handler);

function auth (a, b, c) {
    let role;
    if (a == 'role') {
        role = 'user';
        return handleAuth;
    }

    if (a != 'role')
        return handleAuth(a, b, c);

    function handleAuth(req, res, next) {
        console.log(role || 'guest');
        next();
    }
}

function handler (req, res, next) {
    res.send('OK');
}

app.listen(3000, () => console.log('Listening on port 3000'));

P.S. Imho, this code is knotty.


问:
Getting screen coordinates based on triangles
If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite?

I'm writing this in JavaScript and I'm just trying to find the screen coordinates (x/y) where the hypotenuse ends given a length and angle. So, additionally, I need to know how to convert from a cartesian coordinates to screen coordinates.

Sorry, this is probably a pretty dumb question.

Here is a sketch if I'm being unclear:

So something like this:

```<code>function getLineEndCoords(originX, originY, hypotenuse, angle){
    // Probably something to do with tangents and cosines.
    return [x,y]
}
</code>```

Additionally, if anyone knows any good JS libraries for this sort of stuff (isometric drawings, display related math) that would be convenient.

答:
Here you go:

```<code>function getLineEndCoords(originX, originY, hypotenuse, angle){
  return [originX+Math.cos(angle)*hypotenuse,originY-Math.sin(angle)*hypotenuse];
  }
</code>```

The code above has angle relative to the right x axis (as was in your sketch). For example, angle 0 would be number 3 on a clock. Angle PI/2 in radians (90 in degrees) would be 12 o'clock. The function also returns the coordinates as screen coordinates, where Y increases as you go down, not up as on a Cartesian plane.

Please note that the javascript trigonometry functions only accept radians, not degrees. Your angle argument must be in radians. Here is the code to convert from degrees to radians:

```<code>function deg2rad(deg){
  return deg*Math.PI/180;
  }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
If I have the length of the hypotenuse and its angle, how do I find the adjacent and opposite?

I'm writing this in JavaScript and I'm just trying to find the screen coordinates (x/y) where the hypotenuse ends given a length and angle. So, additionally, I need to know how to convert from a cartesian coordinates to screen coordinates.

Sorry, this is probably a pretty dumb question.

Here is a sketch if I'm being unclear:

So something like this:

function getLineEndCoords(originX, originY, hypotenuse, angle){
    // Probably something to do with tangents and cosines.
    return [x,y]
}

Additionally, if anyone knows any good JS libraries for this sort of stuff (isometric drawings, display related math) that would be convenient.

Body:
Here you go:

function getLineEndCoords(originX, originY, hypotenuse, angle){
  return [originX+Math.cos(angle)*hypotenuse,originY-Math.sin(angle)*hypotenuse];
  }

The code above has angle relative to the right x axis (as was in your sketch). For example, angle 0 would be number 3 on a clock. Angle PI/2 in radians (90 in degrees) would be 12 o'clock. The function also returns the coordinates as screen coordinates, where Y increases as you go down, not up as on a Cartesian plane.

Please note that the javascript trigonometry functions only accept radians, not degrees. Your angle argument must be in radians. Here is the code to convert from degrees to radians:

function deg2rad(deg){
  return deg*Math.PI/180;
  }


问:
mockito when method returns null in junit
I have been writing the test cases using the mockito. the below is my code in the test cases.

```<code>@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("akhila.s@cloudium.io");
        userData.setPassword("Passw0rd");

        User userDataNew = new User();
        userDataNew.setUserName("akhila.s@cloudium.io");
        userDataNew.setPassword("Passw0rd");

        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "akhila.s@cloudium.io");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "akhila.s@cloudium.io")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }
</code>```

For the first test case its working fine but for the second test it is returning null always. Can anyone  please help? Thanks in advance

答:
You have the annotations the wrong way round on your LoginController and LoginService.  You are testing the controller so you don't want to mock it, and you are stubbing methods on your service so this needs to be a mock:</p>

```<code> @Mock
 private LoginService loginService;

 @InjectMocks
 private LoginController loginController;
</code>```

Body:
I have been writing the test cases using the mockito. the below is my code in the test cases.

@RunWith(SpringRunner.class)
public class LoginControllerTest {

    private MockMvc mockMvc;

    @InjectMocks
    private LoginService loginService;

    @Mock
    private LoginController loginController;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        // Setup Spring test in standalone mode
        mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();

    }

    @Test
    public final void test() throws Exception {

        // Assign
        when(loginService.test()).thenReturn("hello");

        // act
        mockMvc.perform(get("/hello"))
                // Assertion
                .andExpect(status().isOk())
                .andExpect(content().string("Message from service: hello"));
        verify(loginService).test();
    }

    @Test
    public final void usernameInvalidAndPassword() throws Exception {

        User userData = new User();
        userData.setUserName("akhila.s@cloudium.io");
        userData.setPassword("Passw0rd");

        User userDataNew = new User();
        userDataNew.setUserName("akhila.s@cloudium.io");
        userDataNew.setPassword("Passw0rd");

        JSONObject requestBody = new JSONObject();

        requestBody.put("userName", "akhila.s@cloudium.io");
        requestBody.put("password", "Passw0rd");

        JSONObject responseBody = new JSONObject();

        responseBody.put("status_code", "200");
        responseBody.put("message", "ok");

        // Assign
        when(loginService.saveUser(userData)).thenReturn(userDataNew);

        // act
        mockMvc.perform(get("/login")
                .param("userName", "akhila.s@cloudium.io")
                .param("password", "Passw0rd"))
                // Assertion
                .andExpect(status().isOk()).andExpect(content().json(responseBody.toString())).andDo(print());
    }

For the first test case its working fine but for the second test it is returning null always. Can anyone  please help? Thanks in advance

Body:
You have the annotations the wrong way round on your LoginController and LoginService.  You are testing the controller so you don't want to mock it, and you are stubbing methods on your service so this needs to be a mock:

 @Mock
 private LoginService loginService;

 @InjectMocks
 private LoginController loginController;


问:
Javascript compare arrays to mark occurrences of a specific element
I have an array that contains n arrays that hold a car information (color, company) as follows:

el[0] -> color value

el[1] -> company value

My goal is to show for how many car companies a color can be found.

For example this array

```<code>var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];
</code>```

Should be changed as follows:

```<code> result = [
  ['red', 'Ford', '3: Ford, Renault, Opel'],
  ['blue', 'Ford', '2: Ford, Renault'],
  ['green', 'Ford', '2: Ford, Open'],
  ['red', 'Renault', '3: Ford, Renault, Opel'],
  ['blue', 'Renault', '2: Ford, Renault'],
  ['green', 'Opel', '2: Ford, Opel'],
  ['red', 'Opel', '3: Ford, Renault, Opel']
 ];
</code>```

Explanation:

There are 3 companies having the red color: Ford, Renault, Opel

There are 2 companies having the blue color: Ford, Renault

There are 2 companies having the green color: Ford, Opel

This is how I think it can be solved, but I'm not sure if it's the right approach:

1. Loop through each array and filter the color to get all companies that apply to it

2. Loop through the filter response and remove the duplicates

3. Loop again through the main array and assign the result from step 2 to the corresponding array that has the filtered color

答:
You can approach it like this:

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

// To store calculated counts
var cache = {};

var result = array.map(item => {
  var key = item[0];

  // Do processing only if the item isn't found in cache
  if (!cache[key]) {
    var models = array
      // Get all the same colored items
      .filter(item1 => {
        return item1[0] === key;
      })
      // Get the list of models
      .map(item1 => {
        return item1[1];
      })
      // Extract only the unique values
      .filter((item1, i, arr) => {
        return arr.indexOf(item1) === i;
      });

    // Put the calculation in cache
    if (!cache[key]) {
      cache[key] = `${models.length}: ${models.join(', ')}`;
    }
  }

  // Append the result into original item
  item.push(cache[key]);

  return item;
});

console.log(result);```

I have used an intermediary object cache to save some processing time, since the same operation has to be done a number of times for a color.

Body:
I have an array that contains n arrays that hold a car information (color, company) as follows:

el[0] -> color value

el[1] -> company value

My goal is to show for how many car companies a color can be found.

For example this array

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

Should be changed as follows:

 result = [
  ['red', 'Ford', '3: Ford, Renault, Opel'],
  ['blue', 'Ford', '2: Ford, Renault'],
  ['green', 'Ford', '2: Ford, Open'],
  ['red', 'Renault', '3: Ford, Renault, Opel'],
  ['blue', 'Renault', '2: Ford, Renault'],
  ['green', 'Opel', '2: Ford, Opel'],
  ['red', 'Opel', '3: Ford, Renault, Opel']
 ];

Explanation:

There are 3 companies having the red color: Ford, Renault, Opel

There are 2 companies having the blue color: Ford, Renault

There are 2 companies having the green color: Ford, Opel

This is how I think it can be solved, but I'm not sure if it's the right approach:

1. Loop through each array and filter the color to get all companies that apply to it

2. Loop through the filter response and remove the duplicates

3. Loop again through the main array and assign the result from step 2 to the corresponding array that has the filtered color

Body:
You can approach it like this:

var array = [
  ['red', 'Ford'],
  ['blue', 'Ford'],
  ['green', 'Ford'],
  ['red', 'Ford'],
  ['red', 'Renault'],
  ['blue', 'Renault'],
  ['green', 'Opel'],
  ['red', 'Opel']
];

// To store calculated counts
var cache = {};

var result = array.map(item => {
  var key = item[0];

  // Do processing only if the item isn't found in cache
  if (!cache[key]) {
    var models = array
      // Get all the same colored items
      .filter(item1 => {
        return item1[0] === key;
      })
      // Get the list of models
      .map(item1 => {
        return item1[1];
      })
      // Extract only the unique values
      .filter((item1, i, arr) => {
        return arr.indexOf(item1) === i;
      });

    // Put the calculation in cache
    if (!cache[key]) {
      cache[key] = `${models.length}: ${models.join(', ')}`;
    }
  }

  // Append the result into original item
  item.push(cache[key]);

  return item;
});

console.log(result);

I have used an intermediary object cache to save some processing time, since the same operation has to be done a number of times for a color.


问:
Solrj getBeans() unable to fit response into bean
For the field type text_general getbeans() method returning that field value as ArrayList() but field in pojo is String(While indexing same pojo was used).Also I have multiValued attribute to false.

managed-schema:

<field name="description" type="text_general" indexed="true" stored="true"/>

pojo-field :

```<code>@Field("description")
private String description;
//getter-setter method
</code>```

Java-code:

```<code>SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/audiovideo").build();
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter Serach : ");
    String search = sc.nextLine();
    SolrQuery query = new SolrQuery();
    query.setQuery("description:" + search);
    query.setStart(0);
    QueryResponse response = client.query(query);
    List<AudioVideoPojo> results = response.getBeans(AudioVideoPojo.class);
</code>```

Exception:

```<code>Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class com.mycompany.solrdemo1.AudioVideoPojo
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:71)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBeans(DocumentObjectBinder.java:50)
at org.apache.solr.client.solrj.response.QueryResponse.getBeans(QueryResponse.java:618)
at com.mycompany.solrdemo1.Main.getDataSolrFromDatabase(Main.java:155)
at com.mycompany.solrdemo1.Main.main(Main.java:131)
Caused by: org.apache.solr.client.solrj.beans.BindingException: Exception while setting value : [India International Music Festival] on private java.lang.String com.mycompany.solrdemo1.AudioVideoPojo.description
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:455)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.inject(DocumentObjectBinder.java:438)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:67)

Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field com.mycompany.solrdemo1.AudioVideoPojo.description to java.util.ArrayList
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:449)
</code>```

答: Set multiValued attribute to false.  As per reference guide, it defaults to false for fieldTypes. But it is not honouring the default.

Body:
For the field type text_general getbeans() method returning that field value as ArrayList() but field in pojo is String(While indexing same pojo was used).Also I have multiValued attribute to false.

managed-schema:

<field name="description" type="text_general" indexed="true" stored="true"/>

pojo-field :

@Field("description")
private String description;
//getter-setter method

Java-code:

SolrClient client = new HttpSolrClient.Builder("http://localhost:8983/solr/audiovideo").build();
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter Serach : ");
    String search = sc.nextLine();
    SolrQuery query = new SolrQuery();
    query.setQuery("description:" + search);
    query.setStart(0);
    QueryResponse response = client.query(query);
    List<AudioVideoPojo> results = response.getBeans(AudioVideoPojo.class);

Exception:

Exception in thread "main" org.apache.solr.client.solrj.beans.BindingException: Could not instantiate object of class com.mycompany.solrdemo1.AudioVideoPojo
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:71)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBeans(DocumentObjectBinder.java:50)
at org.apache.solr.client.solrj.response.QueryResponse.getBeans(QueryResponse.java:618)
at com.mycompany.solrdemo1.Main.getDataSolrFromDatabase(Main.java:155)
at com.mycompany.solrdemo1.Main.main(Main.java:131)
Caused by: org.apache.solr.client.solrj.beans.BindingException: Exception while setting value : [India International Music Festival] on private java.lang.String com.mycompany.solrdemo1.AudioVideoPojo.description
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:455)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.inject(DocumentObjectBinder.java:438)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder.getBean(DocumentObjectBinder.java:67)

Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field com.mycompany.solrdemo1.AudioVideoPojo.description to java.util.ArrayList
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:81)
at java.lang.reflect.Field.set(Field.java:764)
at org.apache.solr.client.solrj.beans.DocumentObjectBinder$DocField.set(DocumentObjectBinder.java:449)


问:
How to write a custom templatefield-like DataControlField
I am using a GridView to display data where one of the data columns has type DateTimeOffset. In order to display dates & times in the user's timezone, I save the user's timezone preference to his or her profile (property value key "TimezoneOffset"), and need to access it when formatting dates & times.

If I were to use templatefield, then I would need to write:

```<code><abbr class="datetimeoffset">
<%#
    ((DateTimeOffset)Eval("CreatedDate"))
    .ToOffset(new TimeSpan(-((Int32)Profile.GetPropertyValue("TimezoneOffset"))
                            .ToRepresentativeInRange(-12, 24), 0, 0)).ToString("f") %>
</abbr>
</code>```

which is too complicated and not reusable.

I tried adding a TimeSpan property to the code-behind (to at least move that out of the data binding expression), but apparently properties of the view's code-behind are inaccessible within <%# ... %>.

Therefore, I think that I need to write a custom DataControlField to format dates & times in the user's timezone.

I have started with:

```<code>public class DateTimeOffsetField : DataControlField
{
    private TimeSpan userOffsetTimeSpan;

    protected override DataControlField CreateField()
    {
        return new DateTimeOffsetField();
    }

    protected override void CopyProperties(DataControlField newField)
    {
        base.CopyProperties(newField);
        ((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
    }

    public override bool Initialize(bool sortingEnabled, System.Web.UI.Control control)
    {
        bool ret = base.Initialize(sortingEnabled, control);
        int timezoneOffset = ((Int32)HttpContext.Current.Profile.GetPropertyValue("TimezoneOffset")).ToRepresentativeInRange(-12, 24);
        userOffsetTimeSpan = new TimeSpan(-timezoneOffset, 0, 0);
        return ret;
    }
}
</code>```

But now I am stuck. How do I output the HTML <%# ((DateTimeOffset)Eval("CreatedDate")).ToOffset(userOffsetTimeSpan).ToString("f") %> for each cell?

EDIT: I have been reading an article titled Cutting Edge: Custom Data Control Fields. So far I have added:

```<code>    public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
    {
        base.InitializeCell(cell, cellType, rowState, rowIndex);

        if (cellType == DataControlCellType.DataCell)
        {
            InitializeDataCell(cell, rowState, rowIndex);
        }
    }

    protected virtual void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState, int rowIndex)
    {
        System.Web.UI.Control control = cell;

        if (control != null && Visible)
        {
            control.DataBinding += new EventHandler(OnBindingField);
        }
    }

    protected virtual void OnBindingField(object sender, EventArgs e)
    {
        var target = (System.Web.UI.Control)sender;

        if (target is TableCell)
        {
            TableCell tc = (TableCell)target;
        }
    }
</code>```

but whereas the article sets the Text property of the TableCell instance, I would like to render a partial view into the table cell. Is that possible?

答:
I figured it out. Here is what I ended up with:

```<code>// DateTimeOffsetField.cs
public class DateTimeOffsetField : BoundField
{
    private TimeSpan userOffsetTimeSpan;

    protected override DataControlField CreateField()
    {
        return new DateTimeOffsetField();
    }

    protected override void CopyProperties(DataControlField newField)
    {
        base.CopyProperties(newField);
        ((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
    }

    public override bool Initialize(bool sortingEnabled, System.Web.UI.Control control)
    {
        bool ret = base.Initialize(sortingEnabled, control);
        int timezoneOffset = ((Int32)HttpContext.Current.Profile.GetPropertyValue("TimezoneOffset")).ToRepresentativeInRange(-12, 24);
        userOffsetTimeSpan = new TimeSpan(-timezoneOffset, 0, 0);
        return ret;
    }

    protected override void OnDataBindField(object sender, EventArgs e)
    {
        base.OnDataBindField(sender, e);

        var target = (Control)sender;

        if (target is TableCell)
        {
            var tc = (TableCell)target;
            var dataItem = DataBinder.GetDataItem(target.NamingContainer);
            var dateTimeOffset = (DateTimeOffset)DataBinder.GetPropertyValue(dataItem, DataField);
            tc.Controls.Add(new TimeagoDateTimeOffset { DateTimeOffset = dateTimeOffset.ToOffset(userOffsetTimeSpan) });
        }
    }
}
</code>```

TimeagoDateTimeOffset.cs:

```<code>[DefaultProperty("DateTimeOffset")]
[ToolboxData("<{0}:TimeagoDateTimeOffset runat=server></{0}:TimeagoDateTimeOffset>")]
public class TimeagoDateTimeOffset : WebControl
{
    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public DateTimeOffset DateTimeOffset
    {
        get { return (DateTimeOffset)ViewState["DateTimeOffset"]; }
        set { ViewState["DateTimeOffset"] = value; }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.BeginRender();
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "timeago", false);
        writer.AddAttribute(HtmlTextWriterAttribute.Title, DateTimeOffset.ToString("o"));
        writer.RenderBeginTag("abbr");
        writer.Write(DateTimeOffset.ToString("d"));
        writer.RenderEndTag();
        writer.EndRender();
    }
}
</code>```

Body:
I am using a GridView to display data where one of the data columns has type DateTimeOffset. In order to display dates & times in the user's timezone, I save the user's timezone preference to his or her profile (property value key "TimezoneOffset"), and need to access it when formatting dates & times.

If I were to use templatefield, then I would need to write:

<%#
    ((DateTimeOffset)Eval("CreatedDate"))
    .ToOffset(new TimeSpan(-((Int32)Profile.GetPropertyValue("TimezoneOffset"))
                            .ToRepresentativeInRange(-12, 24), 0, 0)).ToString("f") %>

which is too complicated and not reusable.

I tried adding a TimeSpan property to the code-behind (to at least move that out of the data binding expression), but apparently properties of the view's code-behind are inaccessible within <%# ... %>.

Therefore, I think that I need to write a custom DataControlField to format dates & times in the user's timezone.

I have started with:

public class DateTimeOffsetField : DataControlField
{
    private TimeSpan userOffsetTimeSpan;

    protected override DataControlField CreateField()
    {
        return new DateTimeOffsetField();
    }

    protected override void CopyProperties(DataControlField newField)
    {
        base.CopyProperties(newField);
        ((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
    }

    public override bool Initialize(bool sortingEnabled, System.Web.UI.Control control)
    {
        bool ret = base.Initialize(sortingEnabled, control);
        int timezoneOffset = ((Int32)HttpContext.Current.Profile.GetPropertyValue("TimezoneOffset")).ToRepresentativeInRange(-12, 24);
        userOffsetTimeSpan = new TimeSpan(-timezoneOffset, 0, 0);
        return ret;
    }
}

But now I am stuck. How do I output the HTML <%# ((DateTimeOffset)Eval("CreatedDate")).ToOffset(userOffsetTimeSpan).ToString("f") %> for each cell?

EDIT: I have been reading an article titled Cutting Edge: Custom Data Control Fields. So far I have added:

    public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
    {
        base.InitializeCell(cell, cellType, rowState, rowIndex);

        if (cellType == DataControlCellType.DataCell)
        {
            InitializeDataCell(cell, rowState, rowIndex);
        }
    }

    protected virtual void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState, int rowIndex)
    {
        System.Web.UI.Control control = cell;

        if (control != null && Visible)
        {
            control.DataBinding += new EventHandler(OnBindingField);
        }
    }

    protected virtual void OnBindingField(object sender, EventArgs e)
    {
        var target = (System.Web.UI.Control)sender;

        if (target is TableCell)
        {
            TableCell tc = (TableCell)target;
        }
    }

but whereas the article sets the Text property of the TableCell instance, I would like to render a partial view into the table cell. Is that possible?

Body:
I figured it out. Here is what I ended up with:

// DateTimeOffsetField.cs
public class DateTimeOffsetField : BoundField
{
    private TimeSpan userOffsetTimeSpan;

    protected override DataControlField CreateField()
    {
        return new DateTimeOffsetField();
    }

    protected override void CopyProperties(DataControlField newField)
    {
        base.CopyProperties(newField);
        ((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
    }

    public override bool Initialize(bool sortingEnabled, System.Web.UI.Control control)
    {
        bool ret = base.Initialize(sortingEnabled, control);
        int timezoneOffset = ((Int32)HttpContext.Current.Profile.GetPropertyValue("TimezoneOffset")).ToRepresentativeInRange(-12, 24);
        userOffsetTimeSpan = new TimeSpan(-timezoneOffset, 0, 0);
        return ret;
    }

    protected override void OnDataBindField(object sender, EventArgs e)
    {
        base.OnDataBindField(sender, e);

        var target = (Control)sender;

        if (target is TableCell)
        {
            var tc = (TableCell)target;
            var dataItem = DataBinder.GetDataItem(target.NamingContainer);
            var dateTimeOffset = (DateTimeOffset)DataBinder.GetPropertyValue(dataItem, DataField);
            tc.Controls.Add(new TimeagoDateTimeOffset { DateTimeOffset = dateTimeOffset.ToOffset(userOffsetTimeSpan) });
        }
    }
}

TimeagoDateTimeOffset.cs:

[DefaultProperty("DateTimeOffset")]
[ToolboxData("<{0}:TimeagoDateTimeOffset runat=server></{0}:TimeagoDateTimeOffset>")]
public class TimeagoDateTimeOffset : WebControl
{
    [Bindable(true)]
    [Category("Appearance")]
    [DefaultValue("")]
    [Localizable(true)]
    public DateTimeOffset DateTimeOffset
    {
        get { return (DateTimeOffset)ViewState["DateTimeOffset"]; }
        set { ViewState["DateTimeOffset"] = value; }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {
        writer.BeginRender();
        writer.AddAttribute(HtmlTextWriterAttribute.Class, "timeago", false);
        writer.AddAttribute(HtmlTextWriterAttribute.Title, DateTimeOffset.ToString("o"));
        writer.RenderBeginTag("abbr");
        writer.Write(DateTimeOffset.ToString("d"));
        writer.RenderEndTag();
        writer.EndRender();
    }
}


问:
Quiver plot on a map with python
I am trying to plot coloured vectors onto a map in python 2.7.
I can plot the vectors and their colours with no problem but as soon as I try add the coastline things go wrong. Please help

```<code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.basemap import Basemap

filename = 'wg_weather1_fixed.csv'
readcsv = pd.read_csv(filename)

temp = readcsv.Temperature_degC
wind_speed_kt = readcsv.Wind_Speed_kt
Wind_Direction = readcsv.Wind_Direction
lat = readcsv.Latitude
lon = readcsv.Longitude

Wind_speed_2 = wind_speed_kt*1.852

# extract U and V components
WG_wind_U = Wind_speed_2 * np.sin((360-Wind_Direction)*np.pi/180)
WG_wind_V = -Wind_speed_2*np.cos((360-Wind_Direction)*np.pi/180)

m = Basemap(projection='merc',llcrnrlat=-32.2,urcrnrlat=-29,\
           llcrnrlon=30,urcrnrlon=33,lat_ts=5,resolution='i')

# Create colour bar
norm = matplotlib.colors.Normalize()
norm.autoscale(temp)
cm = matplotlib.cm.CMRmap

sm = matplotlib.cm.ScalarMappable(cmap=cm, norm=norm)
sm.set_array([])

# Plot
q = m.quiver(lon,lat,WG_wind_U,WG_wind_V,color=cm(norm(temp)))

plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.quiverkey(q,0.9, 0.05, 30, r'$30 \frac{Kp}{h}$',labelpos='W',fontproperties={'size': 15,'weight': 'bold'})
cbar = plt.colorbar(sm)

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

Essentially I need to add a coastline to this plot:
enter image description here

答:
```<code>import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.basemap import Basemap

# Read in data from CSV
filename = 'wg_weather1_fixed.csv'
readcsv = pd.read_csv(filename)

temp = readcsv.Temperature_degC
wind_speed_kt = readcsv.Wind_Speed_kt
Wind_Direction = readcsv.Wind_Direction
lat = readcsv.Latitude
lon = readcsv.Longitude

Wind_speed_2 = wind_speed_kt*1.852 # Convert from knots to KpH

# extract U and V components
WG_wind_U = Wind_speed_2 * np.sin((360-Wind_Direction)*np.pi/180)
WG_wind_V = -Wind_speed_2*np.cos((360-Wind_Direction)*np.pi/180)

m = Basemap(projection='merc',llcrnrlat=-30.2,urcrnrlat=-29,\
          llcrnrlon=30.8,urcrnrlon=32.2,lat_ts=5,resolution='i')

# Grid the co-ordinates
X,Y = np.meshgrid(lon,lat)
lons,lats = m(X,Y) # convert the co-ordinates to fit on the map

# Create colour bar
norm = matplotlib.colors.Normalize()
norm.autoscale(temp)
cm = matplotlib.cm.CMRmap # selecting the colourmap

sm = matplotlib.cm.ScalarMappable(cmap=cm, norm=norm)
sm.set_array([])

# Plot
q = m.quiver(lons[0,:],lats[:,0],WG_wind_U,WG_wind_V,color=cm(norm(temp)))

m.fillcontinents(color='#cc9955', zorder = 0)

# Latitudes
parallels = m.drawparallels(np.arange(-30.2,-29.,0.5))
m.drawparallels(parallels,labels=[True,False,False,True])
# Longitudes
meridians = m.drawmeridians(np.arange(30.8,32.2,0.5))
m.drawmeridians(meridians,labels=[True,False,False,True])

#plt.xlabel('Longitude')
#plt.ylabel('Latitude')
plt.quiverkey(q,0.9, 0.05, 30,'30 KpH',labelpos='W')
cbar = plt.colorbar(sm)
cbar.set_label('Air Temperature')
plt.title('Wind velocity shaded by air temperature')

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

Title: Quiver plot on a map with python

Body:
I am trying to plot coloured vectors onto a map in python 2.7.
I can plot the vectors and their colours with no problem but as soon as I try add the coastline things go wrong. Please help

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.basemap import Basemap

filename = 'wg_weather1_fixed.csv'
readcsv = pd.read_csv(filename)

temp = readcsv.Temperature_degC
wind_speed_kt = readcsv.Wind_Speed_kt
Wind_Direction = readcsv.Wind_Direction
lat = readcsv.Latitude
lon = readcsv.Longitude

Wind_speed_2 = wind_speed_kt*1.852

# extract U and V components
WG_wind_U = Wind_speed_2 * np.sin((360-Wind_Direction)*np.pi/180)
WG_wind_V = -Wind_speed_2*np.cos((360-Wind_Direction)*np.pi/180)

m = Basemap(projection='merc',llcrnrlat=-32.2,urcrnrlat=-29,\
           llcrnrlon=30,urcrnrlon=33,lat_ts=5,resolution='i')

# Create colour bar
norm = matplotlib.colors.Normalize()
norm.autoscale(temp)
cm = matplotlib.cm.CMRmap

sm = matplotlib.cm.ScalarMappable(cmap=cm, norm=norm)
sm.set_array([])

# Plot
q = m.quiver(lon,lat,WG_wind_U,WG_wind_V,color=cm(norm(temp)))

plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.quiverkey(q,0.9, 0.05, 30, r'$30 \frac{Kp}{h}$',labelpos='W',fontproperties={'size': 15,'weight': 'bold'})
cbar = plt.colorbar(sm)

plt.show()

Essentially I need to add a coastline to this plot:
enter image description here


问:
xslt generate some result based on the output xml string
Before I detail out my problem, I am currently transforming on xml to another using XSLT. But the thing is I want to know whether it is possible in the xslt sheet to use the resulted xml for some computation.

For instance, if I have the following XSLT,

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/root/metadata">
        <xsl:variable name="_countEmp" select="count(header/employees)" />
        <xsl:variable name="_countCont" select="count(header/employees/Contribution)" />
        <XMLDATA>
            <XMLHEADER>
                <SERVICEID>RTLOAD001</SERVICEID>
                <SOURCE>MOBILE</SOURCE>
                <VERSION>2.0</VERSION>
                <RELEASEDATE>20171101</RELEASEDATE>
                <VALIDFROM>20171101</VALIDFROM>
                <VALIDTO>99991231</VALIDTO>
            </XMLHEADER>
            <FORMRETURNS>
                <FORMMAIN>
                    <B_A_JOB_NO/>
                    <LTP_FLAG>N</LTP_FLAG>
                    <LOGIN_ID/>
                </FORMMAIN>
                <FORMDETAILS>
                    <xsl:choose>
                        <xsl:when test="($_taxtype = 'PACO')">
                            <RETURNDATA>
                                <RETURNDETAILS formtype='PAYEA'>
                                    <B_A_CONTRACT_NO/>
                                    <B_FORMTYPE>X</B_FORMTYPE>
                                    <B_POSTING_REF/>
                                </RETURNDETAILS>
                                <ANNEXDETAILS>
                                    <TABLE tablename="PAYEA_L">
                                        <rows>
                                            <xsl:for-each select="header/employees">
                                                <xsl:choose>
                                                    <xsl:when test="(status = 'N' or (status = 'A' and WithHeldAmount > 0))">
                                                        <row>
                                                            <ZDTL_NID><xsl:value-of select="nidCardNumber" /></ZDTL_NID>
                                                            <ZDTL_LASTNAME><xsl:value-of select="lastName" /></ZDTL_LASTNAME>
                                                            <ZDTL_ONAME><xsl:value-of select="firstName" /></ZDTL_ONAME>
                                                        </row>
                                                    </xsl:when>
                                                </xsl:choose>
                                            </xsl:for-each>
                                        </rows>
                                        <numRows><xsl:value-of select="$_countEmp"/></numRows>
                                    </TABLE>
                                </ANNEXDETAILS>
                            </RETURNDATA>
                        </xsl:when>
                    </xsl:choose>
                </FORMDETAILS>
            </FORMRETURNS>
        </XMLDATA>
    </xsl:template>
</xsl:stylesheet>
</code>```

I would like to know if it is possible not to output the node RETURNDATA, if the rows node is blank.

Thanks,
Ashley

答:
As you have tagged the question as xslt-2.0 I assume you use an XSLT 2.0 processor and then you can of course use a variable at any place to create a temporary tree which you can then process further, so in your XSLT you could for instance create a variable

```<code><xsl:template match="/">
    <xsl:variable name="result1">
      <xsl:apply-templates/>
    </xsl:variable>
</xsl:template>
</code>```

and that way you have the result of processing the primary input in that variable, you simply need to make sure you process it further with e.g.

```<code><xsl:template match="/">
    <xsl:variable name="result1">
      <xsl:apply-templates/>
    </xsl:variable>
    <!-- example computation -->
    <xsl:value-of select="'result has', count($result1//foo), 'foo elements'"/>
</xsl:template>
</code>```

That assumes you have further templates in place to process the primary input. Depending on your existing code it might help to separate processing steps using modes.

As for the sample you have added to your question, it does not seem to be necessary to write two steps, if you add to your condition <xsl:when test="($_taxtype = 'PACO')"> the test you have inside with e.g.

```<code><xsl:when test="($_taxtype = 'PACO') and header/employees[(status = 'N' or (status = 'A' and WithHeldAmount > 0))]">
</code>```

then the RETURNDATA element should only be output if the inner code produces any row elements.

Body:
Before I detail out my problem, I am currently transforming on xml to another using XSLT. But the thing is I want to know whether it is possible in the xslt sheet to use the resulted xml for some computation.

For instance, if I have the following XSLT,

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/root/metadata">
        <xsl:variable name="_countEmp" select="count(header/employees)" />
        <xsl:variable name="_countCont" select="count(header/employees/Contribution)" />
        <XMLDATA>
            <XMLHEADER>
                <SERVICEID>RTLOAD001</SERVICEID>
                <SOURCE>MOBILE</SOURCE>
                <VERSION>2.0</VERSION>
                <RELEASEDATE>20171101</RELEASEDATE>
                <VALIDFROM>20171101</VALIDFROM>
                <VALIDTO>99991231</VALIDTO>
            </XMLHEADER>
            <FORMRETURNS>
                <FORMMAIN>
                    <B_A_JOB_NO/>
                    <LTP_FLAG>N</LTP_FLAG>
                    <LOGIN_ID/>
                </FORMMAIN>
                <FORMDETAILS>
                    <xsl:choose>
                        <xsl:when test="($_taxtype = 'PACO')">
                            <RETURNDATA>
                                <RETURNDETAILS formtype='PAYEA'>
                                    <B_A_CONTRACT_NO/>
                                    <B_FORMTYPE>X</B_FORMTYPE>
                                    <B_POSTING_REF/>
                                </RETURNDETAILS>
                                <ANNEXDETAILS>

                                        <rows>
                                            <xsl:for-each select="header/employees">
                                                <xsl:choose>
                                                    <xsl:when test="(status = 'N' or (status = 'A' and WithHeldAmount > 0))">
                                                        <row>
                                                            <ZDTL_NID><xsl:value-of select="nidCardNumber" /></ZDTL_NID>
                                                            <ZDTL_LASTNAME><xsl:value-of select="lastName" /></ZDTL_LASTNAME>
                                                            <ZDTL_ONAME><xsl:value-of select="firstName" /></ZDTL_ONAME>
                                                        </row>
                                                    </xsl:when>
                                                </xsl:choose>
                                            </xsl:for-each>
                                        </rows>
                                        <numRows><xsl:value-of select="$_countEmp"/></numRows>

                                </ANNEXDETAILS>
                            </RETURNDATA>
                        </xsl:when>
                    </xsl:choose>
                </FORMDETAILS>
            </FORMRETURNS>
        </XMLDATA>
    </xsl:template>
</xsl:stylesheet>

I would like to know if it is possible not to output the node RETURNDATA, if the rows node is blank.

Thanks,
Ashley

Body:
As you have tagged the question as xslt-2.0 I assume you use an XSLT 2.0 processor and then you can of course use a variable at any place to create a temporary tree which you can then process further, so in your XSLT you could for instance create a variable

<xsl:template match="/">
    <xsl:variable name="result1">
      <xsl:apply-templates/>
    </xsl:variable>
</xsl:template>

and that way you have the result of processing the primary input in that variable, you simply need to make sure you process it further with e.g.

<xsl:template match="/">
    <xsl:variable name="result1">
      <xsl:apply-templates/>
    </xsl:variable>
    <!-- example computation -->
    <xsl:value-of select="'result has', count($result1//foo), 'foo elements'"/>
</xsl:template>

That assumes you have further templates in place to process the primary input. Depending on your existing code it might help to separate processing steps using modes.

As for the sample you have added to your question, it does not seem to be necessary to write two steps, if you add to your condition <xsl:when test="($_taxtype = 'PACO')"> the test you have inside with e.g.

<xsl:when test="($_taxtype = 'PACO') and header/employees[(status = 'N' or (status = 'A' and WithHeldAmount > 0))]">

then the RETURNDATA element should only be output if the inner code produces any row elements.


问:
Google Maps: How to add multiple markers to google maps
I searched a lot but didn't get any exact solution for my question with Swift 3 context. I need to plot multiple markers (of type GMSMarker) in my application. My code is as below.

```<code>var markerDict: [Int: GMSMarker] = [:]
var custlatt = [13.093781,13.034893,13.034893]
var custlong = [77.576284,77.596372, 77.596372]

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0...2{
        let camera = GMSCameraPosition.camera(withLatitude:custlatt[i], longitude: custlong[i], zoom: 10.0)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        view = mapView

        markerDict[i] = GMSMarker()
        markerDict[i]?.position = CLLocationCoordinate2D(latitude:custlatt[i], longitude: custlong[i])
        markerDict[i]?.title = "NAGAVARA"
        markerDict[i]?.snippet = "Bengaluru"
        markerDict[i]?.map = mapView
    }
</code>```

Even though I'm using array of marker only one position (last value of custlatt,custlong array) is being marked. Can anyone suggest where I'm going wrong? Or is there any other method of implementation?

答:
Instantiate GmsMapview outside the for loop solve your problem!!!</p>

```<code>class MapVC:UIViewController{

    var markerDict: [String: GMSMarker] = [:]
    var custlatt = [13.093781,13.034893,13.034893]
    var custlong = [77.576284,77.596372, 77.596372]
    var mapView:GMSMapView!

  override func viewDidLoad() {
    super.viewDidLoad()
    mapView = GMSMapView()
    mapView.frame = self.view.frame
    setupViews()
    for (i, element) in (["first","second","third"]).enumerated(){
        let camera = GMSCameraPosition.camera(withLatitude:custlatt[i], longitude: custlong[i], zoom: 10.0)
        mapView.camera = camera

        markerDict[element] = GMSMarker()
        markerDict[element]?.position = CLLocationCoordinate2D(latitude:custlatt[i], longitude: custlong[i])
        markerDict[element]?.title = element
        markerDict[element]?.snippet = element
        markerDict[element]?.map = mapView
}
    }
</code>```

Body:
I searched a lot but didn't get any exact solution for my question with Swift 3 context. I need to plot multiple markers (of type GMSMarker) in my application. My code is as below.

var markerDict: [Int: GMSMarker] = [:]
var custlatt = [13.093781,13.034893,13.034893]
var custlong = [77.576284,77.596372, 77.596372]

override func viewDidLoad() {
    super.viewDidLoad()

    for i in 0...2{
        let camera = GMSCameraPosition.camera(withLatitude:custlatt[i], longitude: custlong[i], zoom: 10.0)
        let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        view = mapView

        markerDict[i] = GMSMarker()
        markerDict[i]?.position = CLLocationCoordinate2D(latitude:custlatt[i], longitude: custlong[i])
        markerDict[i]?.title = "NAGAVARA"
        markerDict[i]?.snippet = "Bengaluru"
        markerDict[i]?.map = mapView
    }

Even though I'm using array of marker only one position (last value of custlatt,custlong array) is being marked. Can anyone suggest where I'm going wrong? Or is there any other method of implementation?

Body:
Instantiate GmsMapview outside the for loop solve your problem!!!

class MapVC:UIViewController{

    var markerDict: [String: GMSMarker] = [:]
    var custlatt = [13.093781,13.034893,13.034893]
    var custlong = [77.576284,77.596372, 77.596372]
    var mapView:GMSMapView!

  override func viewDidLoad() {
    super.viewDidLoad()
    mapView = GMSMapView()
    mapView.frame = self.view.frame
    setupViews()
    for (i, element) in (["first","second","third"]).enumerated(){
        let camera = GMSCameraPosition.camera(withLatitude:custlatt[i], longitude: custlong[i], zoom: 10.0)
        mapView.camera = camera

        markerDict[element] = GMSMarker()
        markerDict[element]?.position = CLLocationCoordinate2D(latitude:custlatt[i], longitude: custlong[i])
        markerDict[element]?.title = element
        markerDict[element]?.snippet = element
        markerDict[element]?.map = mapView
}
    }


问:
Amazon s3: hide a specific bucket to a specific group
I have an amazon S3 account with 2 buckets in them. Lets call them "BUCKET A" and "BUCKET B". I also created a group full of users, lets call it "GROUP1".

I do not understand JSON, but have managed to correctly setup a group policy granting access to the GROUP1 members to:

see (list) all of my buckets in my account (BUCKET A and BUCKET B)

access BUCKET B (double click and see the folders within)

access the user's individual folder within BUCKET B, and upload files there.

When they try to double click any folder but their own, access is denied- awesome!

However, to add one more level of security/increase the user friendy experience, I want to hide BUCKET A from sight altogether, so that upon login the users of the group only see 'BUCKET B' and do not even know that BUCKET A exists.

Can someone offer the correct code for this?

Many thanks in advance.

Leo

答: It is not possible in AWS Console because the API responsible to list all buckets (s3:ListAllMyBuckets) does not support resource level permission hence must be used with resource "*".</p>


问:
Why is numpy.array so slow?
I am baffled by this

```<code>def main():
    for i in xrange(2560000):
        a = [0.0, 0.0, 0.0]

main()

$ time python test.py

real     0m0.793s
</code>```

Let's now see with numpy:

```<code>import numpy

def main():
    for i in xrange(2560000):
        a = numpy.array([0.0, 0.0, 0.0])

main()

$ time python test.py

real    0m39.338s
</code>```

Holy CPU cycles batman!

Using numpy.zeros(3) improves, but still not enough IMHO

```<code>$ time python test.py

real    0m5.610s
user    0m5.449s
sys 0m0.070s
</code>```

numpy.version.version = '1.5.1'

If you are wondering if the list creation is skipped for optimization in the first example, it is not:

```<code>  5          19 LOAD_CONST               2 (0.0)
             22 LOAD_CONST               2 (0.0)
             25 LOAD_CONST               2 (0.0)
             28 BUILD_LIST               3
             31 STORE_FAST               1 (a)
</code>```

答: Of course numpy consumes more time in this case, since: a = np.array([0.0, 0.0, 0.0]) <=~=> a = [0.0, 0.0, 0.0]; a = np.array(a), it took two steps. But numpy-array has many good qualities, its high speed can be seen in the operations on them, not the creation of them. Part of my personal thoughts:).

Title: Why is numpy.array so slow?

Body:
I am baffled by this

def main():
    for i in xrange(2560000):
        a = [0.0, 0.0, 0.0]

main()

$ time python test.py

real     0m0.793s

Let's now see with numpy:

import numpy

def main():
    for i in xrange(2560000):
        a = numpy.array([0.0, 0.0, 0.0])

main()

$ time python test.py

real    0m39.338s

Holy CPU cycles batman!

Using numpy.zeros(3) improves, but still not enough IMHO

$ time python test.py

real    0m5.610s
user    0m5.449s
sys 0m0.070s

numpy.version.version = '1.5.1'

If you are wondering if the list creation is skipped for optimization in the first example, it is not:

  5          19 LOAD_CONST               2 (0.0)
             22 LOAD_CONST               2 (0.0)
             25 LOAD_CONST               2 (0.0)
             28 BUILD_LIST               3
             31 STORE_FAST               1 (a)


问:
boost::priority_queue not compiling
Created a boost::priority_queue with my comparison operation defined. Here is how my priority_queue looks,

```<code>boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > max_heap;
</code>```

My comparison is defined as,

```<code>struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getTime() < rhs->getTime());
    }
};
</code>```

I have used it as,

```<code>myObject* obj1 = static_cast<myObject*>(base1);
</code>```

'base1' is an object of class 'myBase'(base class of myObject)

myObject and getTime() within it used for comparision are defined as,

```<code>class myObject : public myBase {
    Time getTime() const { return time; }
.
.
.
...
}
</code>```

Compiling this gives me this error,

```<code>c:\Projects\pq_test.cpp(27): error C2662: 'void boost::heap::priority_queue<myObject*,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>::push(myObject *const &)' : cannot convert 'this' pointer from 'const boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' to 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_> &'
1>          Conversion loses qualifiers
</code>```

Using Visual Studio 2013 C++. I understand that I am doing something wrong with const correctness, but I am not able to figure out what is wrong. Any help is appreciated.

TIA!

EDIT1:
@Maxim Egorushkin : Thanks!
I saw that,

```<code>myObject* obj1 = static_cast<myObject*>(base1);
</code>```

is in a function which is a const function whose signature is,

```<code>void workOnObj(myBase* base1) const;
</code>```

So, I changed my definition of my priority_queue to const as,

```<code>const boost::heap::priority_queue<Container*, boost::heap::compare<ContainerPtrCompare> > max_heap;
</code>```

and expected that the error would go away, but it still has the same error.

答: The error message says that the code calls non-const priority_queue::push on a const priority_queue object. You need a non-const priority_queue object to be able to call push on it.

Title: boost::priority_queue not compiling

Body:
Created a boost::priority_queue with my comparison operation defined. Here is how my priority_queue looks,

boost::heap::priority_queue<myObject*, boost::heap::compare<myObjectPtrCompare> > max_heap;

My comparison is defined as,

struct myObjectPtrCompare
{
    bool operator()(const myObject* lhs, const myObject* rhs) const
    {
        return (lhs->getTime() < rhs->getTime());
    }
};

I have used it as,

myObject* obj1 = static_cast<myObject*>(base1);

'base1' is an object of class 'myBase'(base class of myObject)

myObject and getTime() within it used for comparision are defined as,

class myObject : public myBase {
    Time getTime() const { return time; }
.
.
.
...
}

Compiling this gives me this error,

c:\Projects\pq_test.cpp(27): error C2662: 'void boost::heap::priority_queue<myObject*,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>::push(myObject *const &)' : cannot convert 'this' pointer from 'const boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_>' to 'boost::heap::priority_queue<myObject *,boost::heap::compare<myObjectPtrCompare>,boost::parameter::void_,boost::parameter::void_,boost::parameter::void_> &'
1>          Conversion loses qualifiers

Using Visual Studio 2013 C++. I understand that I am doing something wrong with const correctness, but I am not able to figure out what is wrong. Any help is appreciated.

TIA!

EDIT1:
@Maxim Egorushkin : Thanks!
I saw that,

myObject* obj1 = static_cast<myObject*>(base1);

is in a function which is a const function whose signature is,

void workOnObj(myBase* base1) const;

So, I changed my definition of my priority_queue to const as,

const boost::heap::priority_queue<Container*, boost::heap::compare<ContainerPtrCompare> > max_heap;

and expected that the error would go away, but it still has the same error.


问:
Eclipse is not recognizing that the ADT plugin for android development is intalled
I'm having a lot of problems trying to get eclipse to recognize that the ADT plugin was installed, which refers to the android development kit.

When I try to go to windows-preferences, nothing related to android appears.  If I try to start a new project, android is not an option.

I've read through this page: http://developer.android.com/sdk/eclipse-adt.html and am still having issues.

Things I've tried:
1. Re-installing eclipse, then re-installing the plugin
2. running eclipse -clean
3. running eclipse as an administrator
4. everything listed here Android ADT Plugin doesn't show up in Eclipse

答:
For some reason, I had trouble installing the plugin with the secure site https://dl-ssl.google.com/android/eclipse/

I had to use the regular http link  http://dl-ssl.google.com/android/eclipse/


问:
Spring Data, JPA @OneToMany Lazy fetch not working in Spring Boot
I have @OneToMany relationship between FabricRoll and FabricDefect.

```<code>@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id", referencedColumnName = "fabric_roll_id")
private Set<FabricDefect> fabricDefects = new HashSet<>();
</code>```

The problem is when I get FabricRoll by JpaRepository function

findAll()

the associate FabricDefect is also loaded.

I want to load only FabricRoll and FabricDefect should load when calling the function getFabricDefect()

FabricRollServiceImpl class

```<code>@Component
public class FabricRollServiceImpl implements IFabricRollService{
    @Autowired
    FabricRollRepository fabricRollRepository;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public List<FabricRoll> getAllFabricRoll() {
        FabricRoll fabricRoll1 = new FabricRoll();
        fabricRoll1.setBatchNo("34344");
        fabricRoll1.setLotNo("425");
        fabricRoll1.setPoNo("42");
        fabricRoll1.setRollLength(2343);
        fabricRoll1.setRollNo("356");
        fabricRoll1.setRollWidth(60);
        fabricRoll1.setStyleNo("354");

        FabricDefect fabricDefect = new FabricDefect();
        fabricDefect.setDefectNote("note");
        fabricDefect.setDefectPoint(3);
        fabricDefect.setSegment(3);
        fabricDefect.setYard(42);

        Set<FabricDefect> fabricDefects = new HashSet<>();
        fabricDefects.add(fabricDefect);

        fabricRoll1.setFabricDefects(fabricDefects);

        addFabricRoll(fabricRoll1);

        FabricRoll fabricRoll = null;

        return fabricRollRepository.findAll();
    }

@Override
public void addFabricRoll(FabricRoll fabricRoll) {
    fabricRollRepository.save(fabricRoll);
}
</code>```

}

Break point:

Console:

答:
I found solution in this tutorial.

You have to modify FabricRoll OneToMany map as below:

```<code>@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fabricRoll")
private Set<FabricDefect> fabricDefects;
</code>```

FabricDefect ManyToOne as below (remember to remove fabric_roll_id field if you included it in your entity):

```<code>@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id")
private FabricRoll fabricRoll;
</code>```

And you don't need to add @Transactional(propagation = Propagation.REQUIRED) before getAllFabricRoll() function.

Body:
I have @OneToMany relationship between FabricRoll and FabricDefect.

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id", referencedColumnName = "fabric_roll_id")
private Set<FabricDefect> fabricDefects = new HashSet<>();

The problem is when I get FabricRoll by JpaRepository function

findAll()

the associate FabricDefect is also loaded.

I want to load only FabricRoll and FabricDefect should load when calling the function getFabricDefect()

FabricRollServiceImpl class

@Component
public class FabricRollServiceImpl implements IFabricRollService{
    @Autowired
    FabricRollRepository fabricRollRepository;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public List<FabricRoll> getAllFabricRoll() {
        FabricRoll fabricRoll1 = new FabricRoll();
        fabricRoll1.setBatchNo("34344");
        fabricRoll1.setLotNo("425");
        fabricRoll1.setPoNo("42");
        fabricRoll1.setRollLength(2343);
        fabricRoll1.setRollNo("356");
        fabricRoll1.setRollWidth(60);
        fabricRoll1.setStyleNo("354");

        FabricDefect fabricDefect = new FabricDefect();
        fabricDefect.setDefectNote("note");
        fabricDefect.setDefectPoint(3);
        fabricDefect.setSegment(3);
        fabricDefect.setYard(42);

        Set<FabricDefect> fabricDefects = new HashSet<>();
        fabricDefects.add(fabricDefect);

        fabricRoll1.setFabricDefects(fabricDefects);

        addFabricRoll(fabricRoll1);

        FabricRoll fabricRoll = null;

        return fabricRollRepository.findAll();
    }

@Override
public void addFabricRoll(FabricRoll fabricRoll) {
    fabricRollRepository.save(fabricRoll);
}

}

Break point:

Console:

Body:
I found solution in this tutorial.

You have to modify FabricRoll OneToMany map as below:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "fabricRoll")
private Set<FabricDefect> fabricDefects;

FabricDefect ManyToOne as below (remember to remove fabric_roll_id field if you included it in your entity):

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fabric_roll_id")
private FabricRoll fabricRoll;

And you don't need to add @Transactional(propagation = Propagation.REQUIRED) before getAllFabricRoll() function.


问:
Get value from json with non unique key in php
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

```<code><?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>
</code>```

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

答:
You can access the variable val1 by:

```<code>$json = '{"key": {"non_unique_name": {"val1": true, "val2": false}}}';
$json_array = json_decode($json);
foreach($json_array as $val)
{
    echo $val->non_unique_name->val1;
}
</code>```

Body:
I have a json object as follows. I need to get val1. I can do this using the following code if I specify the non_unique_name however as the name implied this can change so I am unable to retrieve it.

<?php
$json = '{"key": {"non_unique_name": {"val1": true, "val2": flase}}}';
$array = json_decode( $json, true );
print_r( $array );
$location = $array['key'];
echo $location['non_unique_name']['val1'];
?>

I have tried to access it using echo $location[0]['val1']; however this doesn't work. Would anyone know the correct way to access this?

Body:
You can access the variable val1 by:

$json = '{"key": {"non_unique_name": {"val1": true, "val2": false}}}';
$json_array = json_decode($json);
foreach($json_array as $val)
{
    echo $val->non_unique_name->val1;
}


问:
Decide execution method by Annotation
I need write a code where the method execution will depends of your anotattion. Example:

```<code>public class Example {
    private final Integer LAYOUT = 1;
    public static void main(String... args){
        executeMethod1();
        executeMethod2();
    }

    @Execute(type = LAYOUT, needs = 1)
    executeMethod1(){
        System.out.println("Layout version 1");
    }

    @Execute(type = LAYOUT, needs = 2)
    executeMethod1(){
        System.out.println("Layout version 2");
    }
}
</code>```

And the result must be:

```<code>console: Layout version 1
</code>```

Maybe using AOP?

答:
This goes by reflection. As you will see by a terribly inefficient construct:

```<code>void execute(int needs) {
    for (Method method : Example.class.getDeclaredMethods()) {
        Execute annotation = method.getAnnotation(Execute.class);
        if (annotation != null && annotation.type() == LAYOUT
                && annotation.needs() == needs) {
            method.invoke(this);
            return;
        }
    }
}
</code>```

Other designs would be thinkable, but I have to work too.

Title: Decide execution method by Annotation

Body:
I need write a code where the method execution will depends of your anotattion. Example:

public class Example {
    private final Integer LAYOUT = 1;
    public static void main(String... args){
        executeMethod1();
        executeMethod2();
    }

    @Execute(type = LAYOUT, needs = 1)
    executeMethod1(){
        System.out.println("Layout version 1");
    }

    @Execute(type = LAYOUT, needs = 2)
    executeMethod1(){
        System.out.println("Layout version 2");
    }
}

And the result must be:

console: Layout version 1

Maybe using AOP?

Body:
This goes by reflection. As you will see by a terribly inefficient construct:

void execute(int needs) {
    for (Method method : Example.class.getDeclaredMethods()) {
        Execute annotation = method.getAnnotation(Execute.class);
        if (annotation != null && annotation.type() == LAYOUT
                && annotation.needs() == needs) {
            method.invoke(this);
            return;
        }
    }
}

Other designs would be thinkable, but I have to work too.


问:
code to know wifi is enabled or not and bluetooth is on or not in iphone
Can anybody tell me the code to know wifi is enabled or not and bluetooth is on or not in iphone.

Thanks in advance.

答: Reachability does not seem to differentiate between Bluetooth and WiFi. If you have WiFi off and BT on as in connecting to a peer but not wanting to be connected to WiFi, you'll get an indication that WiFi is actually on when you don't want it to be....e.g. a private peer-to-peer session w/o WiFi interference.</p>


问:
Bootstrap v4 Carousel Not Initializing
Im trying to get a Bootstrap v4 Slider to work.

Its supposed to have text to the right of the slider and this text is meant to change with each slide.

I have added in the required CSS/JS but the slider will not initialize.

Link to JS FIDDLE

My JS:

```<code><script>
        $( document ).ready(function() {
        //set here the speed to change the slides in the carousel
        $('#features').carousel({});

//Loads the html to each slider. Write in the "div id="slide-content-x" what you want to show in each slide
        $('#carousel-text').html($('#slide-content-0').html());

        // When the carousel slides, auto update the text
        $('#features').on('slid.bs.carousel', function (e) {
                 var id = $('.item.active').data('slide-number');
                $('#carousel-text').html($('#slide-content-'+id).html());
        });
});

    </script>
</code>```

答:
looks like your markup in the example is not sufficient.

you have one .carousel-inner div container without .carousel-item inside.
which of course is just one slide.

try to follow the example provided by the bootstrap documentation

put your #slide-content-x containers inside several .carousel-inner div's and remove your JS workaround for that.

you do not need any JS. it's self-initializing.

see my working example here: https://jsfiddle.net/y8h5oqfw/2/

Title: Bootstrap v4 Carousel Not Initializing


问:
OBIEE 11g - Manage Catalog Group (historic data)
I have been using OBIEE 11g for a long time and during that time I have deleted or edited many groups. Is there any .xml file or table in the database that keeps track of this historical data.

How can I learn, who created or edited a particular group?

答:
Unless you have actually backed up your catalog - or at least the /system folders then there is absolutely no way.

That's one reason why Oracle got rid of catalog groups altogehter and dropped them from the product