问:
Retrofit2 Deserialize response body even if response is not 200
I want to be able to deserialize network response to the same Java object even if response is not succesfull. Currently when I get an error response like 403, the response body is null, and I'm expected to use the response.errorBody() method to read whatever has been sent back, which is ok. However I want to avoid having alot of code in the retrofit callbacks just for deserializing errorBody. Instead I want to have an interceptor that sets the content of errorBody into body.

The reason for this is that I have a response object that has fields for both error and non error responses and depending on the status of the response some fields are expected to be left null e.g

Error Response JSON

```<code>{
"locked":true,
"remaining_attempts": 2
}
</code>```

Success Response JSON

```<code>{
"name":"kev"
"token":"abcdefghijklmnopq"
}
</code>```

I have created a single Java object that captures both scenarios:

```<code>class LoginResponse{
    @Expose
    private String name;
    @Expose
    private String token;
    @Expose
    private Boolean locked;
    @Expose
    private Integer remaining_attempts;
}
</code>```

Is there way to do this in an interceptor?

答:
Retrofit is doing the serialization part by delegating it to the Converter, you you can add a specific one to the builder by using builder.addConverterFactory(GsonConverterFactory.create())
and there is already many written Retrofit Converters, you can find most of them here.

so if you want to control this process of deserialization, you can write your custom converter, something like this

```<code>public class UnwrapConverterFactory extends Converter.Factory {

    private GsonConverterFactory factory;

    public UnwrapConverterFactory(GsonConverterFactory factory) {
        this.factory = factory;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(final Type type,
            Annotation[] annotations, Retrofit retrofit) {
        // e.g. WrappedResponse<Person>
        Type wrappedType = new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                // -> WrappedResponse<type>
                return new Type[] {type};
            }

            @Override
            public Type getOwnerType() {
                return null;
            }

            @Override
            public Type getRawType() {
                return WrappedResponse.class;
            }
        };
        Converter<ResponseBody, ?> gsonConverter = factory
                .responseBodyConverter(wrappedType, annotations, retrofit);
        return new WrappedResponseBodyConverter(gsonConverter);
    }
}
</code>```

then you use addConverterFactory() again to tell Retrofit about the new converter.
I should mention that you can use multiple converters in Retrofit which is awesome, it simply check converters by order till find the proper one to use.

resources: writing custom Retrofit converter, using multiple converters

Body:
I want to be able to deserialize network response to the same Java object even if response is not succesfull. Currently when I get an error response like 403, the response body is null, and I'm expected to use the response.errorBody() method to read whatever has been sent back, which is ok. However I want to avoid having alot of code in the retrofit callbacks just for deserializing errorBody. Instead I want to have an interceptor that sets the content of errorBody into body.

The reason for this is that I have a response object that has fields for both error and non error responses and depending on the status of the response some fields are expected to be left null e.g

Error Response JSON

{
"locked":true,
"remaining_attempts": 2
}

Success Response JSON

{
"name":"kev"
"token":"abcdefghijklmnopq"
}

I have created a single Java object that captures both scenarios:

class LoginResponse{
    @Expose
    private String name;
    @Expose
    private String token;
    @Expose
    private Boolean locked;
    @Expose
    private Integer remaining_attempts;
}

Is there way to do this in an interceptor?

Body:
Retrofit is doing the serialization part by delegating it to the Converter, you you can add a specific one to the builder by using builder.addConverterFactory(GsonConverterFactory.create())
and there is already many written Retrofit Converters, you can find most of them here.

so if you want to control this process of deserialization, you can write your custom converter, something like this

public class UnwrapConverterFactory extends Converter.Factory {

    private GsonConverterFactory factory;

    public UnwrapConverterFactory(GsonConverterFactory factory) {
        this.factory = factory;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(final Type type,
            Annotation[] annotations, Retrofit retrofit) {
        // e.g. WrappedResponse<Person>
        Type wrappedType = new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                // -> WrappedResponse<type>
                return new Type[] {type};
            }

            @Override
            public Type getOwnerType() {
                return null;
            }

            @Override
            public Type getRawType() {
                return WrappedResponse.class;
            }
        };
        Converter<ResponseBody, ?> gsonConverter = factory
                .responseBodyConverter(wrappedType, annotations, retrofit);
        return new WrappedResponseBodyConverter(gsonConverter);
    }
}

then you use addConverterFactory() again to tell Retrofit about the new converter.
I should mention that you can use multiple converters in Retrofit which is awesome, it simply check converters by order till find the proper one to use.

resources: writing custom Retrofit converter, using multiple converters


来源: stackexchange

问:
assign Json data to HTML cells
I have a Jquery function which returns Json format string and I would like to assign the Json data to HTML cells. How do I proceed with doing this please? I tried using Json2HTML library but doesn't seem to work for me.

```<code>var jsonData: [{"PlayerName": xxx, "Site": yyy, "Score":zzz},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"}]
</code>```

Default.aspx:

```<code><div style="position: relative; top: 25px; height: 720px">
        <div style="position: relative; height: 720px; width: 710px;">
            <div class="TopScore" style="position: relative; left: 50px">
                <table class="table">
                    <tr>
                        <td class="RankColumn">1</td>
                        <td class="PlayernameColumn"></td>
                        <td class="Site"></td>
                        <td class="Score"></td>
                    </tr>
                </table>
            </div>
            <div class="ScoreBlueBackground" style="position: relative; top: 5px; left: 100px">
                <table class="table">
                    <tr>
                        <td class="rankColumn">2</td>
                        <td class="playername"></td>
                        <td class="siteName"></td>
                        <td class="score"></td>
                    </tr>
                </table>
            </div>
.
.
.
.
.
.
.
            <div class="ScoreBlueBackground" style="position: relative; top: 5px; left: 100px">
                <table class="table">
                    <tr>
                        <td class="rankColumn">20</td>
                        <td class="playername"></td>
                        <td class="siteName"></td>
                        <td class="score"></td>
                    </tr>
                </table>
            </div>
</code>```

答:
One way to do that maybe is using jquery to dynamically build your DOM element.

var jsonData = [
  {"PlayerName": "aaa", "Site": "s11", "Score": "100"},
  {"PlayerName": "bbb", "Site": "s12", "Score": "99"},
  {"PlayerName": "ccc", "Site": "s13", "Score": "34"},
  {"PlayerName": "ddd", "Site": "s14", "Score": "12"},
  {"PlayerName": "eee", "Site": "s15", "Score": "68"}
];

var dom_top_score = $('

');
var dom_score_blue_background = $('

');

for( var i = 0; i < jsonData.length; i++){

  var player_name = jsonData[i].PlayerName;
  var site = jsonData[i].Site;
  var score = jsonData[i].Score;
  var ranking = i + 1;

  var parent_dom = null;
  var dom_table = '

' + ranking + '	' + player_name + '	' + site + '	' + score + '

';

  // TopScore
  if( i == 0){
    parent_dom = dom_top_score.clone();
  }
  // ScoreBlueBackground
  else{
    parent_dom = dom_score_blue_background.clone();
  }

  parent_dom.append(dom_table);
  $('#GameRanking').append(parent_dom);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  width: 90px;
  padding: 5px;
  text-align: center;
}

#GameRanking {

}

.FirstRow, .TopScore, .ScoreBlueBackground {
  margin: 0 0 0 5px;
}

.TopScore {
  color: #fff;
  background: #b01f1f;
}

.ScoreBlueBackground {
  color: #fff;
  background: #054f90;
}</code>```

              Rank
              Player Name
              Site
              Score

```

ContentLicense: CC BY-SA 3.0

Title: assign Json data to HTML cells

Body:
I have a Jquery function which returns Json format string and I would like to assign the Json data to HTML cells. How do I proceed with doing this please? I tried using Json2HTML library but doesn't seem to work for me.

var jsonData: [{"PlayerName": xxx, "Site": yyy, "Score":zzz},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"},
{"PlayerName": "aaa", "site": "yyy", "Score": "zzz"}]

Default.aspx:

                        1

                        2

.
.
.
.
.
.
.

                        20

Body:
One way to do that maybe is using jquery to dynamically build your DOM element.

var jsonData = [
  {"PlayerName": "aaa", "Site": "s11", "Score": "100"},
  {"PlayerName": "bbb", "Site": "s12", "Score": "99"},
  {"PlayerName": "ccc", "Site": "s13", "Score": "34"},
  {"PlayerName": "ddd", "Site": "s14", "Score": "12"},
  {"PlayerName": "eee", "Site": "s15", "Score": "68"}
];

var dom_top_score = $('<div class="TopScore"><div>');
var dom_score_blue_background = $('<div class="ScoreBlueBackground"></div>');

for( var i = 0; i < jsonData.length; i++){

  var player_name = jsonData[i].PlayerName;
  var site = jsonData[i].Site;
  var score = jsonData[i].Score;
  var ranking = i + 1;

  var parent_dom = null;
  var dom_table = '<table class="table"><tr><td class="RankColumn">' + ranking + '</td><td class="PlayernameColumn">' + player_name + '</td><td class="Site">' + site + '</td><td class="Score">' + score + '</td></tr></table>';

  // TopScore
  if( i == 0){
    parent_dom = dom_top_score.clone();
  }
  // ScoreBlueBackground
  else{
    parent_dom = dom_score_blue_background.clone();
  }

  parent_dom.append(dom_table);
  $('#GameRanking').append(parent_dom);
}

td {
  width: 90px;
  padding: 5px;
  text-align: center;
}

#GameRanking {

}

.FirstRow, .TopScore, .ScoreBlueBackground {
  margin: 0 0 0 5px;
}

.TopScore {
  color: #fff;
  background: #b01f1f;
}

.ScoreBlueBackground {
  color: #fff;
  background: #054f90;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="GameRanking" style="position: relative; top: 5px; height: 720px">
  <div class="FirstRow">
      <table class="table">
          <tr>
              <td class="RankColumn">Rank</td>
              <td class="PlayernameColumn">Player Name</td>
              <td class="Site">Site</td>
              <td class="Score">Score</td>
          </tr>
      </table>
  </div>
</div>


问:
Nginx - Do I really need sites-available and sites-enabled folders?
I noticed my install of nginx has three folders called

```<code>etc/nginx/sites-available
etc/nginx/sites-enabled
etc/nginx/conf.d
</code>```

Do I really need these if I just want to work directly in the etc/nginx/nginx.conf file and remove the include lines that include these items in nginx.conf? Are these directories used for anything else that would mess things up if I delete them?

答:
Important information:

You should edit files only in sites-available directory.

Never edit files inside the sites-enabled directory, otherwise you can have problems if your editor runs out of memory or, for any reason, it receives a SIGHUP or SIGTERM.

For example: if you are using nano to edit the file sites-enabled/default and it runs out of memory or, for any reason, it receives a SIGHUP or SIGTERM, then nano will create an emergency file called default.save, inside the sites-enabled directory. So, there will be an extra file inside the sites-enabled directory. That will prevent Apache or NGINX to start. If your site was working, it will not be anymore. You will have a hard time until you find out, in the logs, something related to the default.save file and, then, remove it.

In the example above, if you were editing the file inside the sites-available directory, nothing bad would have happened. The file sites-available/default.save would have been created, but it wouldn't do any harm inside the sites-available directory.

ContentLicense: CC BY-SA 4.0

Body:
I noticed my install of nginx has three folders called

etc/nginx/sites-available
etc/nginx/sites-enabled
etc/nginx/conf.d

Do I really need these if I just want to work directly in the etc/nginx/nginx.conf file and remove the include lines that include these items in nginx.conf? Are these directories used for anything else that would mess things up if I delete them?


问:
JQuery Selector code validation for list of select options
I'm having situation like 3 select box is there in a form

```<code>    <form>
   <select name="select1">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>

<select name="select2">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>
  <select name="select3">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select> </form>
</code>```

On submitting this form i have to check atleast one of the select box value should be "a".

Is there any one line selctor query like jQuery['form'].find('select val=="a"').length() like this .

Thanks,
Nithish.

答:
If I understand you right, and you want to know if at least one selected option has the value of 'a', it should look like

```<code>if( $('form').find('option:selected[value=a]').length ) {
   /*  */
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm having situation like 3 select box is there in a form

    <form>
   <select name="select1">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>

<select name="select2">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select>
  <select name="select3">
 <option value="a">a</option>
 <option value="b">b</option>
 <option value="c">c</option>
 </select> </form>

On submitting this form i have to check atleast one of the select box value should be "a".

Is there any one line selctor query like jQuery['form'].find('select val=="a"').length() like this .

Thanks,
Nithish.

Body:
If I understand you right, and you want to know if at least one selected option has the value of 'a', it should look like

if( $('form').find('option:selected[value=a]').length ) {
   /*  */
}


问:
Ubuntu (14 & 16) Bash errors with printf loops from input containing lowercase "n" characters
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done
</code>```

my script then loops through the file doing the printf statement as follows but this is the output produced

```<code>"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;
</code>```

example contents of myinput.txt

```<code>jetmon
spammen
baidu
</code>```

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

```<code>#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT
</code>```

Tried suggestion from comments using echo

```<code>echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
</code>```

and now I get this output

```<code>-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;
</code>```

Running hexdump -C myinput.txt gives this output

```<code>00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016
</code>```

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done
</code>```

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

```<code>#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1
</code>```

答:
This can happen if the internal field separator ($IFS) contains the letter n:

```<code>$ IFS=$' \t\nn' read line <<< foon
$ printf '%q\n' "$line"
foo
</code>```

This is a fairly common mistake. Here is the correct value:

```<code>$ printf '%q\n' "$IFS"
$' \t\n'
</code>```

Example:

```<code>$ IFS=$' \t\n' read line <<< foon
$ printf '%q\n' "$line"
foon
</code>```

Body:
I have some bash scripts I have been running on Ubuntu 14.04 and 16.04 for well over a year now. Some recent Ubuntu update has broken bash and I cannot figure out how to sort this out.

Example:

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"

cat $INPUT | while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done

my script then loops through the file doing the printf statement as follows but this is the output produced

"~jetmo" 0;
"~spamme" 0;
"~baidu" 0;

example contents of myinput.txt

jetmon
spammen
baidu

Input lines containing a lowercase n character gets stripped out ??
Am I missing some major change in bash that occured, this started happening a week ago and is driving me insane now.

I have tried changing #!/bin/bash to #!/bin/sh with same results.

Also tried this method of looping through the input file and still get the same results.

#!/bin/bash
INPUT=myinput.txt
OUTPUT=myoutput.txt
ACTION1="0;"
while read LINE
do
printf "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT
done < $INPUT

Tried suggestion from comments using echo

echo -e -n "\t\"~${LINE}\"\t\t$ACTION1\n" >> $OUTPUT

and now I get this output

-e -n "~jetmo" 0;
-e -n "~spamme" 0;
-e -n "~baidu" 0;

Running hexdump -C myinput.txt gives this output

00000000  6a 65 74 6d 6f 6e 0a 73  70 61 6d 6d 65 6e 0a 62  |jetmon.spammen.b|
00000010  61 69 64 75 0a 0a                                 |aidu..|
00000016

Also changed all variable names to lowercase as suggested by Michael but still getting the same results.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"

cat $input | while read line
do
printf "\t\"~${line}\"\t\t$action1\n" >> $output
done

THE SOLUTION
The Mystery is Solved

thanks to everyone, but https://stackoverflow.com/users/96588/l0b0 nailed it on the head. I had an IFS=$'\n' hiding earlier on in my script.

I now have this final, better and safer formatting of printf thanks to the recommendations of Nahuel and Charles and it is working 100% ... cannot thank you all enough.

#!/bin/bash
input=myinput.txt
output=myoutput.txt
action1="0;"
while IFS= read -r LINE
do
printf '\t"~%s"\t\t%s\n' "${LINE}" "$ACTION1" >> "$output"
done < $input1

Body:
This can happen if the internal field separator ($IFS) contains the letter n:

$ IFS=$' \t\nn' read line <<< foon
$ printf '%q\n' "$line"
foo

This is a fairly common mistake. Here is the correct value:

$ printf '%q\n' "$IFS"
$' \t\n'

Example:

$ IFS=$' \t\n' read line <<< foon
$ printf '%q\n' "$line"
foon


问:
Getting the exception like "Cannot convert value '0000-00-00 00:00:00' from column 12 to TIMESTAMP"
Previously the column Data type is Date now I am changed to Timestamp
Now if I tried to run the program am getting them  exception

java.sql.SQLException: Cannot convert value '0000-00-00 00:00:00' from column 12 to TIMESTAMP.
 at com.mysql.jdbc.ResultSetRow.getTimestampFast(ResultSetRow.java:1298)
 at com.mysql.jdbc.ByteArrayRow.getTimestampFast(ByteArrayRow.java:124)
 at com.mysql.jdbc.ResultSetImpl.getTimestampInternal(ResultSetImpl.java:6610)
 at com.mysql.jdbc.ResultSetImpl.getTimestamp(ResultSetImpl.java:5928)
 at com.mysql.jdbc.ResultSetImpl.getTimestamp(ResultSetImpl.java:5966)
 at org.hibernate.type.TimestampType.get(TimestampType.java:30)
 at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:163)
 at org.hibernate.type.NullableType.nullSafeGet(NullableType.java:154)
 at org.hibernate.type.AbstractType.hydrate(AbstractType.java:81)
 at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2096)
 at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1380)
 at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1308)
 at org.hibernate.loader.Loader.getRow(Loader.java:1206)
 at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:580)
 at org.hibernate.loader.Loader.doQuery(Loader.java:701)
 at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
 at org.hibernate.loader.Loader.doList(Loader.java:2220)
 ... 40 more

答:
I'm going to take a wild guess here that you're using MySQL :-) It uses "zero dates" as special placeholder - unfortunatelly, JDBC can not handle them by default.

The solution is to specify "zeroDateTimeBehavior=convertToNull" as parameter to your MySQL connection (either in datasource URL or as an additional property), e.g.:

```<code>jdbc:mysql://localhost/myDatabase?zeroDateTimeBehavior=convertToNull
</code>```

This will cause all such values to be retrieved as NULLs.

Body:
I'm going to take a wild guess here that you're using MySQL :-) It uses "zero dates" as special placeholder - unfortunatelly, JDBC can not handle them by default.

The solution is to specify "zeroDateTimeBehavior=convertToNull" as parameter to your MySQL connection (either in datasource URL or as an additional property), e.g.:

jdbc:mysql://localhost/myDatabase?zeroDateTimeBehavior=convertToNull

This will cause all such values to be retrieved as NULLs.


问:
Parsing wrapped attributes with jaxb
Given something like:

```<code><root>
    <wrapper>
        <wrapped id="..."/>
        <wrapped id="..."/>
    </wrapper>
</root>
</code>```

how can I map it to this POJO:

```<code>public class Root {
    public Set<UUID> myIds = new LinkedHashSet();
}
</code>```

I am wondering since @XmlElement( name = "wrapped" ) @XmlElementWrapper( name = "wrapper" ) works somewhat similar to what I want, is there something to get the attribute?

note: i am not using moxy so as far as I know, I cannot use xpaths. I am trying to avoid the @XmlJavaTypeAdapter route.

答:
You need to modify your root class a little bit,
so that it will contain a Set<Wrapped> instead of a Set<UUID>.

```<code>@XmlRootElement(name = "root")
public class Root {

    @XmlElementWrapper(name = "wrapper")
    @XmlElement(name = "wrapped")
    public Set<Wrapped> myWrappeds = new LinkedHashSet<>();
}
</code>```

And you need a separate class for the <wrapped> elements.

Surprisingly for me, you don't need an @XmlJavaAdapter for id here, because JAXB already has a built-in converter between java.util.UUID and String.

```<code>public class Wrapped {

    @XmlAttribute(name = "id")
    public UUID id;
}
</code>```

I have checked the above with this XML input file

```<code><root>
    <wrapper>
        <wrapped id="550e8400-e29b-11d4-a716-446655440000"/>
        <wrapped id="550e8400-e29b-11d4-a716-446655440001"/>
    </wrapper>
</root>
</code>```

and this main method which reproduces the original XML:

```<code>public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    File file = new File("root.xml");
    Root root = (Root) unmarshaller.unmarshal(file);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
}
</code>```

Title: Parsing wrapped attributes with jaxb

Body:
Given something like:

<root>
    <wrapper>
        <wrapped id="..."/>
        <wrapped id="..."/>
    </wrapper>
</root>

how can I map it to this POJO:

public class Root {
    public Set<UUID> myIds = new LinkedHashSet();
}

I am wondering since @XmlElement( name = "wrapped" ) @XmlElementWrapper( name = "wrapper" ) works somewhat similar to what I want, is there something to get the attribute?

note: i am not using moxy so as far as I know, I cannot use xpaths. I am trying to avoid the @XmlJavaTypeAdapter route.

Body:
You need to modify your root class a little bit,
so that it will contain a Set<Wrapped> instead of a Set<UUID>.

@XmlRootElement(name = "root")
public class Root {

    @XmlElementWrapper(name = "wrapper")
    @XmlElement(name = "wrapped")
    public Set<Wrapped> myWrappeds = new LinkedHashSet<>();
}

And you need a separate class for the <wrapped> elements.

Surprisingly for me, you don't need an @XmlJavaAdapter for id here, because JAXB already has a built-in converter between java.util.UUID and String.

public class Wrapped {

    @XmlAttribute(name = "id")
    public UUID id;
}

I have checked the above with this XML input file

<root>
    <wrapper>
        <wrapped id="550e8400-e29b-11d4-a716-446655440000"/>
        <wrapped id="550e8400-e29b-11d4-a716-446655440001"/>
    </wrapper>
</root>

and this main method which reproduces the original XML:

public static void main(String[] args) throws Exception {
    JAXBContext context = JAXBContext.newInstance(Root.class);
    Unmarshaller unmarshaller = context.createUnmarshaller();
    File file = new File("root.xml");
    Root root = (Root) unmarshaller.unmarshal(file);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(root, System.out);
}


问:
SEO Optimalization performance , which method ? (ASP.NET Routing)
I'm trying to figure out which type of seo i will use for my site. I'm using asp.net routing (webforms) with an sql 2005 database.

I want to show my urls like:
http://www.domain.com/article-category/article-title-of-current-page

This means I need to query my category and article by it's title (well, systemtitle column). The systemtitles columns are an indexed varchar(255) column.

Does anyone have done this the similar way and if so, did u notice any performance decrease by using this method? I can always opt-in for the /2-article-category/243-article-title-of-current-page and then query by id but I was hoping to avoid that so the urls look really clean.

I've read some things about this topic before and some say the performance impact is very little when the columns are indexed while others say it will make a huge impact. For now it's not important but if the site grows it should not suffer too much from it.

Any tips/advice is welcome.

Thank you for your time.

Kind regards,
Mark

答:
I dont think its somthing to worry about, a query on "where Title = 'abc'" wont be hugley differant to a query on 'where ID = x'

However, I'd advise not using LIKE as that may hinder performance.

Check this out.

SQL SELECT speed int vs varchar

Edit: While the above is true, I really dont think its going to be a problem. We are talking such small amounts of time on decent hardware.

Infact I'm working on some benchmarks now.


问:
How can I force browsers to print background images in CSS?
This question was asked before but the solution is not applicable in my case. I want to make sure certain background images are printed because they are integral to the page. (They are not images directly in the page because there are several of them being used as CSS sprites.)

Another solution on that same question suggests using list-style-image, which only works if you have a different image for every icon, no CSS sprites possible.

Aside from creating a separate page with the icons inline, is there another solution?

答:
Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this.
Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari 6 – 15.3, Edge */
    color-adjust: exact !important;                 /* Firefox 48 – 96 */
    print-color-adjust: exact !important;           /* Firefox 97+, Safari 15.4+ */
}
```


问:
How to get hidden input value with JSoup?
I have data

```<code><input name="authenticity_token" type="hidden" value="aiUlw1Yh4W47lPQearSEdTkU0rhKpziZOweq5PMTV0Q=" />
</code>```

I am trying to select it with Jsoup.

```<code> Element input = doc.select("input[name=authenticity_token]").first();

 String auth_token = input.attr("value");
</code>```

But this not working.

I am recieving a null pointer exception at String auth_token =.

java.lang.NullPointerException at crime.ic.Main.main(Main.java:2)

What am I doing wrong?

答:
After some researching, I think I know what happens here: the content you want to load may come from some JavaScript and is not visible/existent upon page loading. The loading of JS happens afterwards and fills data in place, and this is not Jsoup can do. So it is beyond reach of Jsoup.

What we need is simulate/automated the loading of JS. Such tools exist.

I found this answer and this question helpful.

Body:
I have data

<input name="authenticity_token" type="hidden" value="aiUlw1Yh4W47lPQearSEdTkU0rhKpziZOweq5PMTV0Q=" />

I am trying to select it with Jsoup.

 Element input = doc.select("input[name=authenticity_token]").first();

 String auth_token = input.attr("value");

But this not working.

I am recieving a null pointer exception at String auth_token =.

java.lang.NullPointerException at crime.ic.Main.main(Main.java:2)

What am I doing wrong?


问:
Connect, update and close connection to MySQL from VBA
I am trying to connect to MySQL using VBA, in order to write the results produced in Excel. I need to write thousands of rows each containing around 100 columns. So I have created separate subroutines to connect to MySQL before I start writing the results, then for each row, I need to run an 'insert' query and in the end, I need to close the connection.

I have created the following subs which I am calling from my main program:

```<code>sub main
    dbconnect
    for i = 1 to 50000
         dbupdate
    next i
    dbclose

sub dbconnect()
    Dim cn as ADODB.connection
    Set cn = New ADODB.Connection
    cn.open "Driver .............." (usual stuff)

sub dbupdate()
    dim sqlstr as string
    sqlstr = "insert into table " .... (some query to write the results in a table)
    cn.execute sqlstr

sub dbclose()
    cn.close
    cn = nothing
</code>```

However, my macro doesn't seem to understand cn when it appears in the dbupdate or dbclose subroutines. It seems that the connection I had set up in dbconnect is not accessible to other subroutines. The macro stops at cn.execute sqlstr in dbupdate with the following error: runtime error 91: object variable or with block variable note set.

Is there a way I can make this work?

Many thanks!

答:
You're declaring your connection object within the dbconnect() sub.
That means that connection will cease to exist after that sub ends executing.
To fix this, make it a publicly declared variable outside of any sub:</p>

```<code>Public cn as ADODB.connection 'Declare it here!!!

Sub main()
    dbconnect
    for i = 1 to 50000
         dbupdate
    next i
    dbclose
    '....
End Sub
Sub dbconnect()
    Set cn = New ADODB.Connection
    cn.open "Driver .............." (usual stuff)
    '....
End Sub
Sub dbupdate()
    dim sqlstr as string
    sqlstr = "insert into table " .... (some query to write the results in a table)
    cn.execute sqlstr
End Sub
Sub dbclose()
    cn.close
    Set cn = nothing 'Use set keyword!
End Sub
</code>```

Body:
I am trying to connect to MySQL using VBA, in order to write the results produced in Excel. I need to write thousands of rows each containing around 100 columns. So I have created separate subroutines to connect to MySQL before I start writing the results, then for each row, I need to run an 'insert' query and in the end, I need to close the connection.

I have created the following subs which I am calling from my main program:

sub main
    dbconnect
    for i = 1 to 50000
         dbupdate
    next i
    dbclose

sub dbconnect()
    Dim cn as ADODB.connection
    Set cn = New ADODB.Connection
    cn.open "Driver .............." (usual stuff)

sub dbupdate()
    dim sqlstr as string
    sqlstr = "insert into table " .... (some query to write the results in a table)
    cn.execute sqlstr

sub dbclose()
    cn.close
    cn = nothing

However, my macro doesn't seem to understand cn when it appears in the dbupdate or dbclose subroutines. It seems that the connection I had set up in dbconnect is not accessible to other subroutines. The macro stops at cn.execute sqlstr in dbupdate with the following error: runtime error 91: object variable or with block variable note set.

Is there a way I can make this work?

Many thanks!

Body:
You're declaring your connection object within the dbconnect() sub.
That means that connection will cease to exist after that sub ends executing.
To fix this, make it a publicly declared variable outside of any sub:

Public cn as ADODB.connection 'Declare it here!!!

Sub main()
    dbconnect
    for i = 1 to 50000
         dbupdate
    next i
    dbclose
    '....
End Sub
Sub dbconnect()
    Set cn = New ADODB.Connection
    cn.open "Driver .............." (usual stuff)
    '....
End Sub
Sub dbupdate()
    dim sqlstr as string
    sqlstr = "insert into table " .... (some query to write the results in a table)
    cn.execute sqlstr
End Sub
Sub dbclose()
    cn.close
    Set cn = nothing 'Use set keyword!
End Sub


问:
Hide Add button From Grid
I would like to completely hide the Add button in a grid (using Acumatica Framework). I know how to disable it using AllowInsert false, but I would like to hide it completely? Is that possible please?</p>

答:
Let's assume that for some reasons you want to hide Add button from Sales Order Details Grid. For achieving this you should do the following:

1. Add Sales Orders screeen to Customization's Screens. You can do it by clicking Add Screen -> Customize Existing Screen and selecting Sales Orders screen in the appeared Smart Panel.

2. Now you should go to the Tab->Document Details->Grid:Transactions and select Properties in the panel on the Right open Action Bar -> Actions-> Add New and set Enabled to false.

Now publish your customization. As a result you will get the following:

Title: Hide Add button From Grid


问:
'$' was used before it was defined .hover
I'm trying to get a background gif to play when I hover over a link, and reset and play as you hover over it again.

It works exactly as I want it in this jsFiddle.

When I write my code up in Brackets I get this warning -> $' was used before it was defined.    $("#hover").hover(function () {

I have included the Javascript in the head of my HTML like:

```<code><head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="main.js"></script>

<head>
</code>```

The HTML, CSS and JavaScript are the same as in the jsFiddle.

Checked in browser also, doesn't work. i get this warning ---> imain.js:10 Uncaught ReferenceError: $ is not defined at main.js:10 My page in its entirety can be seen here. jepen84.github.io/github.io

答:
You get the error because jQuery does not load.

To load jQuery, you used:

jQuery is not a programming language. It's solely a javascript library providing some convenient features.

In your

Body:
I'm trying to get a background gif to play when I hover over a link, and reset and play as you hover over it again.

It works exactly as I want it in this jsFiddle.

When I write my code up in Brackets I get this warning -> $' was used before it was defined.    $("#hover").hover(function () {

I have included the Javascript in the head of my HTML like:

The HTML, CSS and JavaScript are the same as in the jsFiddle.

Checked in browser also, doesn't work. i get this warning ---> imain.js:10 Uncaught ReferenceError: $ is not defined at main.js:10 My page in its entirety can be seen here. jepen84.github.io/github.io

Body:
You get the error because jQuery does not load.

To load jQuery, you used:
<script type="text/jquery" src="jquery-3.2.1.js"></script>

jQuery is not a programming language. It's solely a javascript library providing some convenient features.

In your <script>-tag, change type="text/jquery" to type="text/javascript" and it will load the file.


问:
url structure for mobile/desktop site
What are the pros and cons of these url formats for a website that does mobile and desktop content...

mobile.example.com

example.com/mobile

no explicit url, but send back dynamic content based on browser, or querystring variable?

thanks

答:
W3 recommends "When accessing site entry points users should not have to enter a filename as part of the URI. If possible, configure Web sites so that they can be accessed without having to specify a sub-domain as part of the URI."

So m.example.com or example.com/m would be best solution

Title: url structure for mobile/desktop site


问:
Data factory create hdinsight on-demand cluster fails
I have come upon two major issues trying to make my datafactory implementation work.

This is the first error message i received:

```<code>Failed to create cluster. HttpCode:PreClusterCreationValidationFailure, Error message: Pre cluster creation validation failed for cluster d4755ccc6-e9d5-4ad3-922e-225a3a2911ff due to user error. Validation Report: HdInsight supports only general-purpose storage accounts with standard tier. Make sure that the account is not a premium or blob only storage account. Information about various storage accounts can be found at go.microsoft.com/fwlink/?LinkId=808302 Exception: An exception has occurred: The remote server returned an error: (501) Not Implemented.
</code>```

This error returned over and over again, but today I got a new error:

```<code>Unknown error in module: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: 'authority' Uri should have at least one segment in the path (i.e. https //<host>/<path>/...) Parameter name: authority
</code>```

So my question is what is really going on here? All these errors I have found in the Data factory Monitor.

Regards

Erik

答:
To answer your first error check out this question:

How to create Azure on demand HD insight Spark cluster using Data Factory

Not sure about your second error.

Body:
I have come upon two major issues trying to make my datafactory implementation work.

This is the first error message i received:

Failed to create cluster. HttpCode:PreClusterCreationValidationFailure, Error message: Pre cluster creation validation failed for cluster d4755ccc6-e9d5-4ad3-922e-225a3a2911ff due to user error. Validation Report: HdInsight supports only general-purpose storage accounts with standard tier. Make sure that the account is not a premium or blob only storage account. Information about various storage accounts can be found at go.microsoft.com/fwlink/?LinkId=808302 Exception: An exception has occurred: The remote server returned an error: (501) Not Implemented.

This error returned over and over again, but today I got a new error:

Unknown error in module: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ArgumentException: 'authority' Uri should have at least one segment in the path (i.e. https //<host>/<path>/...) Parameter name: authority

So my question is what is really going on here? All these errors I have found in the Data factory Monitor.

Regards

Erik


问:
Input field validation for two numbers
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

```<code><input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
</code>```

答:
You have can use several ways

The first one is to change the input type to number

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {

 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="number" ng-model="num1" placeholder="num1">
      <input name="num2" type="number" ng-model="num2" placeholder="num2">
      <span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div></code>```

Another is to use the input as text and associate a controller function to ng-show so that it compares the integer and not the string values

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {
    $scope.checkNum = function(){
      return parseInt($scope.num1) > parseInt($scope.num2)
 }
 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="text" ng-model="num1" placeholder="num1">
      <input name="num2" type="text" ng-model="num2" placeholder="num2">
      <span ng-show="checkNum()">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div></code>```

Title: Input field validation for two numbers

Body:
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
num2">Num2 cannot be lesser than num1

Body:
You have can use several ways

The first one is to change the input type to number

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {

 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="number" ng-model="num1" placeholder="num1">
      <input name="num2" type="number" ng-model="num2" placeholder="num2">
      <span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div>

Another is to use the input as text and associate a controller function to ng-show so that it compares the integer and not the string values

 var app = angular.module("Demo", []);
 app.controller("AppController", function($scope) {
    $scope.checkNum = function(){
      return parseInt($scope.num1) > parseInt($scope.num2)
 }
 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div ng-app="Demo">
  <div ng-controller="AppController">
    <div ng-form="regForm">
      <input name="num1" type="text" ng-model="num1" placeholder="num1">
      <input name="num2" type="text" ng-model="num2" placeholder="num2">
      <span ng-show="checkNum()">Num2 cannot be lesser than num1</span>
    </div>
  </div>
</div>


问:
Model serilize hash turned from hash to string when saving object
ruby 2.3.3, rails 3.2.22.5

Hi. I'm using a serialized :logs, Hash in a User model, when saving the logs hash- afterwards it's being retrieved as string instead of Hash.

How it happen:

assign value to logs hash

save user object

now logs hash is a string..

So for user when assigning value to logs hash: user.logs[2] = 4, then saving

```<code>class User < ActiveRecord::Base
  serialize :logs, Hash # in database it's a text type
end
</code>```

An example in the rails console:

```<code># rails console
test_user_id = 3
user = User.find(test_user_id)
user.logs = {}
user.save

user.logs # => {} # great
User.find(test_user_id).logs # => {} # great
# now trying to add value and save:

# 1. assign value to logs hash
user.logs[Time.now] = {:field_id=>6} # => {:field_id=>6}
# 2. save user object:
user.save
# 3. now logs hash is a string..
user.logs
#=> "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"
# why it turned to string ?!?!

User.find(test_user_id).logs # same here:
# => "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"
</code>```

Any ideas?

答:
Ok. so (As I understand it) Rails version: 3.2.22.5 is compatible with ruby 2.2.x but not ruby 2.3.x

So fixed it by reverting from ruby 2.3.3 to ruby 2.2.6

Body:
ruby 2.3.3, rails 3.2.22.5

Hi. I'm using a serialized :logs, Hash in a User model, when saving the logs hash- afterwards it's being retrieved as string instead of Hash.

How it happen:

assign value to logs hash

save user object

now logs hash is a string..

So for user when assigning value to logs hash: user.logs[2] = 4, then saving

class User < ActiveRecord::Base
  serialize :logs, Hash # in database it's a text type
end

An example in the rails console:

# rails console
test_user_id = 3
user = User.find(test_user_id)
user.logs = {}
user.save

user.logs # => {} # great
User.find(test_user_id).logs # => {} # great
# now trying to add value and save:

# 1. assign value to logs hash
user.logs[Time.now] = {:field_id=>6} # => {:field_id=>6}
# 2. save user object:
user.save
# 3. now logs hash is a string..
user.logs
#=> "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"
# why it turned to string ?!?!

User.find(test_user_id).logs # same here:
# => "---\n2017-07-03 19:33:34.938364000 +03:00:\n  :field_id: 6\n"

Any ideas?


问:
Adding a Tileset from mapbox into my map
I'm new working with mapbox, and recently I want to create a web map. I uploaded a shape into mapbox tilseset cloud, but when I try to add it into a map it doesn't display. This is the code funtion that I'm using:

```<code>        map.on('load', function() {
        map.addLayer({
            'id' : 'Resguardos',
            'type' : 'fill',
            "source" : {
                'type' : 'vector',
                'url' : 'mapbox://fabiofz1990.9lhgml6c',
            },
            'layout' : {},
            'paint' : {
                'fill-color' : '#0044b2',
                'fill-opacity' : 1
            }
        });

    });
</code>```

Thank you

答:
I think to display it you would need to add the tileset data to the style that your are using.

There is an option for that in your mapbox account at: https://www.mapbox.com/studio/tilesets/

Body:
I'm new working with mapbox, and recently I want to create a web map. I uploaded a shape into mapbox tilseset cloud, but when I try to add it into a map it doesn't display. This is the code funtion that I'm using:

        map.on('load', function() {
        map.addLayer({
            'id' : 'Resguardos',
            'type' : 'fill',
            "source" : {
                'type' : 'vector',
                'url' : 'mapbox://fabiofz1990.9lhgml6c',
            },
            'layout' : {},
            'paint' : {
                'fill-color' : '#0044b2',
                'fill-opacity' : 1
            }
        });

    });

Thank you


问:
JaxB Marshaling in camel
I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?

I have the following POJO class

```<code>public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}
</code>```

following is my camel code for jaxb implementation

```<code>JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
    jaxbMarshal.setContextPath("com.test");
    jaxbMarshal.setPartClass("com.test.MyPojo");

from("direct:javaObjects") //this direct having the list of MYPojo Objects
    .marshal(jaxbMarshal)
     .to("src/output");
</code>```

I am getting below exception(I added maven dependency for jaxb in classpath)

```<code>Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat@3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath
</code>```

答:
You can use your pojo with some annotations:</p>

```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="MY-POJO")
@XmlType(propOrder = {"groupId", "memberId", "details"})
public class MyPojo {
@XmlElement(name = "groupId")
private int groupId;
@XmlElement(name = "memberId")
private int memberId;
@XmlElement(name = "details")
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}
</code>```

Title: JaxB Marshaling in camel

Body:
I am new to Apache camel and Jax b concept in java.
I have a list of java objects in a camel queue. I want to Marshall it to an xml with Javs DSL(without using spring).
Could any one guide me to do that?

I have the following POJO class

public class MyPojo {
private int groupId;
private int memberId;
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}

following is my camel code for jaxb implementation

JaxbDataFormat jaxbMarshal = new JaxbDataFormat();
    jaxbMarshal.setContextPath("com.test");
    jaxbMarshal.setPartClass("com.test.MyPojo");

from("direct:javaObjects") //this direct having the list of MYPojo Objects
    .marshal(jaxbMarshal)
     .to("src/output");

I am getting below exception(I added maven dependency for jaxb in classpath)

Failed to create route route4 at: >>> Marshal[org.apache.camel.model.dataformat.JaxbDataFormat@3feb2dda] <<< in route: Route(route4)[[From[direct:javaObjects]] -> [Marshal[org.apa... because of Data format 'jaxb' could not be created. Ensure that the data format is valid and the associated Camel component is present on the classpath

Body:
You can use your pojo with some annotations:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name="MY-POJO")
@XmlType(propOrder = {"groupId", "memberId", "details"})
public class MyPojo {
@XmlElement(name = "groupId")
private int groupId;
@XmlElement(name = "memberId")
private int memberId;
@XmlElement(name = "details")
private String details;
public int getgroupId() {
    return groupId;
}
public void setgroupId(int groupId) {
    this.groupId = groupId;
}
public int getMemberId() {
    return memberId;
}
public void setMemberId(int memberId) {
    this.memberId = memberId;
}
public String getdetails() {
    return details;
}
public void setdetails(String details) {
    this.details = details;
}}


问:
Return value after successful assert
I have a little problem with a function used for testing. Here is my test method:

```<code>public static List<FieldError> proofFields(final List<String> fieldNames, final List<FieldError> errors, boolean fieldsAbsent){
    List<FieldError> foundFields = errors.stream().filter(fieldError -> fieldNames.contains(fieldError.getField())).collect(toList());
    if(fieldsAbsent){
        assertTrue(foundFields.isEmpty());
    } else {
        assertTrue(fieldNames.size() == foundFields.size());
    }
    return foundFields;
}
</code>```

It should check, if one list is (partially) contained in the other.

I would like to return the result, no matter if the test was successful or not. Is there a way to do this or does assertTrue/assertFalse always exit immediately?

答:
your method should return value or verify data.Don't mix it. You did it and now you have a problem :)

```<code>public static List<FieldError> proofFields(final List<String> fieldNames, final
       List<FieldError> errors){
         return errors.stream().filter(fieldError ->
       fieldNames.contains(fieldError.getField())).collect(toList());
}

public static assertFieldWithError(final List<String> fieldNames, final
       List<FieldError> errors){
      assertEquals(fieldNames.size(), foundFields.isEmpty());
      ... iterate do more detail and check ....with assertXXXX();
}

public static assertFieldWithoutError(final
       List<FieldError> errors){
      assertTrue(foundFields.isEmpty());
}
</code>```

also for construction like :

```<code>assertTrue(fieldNames.size() == foundFields.size())
</code>```

better use

```<code>assertEquals(fieldsAbsent.size() , foundFields.size());
</code>```

as it more informative way.

Title: Return value after successful assert

Body:
I have a little problem with a function used for testing. Here is my test method:

public static List<FieldError> proofFields(final List<String> fieldNames, final List<FieldError> errors, boolean fieldsAbsent){
    List<FieldError> foundFields = errors.stream().filter(fieldError -> fieldNames.contains(fieldError.getField())).collect(toList());
    if(fieldsAbsent){
        assertTrue(foundFields.isEmpty());
    } else {
        assertTrue(fieldNames.size() == foundFields.size());
    }
    return foundFields;
}

It should check, if one list is (partially) contained in the other.

I would like to return the result, no matter if the test was successful or not. Is there a way to do this or does assertTrue/assertFalse always exit immediately?

Body:
your method should return value or verify data.Don't mix it. You did it and now you have a problem :)

public static List<FieldError> proofFields(final List<String> fieldNames, final
       List<FieldError> errors){
         return errors.stream().filter(fieldError ->
       fieldNames.contains(fieldError.getField())).collect(toList());
}

public static assertFieldWithError(final List<String> fieldNames, final
       List<FieldError> errors){
      assertEquals(fieldNames.size(), foundFields.isEmpty());
      ... iterate do more detail and check ....with assertXXXX();
}

public static assertFieldWithoutError(final
       List<FieldError> errors){
      assertTrue(foundFields.isEmpty());
}

also for construction like :

assertTrue(fieldNames.size() == foundFields.size())

better use

assertEquals(fieldsAbsent.size() , foundFields.size());

as it more informative way.


问:
_wp_old_slug is not working
I have a post that its slug was changed from google-photos to tips-google-photos.
When i try to reach www.example.com/2017/04/07/google-photos it should be redirected to www.example.com/2017/04/07/tips-google-photos but it doesn't and it shows 404 page.
I went throughout my database and I did this query:

```<code>SELECT * FROM `wp_postmeta` WHERE post_id=161154;
</code>```

and found a _wp_old_slug meta_key with this value: google-photos. so the old slug is saved in database, but it seems something is wrong and worpress is not checking the old_slug value in database.

I'd appreciate if somebody can help me.

答:
It won't auto-redirect just by changing the slug (if you have links pointing to .../google-photos, just by updating the slug to tips-google-photos existing links in your site will still point to the original slug - that's why the 404). You can use a redirect plugin to solve the issue.

As for not being able to reach it directly under .../tips-google-photos - to regenerate the permalinks you have to visit Settings > Permalinks (no need to change anything, just hit Save Changes and this will force WP to regenerate all permalinks).

Please try and let me know if that fixed it.

Title: _wp_old_slug is not working

Body:
I have a post that its slug was changed from google-photos to tips-google-photos.
When i try to reach www.example.com/2017/04/07/google-photos it should be redirected to www.example.com/2017/04/07/tips-google-photos but it doesn't and it shows 404 page.
I went throughout my database and I did this query:

SELECT * FROM `wp_postmeta` WHERE post_id=161154;

and found a _wp_old_slug meta_key with this value: google-photos. so the old slug is saved in database, but it seems something is wrong and worpress is not checking the old_slug value in database.

I'd appreciate if somebody can help me.


问:
React Native - Async storage information is extracted after componentWillMount()
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

```<code>constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />
        <Body>
          <Text>{title}</Text>
        </Body>
        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }
</code>```

There is no difference if I put everything in componentWillMount in the constructor.

答:
The return value of an async function is a Promise object. So you have to use then to access the resolved value of getCache. Change your code to the following and it should work.

```<code>  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString();
    this.getCache(key).then(status => {
      this.setState({ isChecked: status === true });
    })
  }
</code>```

Body:
I am storing if a checkbox is checked or not using AsyncStorage. When I reload the app, I see from logs that inside the asynchronous variable the correct information is stored. But, it is loaded after componentWillMount. Because of that, the checkbox does not appear checked, as it should be.

I think a good workaround will be to change the checkbox properties inside the asynchronous function. Do you think that would be a good solution? Do you have other suggestions for showing the correct checkbox value?

My code:

constructor(props) {
    super(props)
    this.state = {isChecked: false}
    this.switchStatus = this.switchStatus.bind(this)
  }

  async getCache(key) {
    try {
      const status = await AsyncStorage.getItem(key);
      if (status == null)
        status = false
      console.log("my async status is " + status)
      return status
    } catch(error) {
      console.log("error", e)
    }
  }

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString()
    this.getCache = this.getCache.bind(this)
    this.setState({isChecked: (this.getCache(key) == 'true')})
    console.log("my state is" + this.state.isChecked)
  }

  switchStatus () {
    const newStatus = this.state.isChecked == false ? true : false
    AsyncStorage.setItem("status_" + this.props.data.id.toString(), newStatus.toString());
    console.log("hi my status is " + newStatus)
    this.setState({isChecked: newStatus})
  }

  render({ data, onPress} = this.props) {
    const {id, title, checked} = data
    return (
      <ListItem button onPress={onPress}>
        <CheckBox
          style={{padding: 1}}
          onPress={(this.switchStatus}
          checked={this.state.isChecked}
        />

          <Text>{title}</Text>

        <Right>
          <Icon name="arrow-forward" />
        </Right>
      </ListItem>
    )
  }

There is no difference if I put everything in componentWillMount in the constructor.

Body:
The return value of an async function is a Promise object. So you have to use then to access the resolved value of getCache. Change your code to the following and it should work.

  componentWillMount(){
    // key string depends on the object selected to be checked
    const key = "status_" + this.props.data.id.toString();
    this.getCache(key).then(status => {
      this.setState({ isChecked: status === true });
    })
  }


问:
How Stuff and 'For Xml Path' work in SQL Server?
Table is:

Id
Name

1
aaa

1
bbb

1
ccc

1
ddd

1
eee

Required output:

Id
abc

1
aaa,bbb,ccc,ddd,eee

Query:

```<code>SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id
</code>```

This query is working properly. But I just need the explanation how it works or is there any other or short way to do this.

I am getting very confused to understand this.

答:
```<code>SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id
</code>```

Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ddd,eee) then it will become (aaa,bbb,ccc,ddd,eee).

And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ddd,eee) string but in PATH we are passing '' so it will not create a XML tag.

And at the end we have grouped records using ID column.

Body:
Table is:

Id
Name

1
aaa

1
bbb

1
ccc

1
ddd

1
eee

Required output:

Id
abc

1
aaa,bbb,ccc,ddd,eee

Query:

SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id

This query is working properly. But I just need the explanation how it works or is there any other or short way to do this.

I am getting very confused to understand this.

Body:
SELECT ID,
    abc = STUFF(
                 (SELECT ',' + name FROM temp1 FOR XML PATH ('')), 1, 1, ''
               )
FROM temp1 GROUP BY id

Here in the above query STUFF function is used to just remove the first comma (,) from the generated xml string (,aaa,bbb,ccc,ddd,eee) then it will become (aaa,bbb,ccc,ddd,eee).

And FOR XML PATH('') simply converts column data into (,aaa,bbb,ccc,ddd,eee) string but in PATH we are passing '' so it will not create a XML tag.

And at the end we have grouped records using ID column.


问:
Windows error LNK1179
I compiled an exe on windows VS 2005, a c++ program that link to other libs of mine.
It compiled and suddenly it doesn't with an error of LNK1170 COMDAT "

I can't understand what happened and how to solve the problem.

Thanks

答:
This is copied from http://msdn.microsoft.com/en-us/library/aa234469(VS.60).aspx

Linker Tools Error LNK1179

Visual Studio 6.0

invalid or corrupt file: duplicate comdat comdat

An object module contained two or more COMDATs with the same name.

One possible cause is if you use the /H option with /Gy. The /H option limits the length of external names, and the /Gy option packages functions in COMDATs.

For example, if you compile the following with /Gy and /H8, you will get error LNK1179 since the object module will contain two COMDATs of the same name (function1 and function2 are unique at nine characters):

```<code>void function1(void);
void function2(void);

void main(void) {
    function1();
    function2();
}

void function1(void) {}
void function2(void) {}
</code>```

Title: Windows error LNK1179

Body:
This is copied from http://msdn.microsoft.com/en-us/library/aa234469(VS.60).aspx

Linker Tools Error LNK1179

Visual Studio 6.0

invalid or corrupt file: duplicate comdat comdat

An object module contained two or more COMDATs with the same name.

One possible cause is if you use the /H option with /Gy. The /H option limits the length of external names, and the /Gy option packages functions in COMDATs.

For example, if you compile the following with /Gy and /H8, you will get error LNK1179 since the object module will contain two COMDATs of the same name (function1 and function2 are unique at nine characters):

void function1(void);
void function2(void);

void main(void) {
    function1();
    function2();
}

void function1(void) {}
void function2(void) {}


问:
Cordova browser opens a different Chrome?
When I use cordova run browser or alternatively cordova run browser --target=chrome the process starts a new Chrome window with a different version Chrome than my default.

<s>On my system I have my regular installation (currently at v58), a Chrome Canary installation (currently at v61) and Cordova opens a new Chrome with v59.</s>
(This weird reporting was probably due to a pending install on my regular Chrome, both regular Chrome and Cordova's opened Chrome are v59)

Why does Cordova not start in a new tab, or why can't I even drag the newly opened window into a tab of my already open regular Chrome?

答:
It's --user-data-dir param that we pass along with chrome.exe, results in the behavior of opening a chrome instance in new window. This feature is incorporated so that user specific data can be kept separately for testing.

This is same reason why you are not able to even drag drop the newly opened window into an already opened instance of chrome. Basically its done to maintain the integrity of individual instances.

The tweak to stop opening new instance of chrome instance(though not recommended unless its really a requirement) is to edit the browser.js file under /Projectroot/platforms/browser/cordova/node_modules/cordova_serve/src folder as you have mentioned in your answer and stop passing the --user-data-dir parameter. Hope it helps. Cheers


问:
Where's the Node.js root on Windows?
Here is my Node.js code (trying to console.log to a file):

```<code>var fs = require('fs');
var util = require('util');

var logFile = fs.createWriteStream('/tmp/test', { flags: 'a' });

// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
    logFile.write(util.format.apply(null, arguments) + '\n');
    logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;
</code>```

My issue: I can't find this mythical /tmp/test folder.

答:
That directory, /tmp/test, does not exist on Windows. It only exists on Linux. Replace it with a path that actually exist on Windows. like C:/file.txt.

You might want to check for permissions and path when you are creating a file.

Title: Where's the Node.js root on Windows?

Body:
Here is my Node.js code (trying to console.log to a file):

var fs = require('fs');
var util = require('util');

var logFile = fs.createWriteStream('/tmp/test', { flags: 'a' });

// Or 'w' to truncate the file every time the process starts.
var logStdout = process.stdout;

console.log = function () {
    logFile.write(util.format.apply(null, arguments) + '\n');
    logStdout.write(util.format.apply(null, arguments) + '\n');
}
console.error = console.log;

My issue: I can't find this mythical /tmp/test folder.


问:
Fit gaussians (or other distributions) on my data using python
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

```<code>data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)
</code>```

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?

答:
Is is always preferred to choose a reduced set of candidate before trying to identify the distribution (in other words, use Cullen & Frey to reject the unlikely candidates) and then go for goodness of fit a select the best result,

You can just create a list of all available distributions in scipy. An example with two distributions and random data:

```<code>import numpy as np
import scipy.stats as st

data = np.random.random(10000)
#Specify all distributions here
distributions = [st.laplace, st.norm]
mles = []

for distribution in distributions:
    pars = distribution.fit(data)
    mle = distribution.nnlf(pars, data)
    mles.append(mle)

results = [(distribution.name, mle) for distribution, mle in
zip(distributions, mles)]
best_fit = sorted(zip(distributions, mles), key=lambda d: d[1])[0]
print 'Best fit reached using {}, MLE value: {}'.format(best_fit[0].name, best_fit[1])
</code>```

Body:
I have a database of features, a 2D np.array (2000 samples and each sample contains 100 features, 2000 X 100). I want to fit gaussian distributions to my database using python. My code is the following:

data = load_my_data() # loads a np.array with size 2000x200
clf = mixture.GaussianMixture(n_components= 50, covariance_type='full')
clf.fit(data)

I am not sure about the parameters for example the covariance_type and how can I investigate whether the fit was occured succesfully or not.

EDIT: I debug the code to investigate what is happening with the clf.means_ and appartently it produced a matrix n_components X size_of_features 50 X 20). Is there a way that i can check that the fitting was successful, or to plot data? What are the alternatives to Gaussian mixtures (mixtures of exponential for example, I cannot find any available implementation)?

Body:
Is is always preferred to choose a reduced set of candidate before trying to identify the distribution (in other words, use Cullen & Frey to reject the unlikely candidates) and then go for goodness of fit a select the best result,

You can just create a list of all available distributions in scipy. An example with two distributions and random data:

import numpy as np
import scipy.stats as st

data = np.random.random(10000)
#Specify all distributions here
distributions = [st.laplace, st.norm]
mles = []

for distribution in distributions:
    pars = distribution.fit(data)
    mle = distribution.nnlf(pars, data)
    mles.append(mle)

results = [(distribution.name, mle) for distribution, mle in
zip(distributions, mles)]
best_fit = sorted(zip(distributions, mles), key=lambda d: d[1])[0]
print 'Best fit reached using {}, MLE value: {}'.format(best_fit[0].name, best_fit[1])


问:
Is form data / authentication / or any other request / response architecture affected by perm redirects?

My application is running on multiple servers.

I would like one of the servers to deal with a specific subset of api requests due to its interaction with cache. This server can be contacted by using the special CMS Url i gave it: Config.CMSUrl

I have the following code:

```<code>public enum ServerType
{
    CMS
}

public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = new Uri($"{Config.CMSUrl}/{filterContext.Request.RequestUri.PathAndQuery}");
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}
</code>```

This should allow developers to add a simple attribute to an API method that will denote exactly where that method needs to run (so any methods that deal with interaction with cache should be directed through the cms server).

Is this method safe to use in order to maintain authentication, form data and any other request/response architecture i may have in place? Or am i possibly risking something here?

My other choice is to ensure that people calling the url in the first place correctly use the CMS Url rather than the normal api url... but my problem with that is the possible maintenance and human error.

答:
Please read this article as well.
When you redirect using your own scheme or url make sure you take care of any query parameters and encoded urls etc being passed. POST params will carry on as normal as they would be part of the request object.</p>

Body:
My application is running on multiple servers.

I would like one of the servers to deal with a specific subset of api requests due to its interaction with cache. This server can be contacted by using the special CMS Url i gave it: Config.CMSUrl

I have the following code:

public enum ServerType
{
    CMS
}

public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = new Uri($"{Config.CMSUrl}/{filterContext.Request.RequestUri.PathAndQuery}");
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}

This should allow developers to add a simple attribute to an API method that will denote exactly where that method needs to run (so any methods that deal with interaction with cache should be directed through the cms server).

Is this method safe to use in order to maintain authentication, form data and any other request/response architecture i may have in place? Or am i possibly risking something here?

My other choice is to ensure that people calling the url in the first place correctly use the CMS Url rather than the normal api url... but my problem with that is the possible maintenance and human error.


问:
How to remove Empty Rows from a list in Python 3.5
```<code>apple
mango
banana

tea

coffee
</code>```

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

```<code>apple
mango
banana
tea
coffee
</code>```

答: i have forgot to check the spaces after last string in the file. After i remove the spaces and bringing the curser just in parallel to the last string, this solves the problem. thanks all.</p>

Body:
apple
mango
banana

tea

coffee

Can someone please suggest a python code to remove the empty rows in this case after banana/tea/coffee so the actual result should be as below without any empty rows in between and after the end of lists

apple
mango
banana
tea
coffee


问:
jQuery custom validation: custom phone number format
I have a form in which you have to input your phone number and other fields.

I'm validating the form with jQuery Validate.

To validate the phone number field I do:

```<code>rules: {
    phone: {
    required: true,
        minlength: 9,
        number:true
    },..
</code>```

But I need to check also that phone starts with 6.

How can I do that?

答:
You can add a custom validator

```<code>jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.match(/^6\d{8,}$/);
}, "Phone number should start with 6");
</code>```

and use it like this:

```<code>rules: {
    phone: {
        required: true,
        minlength: 9,
        phoneEnding6: true
    },..
</code>```

You need to edit the regex inside phone_number.match to suit your requirements.

Body:
I have a form in which you have to input your phone number and other fields.

I'm validating the form with jQuery Validate.

To validate the phone number field I do:

rules: {
    phone: {
    required: true,
        minlength: 9,
        number:true
    },..

But I need to check also that phone starts with 6.

How can I do that?

Body:
You can add a custom validator

jQuery.validator.addMethod("phoneStartingWith6", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, "");
    return this.optional(element) || phone_number.match(/^6\d{8,}$/);
}, "Phone number should start with 6");

and use it like this:

rules: {
    phone: {
        required: true,
        minlength: 9,
        phoneEnding6: true
    },..

You need to edit the regex inside phone_number.match to suit your requirements.


问:
Lost Microstrategy Administrator Password?
In researching this scenario, all I could find was a suggestion that you contact Microstrategy, send them your metadata DB and ask them for the password.

This CAN'T be the only way.

Is there no way to simply reset the password in some fashion?  Looking at the DSSMDUSRACCT table in the metadata DB, this appears to hold (at first glance anyway) a hashed/encrypted password, but I don't believe this is correct, as every entry for every account is the same in the PASSWD field.

Can someone suggest an alternative beyond sending a database to Microstrategy?

答:
You could try using the MicroStrategy Object Manager to copy the Administrator user from another project source/server to this environment.
This should do the trick if you have at least one other user with the right administrative privileges.</p>


问:
Discrete to continuous number ranges via awk
Assume a text file file which contains multiple discrete number ranges, one per line. Each range is preceded by a string (i.e., the range name). The lower and upper bound of each range is separated by a dash. Each number range is succeeded by a semi-colon. The individual ranges are sorted (i.e., range 101-297 comes before 1299-1301) and do not overlap.

```<code>$cat file
foo  101-297;
bar  1299-1301;
baz  1314-5266;
</code>```

Please note that in the example above the three ranges do not form a continuous range that starts at integer 1.

I believe that awk is the appropriate tool to fill the missing number ranges such that all ranges taken together form a continuous range from {1} to {upper bound of the last range}. If so, what awk command/function would you use to perform the task?

```<code>$cat file | sought_awk_command
new1 1-100;
foo  101-297;
new2 298-1298;
bar  1299-1301;
new3 1302-1313;
baz  1314-5266;
</code>```

--

Edit 1: Upon closer evaluation, the code suggested below fails at another simple example.

```<code>$cat example2
foo  101-297;
bar  1299-1301;
baz  1302-1314; # Notice that ranges "bar" and "baz" are continuous to one another
qux  1399-5266;

$ awk -F'[ -]' '$3-Q>1{print "new"++o,Q+1"-"$3-1";";Q=$4} 1' example2
new1 1-100;
foo  101-297;
new2 298-1298;
bar  1299-1301;
baz  1302-1314;
new3 1302-1398; # ERROR HERE: Notice that range "new3" has a lower bound that is equal to upper bound of "bar", not of "baz".
qux  1399-5266;
</code>```

--

Edit 2: Many thanks to RavinderSingh13 for assistance with solving this question. However, the suggested code still generates output inconsistent with the given objective.

```<code>$ cat example3
foo  35025-35144;
bar  35259-35375;
baz  35376-35624;
qux  37911-39434;

$ awk -F'[ -]' '$3-Q+0>=1{print "new"++o,Q+1"-"$3-1";";Q=$4} {Q=$4;print}' example3
new1 1-35024;
foo  35025-35144;
new2 35145-35258;
bar  35259-35375;
new3 35376-35375; # ERROR HERE: Notice that range "new3" has been added, even though ranges "bar" and "baz" are contiguous.
baz  35376-35624;
new4 35625-37910;
qux  37911-39434;
</code>```

Body:
Assume a text file file which contains multiple discrete number ranges, one per line. Each range is preceded by a string (i.e., the range name). The lower and upper bound of each range is separated by a dash. Each number range is succeeded by a semi-colon. The individual ranges are sorted (i.e., range 101-297 comes before 1299-1301) and do not overlap.

$cat file
foo  101-297;
bar  1299-1301;
baz  1314-5266;

Please note that in the example above the three ranges do not form a continuous range that starts at integer 1.

I believe that awk is the appropriate tool to fill the missing number ranges such that all ranges taken together form a continuous range from {1} to {upper bound of the last range}. If so, what awk command/function would you use to perform the task?

$cat file | sought_awk_command
new1 1-100;
foo  101-297;
new2 298-1298;
bar  1299-1301;
new3 1302-1313;
baz  1314-5266;

--

Edit 1: Upon closer evaluation, the code suggested below fails at another simple example.

$cat example2
foo  101-297;
bar  1299-1301;
baz  1302-1314; # Notice that ranges "bar" and "baz" are continuous to one another
qux  1399-5266;

$ awk -F'[ -]' '$3-Q>1{print "new"++o,Q+1"-"$3-1";";Q=$4} 1' example2
new1 1-100;
foo  101-297;
new2 298-1298;
bar  1299-1301;
baz  1302-1314;
new3 1302-1398; # ERROR HERE: Notice that range "new3" has a lower bound that is equal to upper bound of "bar", not of "baz".
qux  1399-5266;

--

Edit 2: Many thanks to RavinderSingh13 for assistance with solving this question. However, the suggested code still generates output inconsistent with the given objective.

$ cat example3
foo  35025-35144;
bar  35259-35375;
baz  35376-35624;
qux  37911-39434;

$ awk -F'[ -]' '$3-Q+0>=1{print "new"++o,Q+1"-"$3-1";";Q=$4} {Q=$4;print}' example3
new1 1-35024;
foo  35025-35144;
new2 35145-35258;
bar  35259-35375;
new3 35376-35375; # ERROR HERE: Notice that range "new3" has been added, even though ranges "bar" and "baz" are contiguous.
baz  35376-35624;
new4 35625-37910;
qux  37911-39434;

Body:
$ cat file1
foo  2-100
bar  102-200
$ awk F' +|[-;}' 'p+1<$2{print "new" ++q, p+1 "-" $2-1 ";"}p=$3' file1
new1 1-1;
foo  2-100
new2 101-101;
bar  102-200
$ cat file2
foo  101-297;
bar  1299-1301;
baz  1314-5266;
$ awk -F' +|[-;]' 'p+1<$2{print "new" ++q, p+1 "-" $2-1 ";"}p=$3' file2
new1 1-100;
foo  101-297;
new2 298-1298;
bar  1299-1301;
new3 1302-1313;
baz  1314-5266;

Explained:

$ awk -F' +|[-;]' '                   # FS is ; - or a bunch of spaces
p+1 < $2 {                           # if p revious $3+1 is still less than new $2
    print "new"++q,p+1 "-" $2-1 ";"  # print a "new" line
}
p=$3                                 # set future p and implicit print of record *
' file2                              # * as all values are above 0


问:
Input field validation for two numbers
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

```<code><input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
<span ng-show="num1>num2">Num2 cannot be lesser than num1</span>
</code>```

答:
Change the text box  type="text"  to type="number"

```<code><input name="num1" type="number" ng-model="num1" placeholder="num1">
<input name="num2" type="number" ng-model="num2" placeholder="num2">
<span ng-show="num1 > num2">Num2 cannot be lesser than num1</span>
</code>```

Demo

Title: Input field validation for two numbers

Body:
I seem to be stuck with a validation issue for 2 numbers which I am passing in the input field. I provide 2 numbers in the input, say num1 and num2. num2 must be greater than num1. If it is not, then I need to show an error message. This is what I have tried so far. I am not seeing the error message being shown consistently. Appreciate it if someone could point out what I might be missing.

JSFiddle

<input name="num1" type="text" ng-model="num1" placeholder="num1">
<input name="num2" type="text" ng-model="num2" placeholder="num2">
num2">Num2 cannot be lesser than num1

Body:
Change the text box  type="text"  to type="number"

<input name="num1" type="number" ng-model="num1" placeholder="num1">
<input name="num2" type="number" ng-model="num2" placeholder="num2">
<span ng-show="num1 > num2">Num2 cannot be lesser than num1</span>

Demo


问:
Create seperate data frames and plots with a for loop
I'm trying to automate pivot table creation so I can make multiple pivot tables at once. I would also like to graph these with a sns.heatmap() plot.

The code I have so far technically works but I'm forced to use a print command so the data doesn't come out in a data frame and the graph the is produced is extremely unreadable.

```<code>for i in list(df):
y = pd.pivot_table(df, index = df[i], values=vector)
print(y)
</code>```

This doesn't give the desired result of an individual data frame for each loop of the loop.

If I graph this with the code:

```<code>for i in list(df):
y = pd.pivot_table(df, index = df[i], values=vector)
sns.heatmap(y, annot=True)
</code>```

I get all the tables mushed into one long one with a n different heat map legends.

I've tried using dictionaries to get around this but I don't think this is the best approach (but what do I know?)

```<code>d={}
for i in list(df):
    d[i] = pd.pivot_table(df, index = df[i], values=vector)
</code>```

Any one have any tips?

答:
If you want to iterate over a DataFrame, for i in list(df) is not the way to go.

As you yourself suggested, keeping the results in a dict is the easiest way. And split the generation with the plotting

```<code>d = {col_name: pd.pivot_table(df, index=col, values=vecor) for col_name, col in df.iteritems()}
</code>```

Then plotting  can loop over the results, and do the plotting

```<code>for column_name, pivot_results in d:
    # plotting
</code>```

Body:
I'm trying to automate pivot table creation so I can make multiple pivot tables at once. I would also like to graph these with a sns.heatmap() plot.

The code I have so far technically works but I'm forced to use a print command so the data doesn't come out in a data frame and the graph the is produced is extremely unreadable.

for i in list(df):
y = pd.pivot_table(df, index = df[i], values=vector)
print(y)

This doesn't give the desired result of an individual data frame for each loop of the loop.

If I graph this with the code:

for i in list(df):
y = pd.pivot_table(df, index = df[i], values=vector)
sns.heatmap(y, annot=True)

I get all the tables mushed into one long one with a n different heat map legends.

I've tried using dictionaries to get around this but I don't think this is the best approach (but what do I know?)

d={}
for i in list(df):
    d[i] = pd.pivot_table(df, index = df[i], values=vector)

Any one have any tips?

Body:
If you want to iterate over a DataFrame, for i in list(df) is not the way to go.

As you yourself suggested, keeping the results in a dict is the easiest way. And split the generation with the plotting

d = {col_name: pd.pivot_table(df, index=col, values=vecor) for col_name, col in df.iteritems()}

Then plotting  can loop over the results, and do the plotting

for column_name, pivot_results in d:
    # plotting


问:
How to strip a certain string from each the list items
I have list of file paths inside C:\ stored in a list called filepaths, now i have to strip off C:\ from all the filepaths while doing a for loop.

I'm not able to find a strip method while looping, as each element is coming as Type list. Please find my code below.

```<code>filepaths = ['C:\folder\file1.jpg','C:\file2.png','C:\file3.xls']
tobestriped = 'C:\'
for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)
</code>```

答:
Well, to begin with, in tobestriped you'll get an error as \' will be escaped. You can use tobestriped = 'C:\\'.

From this SO answer:

A "raw string literal" is a slightly different syntax for a string
  literal, in which a backslash, \, is taken as meaning "just a
  backslash" (except when it comes right before a quote that would
  otherwise terminate the literal) -- no "escape sequences" to represent
  newlines, tabs, backspaces, form-feeds, and so on. In normal string
  literals, each backslash must be doubled up to avoid being taken as
  the start of an escape sequence.

Next, In your paths list \f will also be escaped. To get rid of this issue, make those strings raw strings:

```<code>filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
</code>```

An you will have the desired result:

```<code>filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
tobestriped = 'C:\\'

for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)
</code>```

Output:

```<code>folder\file1.jpg
file2.png
file3.xls
</code>```

An alternative to your solution would be to take advantage of the fact that all your strings begin with C:\ so you can do something like this:

```<code>print([x[3:] for x in filepaths])
</code>```

Body:
I have list of file paths inside C:\ stored in a list called filepaths, now i have to strip off C:\ from all the filepaths while doing a for loop.

I'm not able to find a strip method while looping, as each element is coming as Type list. Please find my code below.

filepaths = ['C:\folder\file1.jpg','C:\file2.png','C:\file3.xls']
tobestriped = 'C:\'
for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)

Body:
Well, to begin with, in tobestriped you'll get an error as \' will be escaped. You can use tobestriped = 'C:\\'.

From this SO answer:

A "raw string literal" is a slightly different syntax for a string
  literal, in which a backslash, \, is taken as meaning "just a
  backslash" (except when it comes right before a quote that would
  otherwise terminate the literal) -- no "escape sequences" to represent
  newlines, tabs, backspaces, form-feeds, and so on. In normal string
  literals, each backslash must be doubled up to avoid being taken as
  the start of an escape sequence.

Next, In your paths list \f will also be escaped. To get rid of this issue, make those strings raw strings:

filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']

An you will have the desired result:

filepaths = [r'C:\folder\file1.jpg', r'C:\file2.png', r'C:\file3.xls']
tobestriped = 'C:\\'

for filepath in filepaths:
    newfilepath = filepath.strip(tobestriped)
    print(newfilepath)

Output:

folder\file1.jpg
file2.png
file3.xls

An alternative to your solution would be to take advantage of the fact that all your strings begin with C:\ so you can do something like this:

print([x[3:] for x in filepaths])