问:
Elastic search creating new mapping rather than joining the one already defined?
I created a index with mapping given below. And the index is empty

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}
</code>```

When i am inserting a document like this :

```<code>PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }
</code>```

It is creating a new mapping rather than joining in the one that defined previously.

```<code>{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

答:
If you would like to index following document then:

```<code>PUT content/university/1
{
  "university": [
    {
      "state": {
        "region": "usa",
        "pincode": 5693
      }
    }
  ]
}
</code>```

mapping should be defined as shown below:

```<code>PUT content
{
  "mappings": {
    "university": {
      "properties": {
        "university": {
          "type": "nested",
          "properties": {
            "state": {
              "type": "nested",
              "properties": {
                "pincode": {
                  "type": "long"
                },
                "region": {
                  "type": "string",
                  "index": "not_analyzed"
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

Body:
I created a index with mapping given below. And the index is empty

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          }
        }
      }
    }
  }
}

When i am inserting a document like this :

PUT content/university/1
    {
      "university": [
        {
          "state": {
            "region": "usa",
            "pincode": 5693
          }
        }
      ]
    }

It is creating a new mapping rather than joining in the one that defined previously.

{
  "content": {
    "mappings": {
      "university": {
        "properties": {
          "state": {
            "type": "nested",
            "properties": {
              "pincode": {
                "type": "long"
              },
              "region": {
                "type": "string",
                "index": "not_analyzed"
              }
            }
          },
          "university": {
            "properties": {
              "state": {
                "properties": {
                  "pincode": {
                    "type": "long"
                  },
                  "region": {
                    "type": "string"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

How i can avoid this in elasticsearch?

Whether i have to use inline scripts for this?

Body:
If you would like to index following document then:

PUT content/university/1
{
  "university": [
    {
      "state": {
        "region": "usa",
        "pincode": 5693
      }
    }
  ]
}

mapping should be defined as shown below:

PUT content
{
  "mappings": {
    "university": {
      "properties": {
        "university": {
          "type": "nested",
          "properties": {
            "state": {
              "type": "nested",
              "properties": {
                "pincode": {
                  "type": "long"
                },
                "region": {
                  "type": "string",
                  "index": "not_analyzed"
                }
              }
            }
          }
        }
      }
    }
  }
}


来源: stackexchange

问:
Getting device's local timezone
2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400

is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM

答:
Using SimpleDateFormat

```<code>String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
</code>```

Note: I am not sure the same class is available in andriod.

ContentLicense: CC BY-SA 2.5

Title: Getting device's local timezone

Body:
Using SimpleDateFormat

String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);

Note: I am not sure the same class is available in andriod.


问:
CSS - center two images in css side by side
I am trying to center two images side by side, but for some reason it always displays the images beneath each other. Does anyone know how I could get them centered and next to each other?

Thanks!

HTML code

```<code><a href="mailto:olympiahaacht@hotmail.com">
<img id="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/07/email-icon-e1343123697991.jpg"/></a>
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img id="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>`
</code>```

CSS code

```<code>#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px;
}
</code>```

答:
Flexbox can do this with just two css rules on a surrounding div.

.social-media{
    display: flex;
    justify-content: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="social-media">

<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>

<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to center two images side by side, but for some reason it always displays the images beneath each other. Does anyone know how I could get them centered and next to each other?

Thanks!

HTML code

`

CSS code

#fblogo {
    display: block;
    margin-left: auto;
    margin-right: auto;
    height: 30px;
}

Body:
Flexbox can do this with just two css rules on a surrounding div.

.social-media{
    display: flex;
    justify-content: center;
}

<div class="social-media">
<a href="mailto:olympiahaacht@hotmail.com">
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>
</div>

ContentLicense: CC BY-SA 4.0


问:
c++ - isdigit, how to distinguish between a character and a number
I want to check if my array has only numbers how can I check it out?

i try this example but this not working and i dont Understand why.

```<code>int main() {

char* str = new char[9];
cin >> str;

cout << isdigit(str[0])<<endl;

system("pause");
return 0;
}
</code>```

input:

1234

output:
4

what i want is:

input:
1234

print: ok

input:

12fg

print: not ok (because the character in my array)

I look forward to your help and explanation

thank's.

答:
try this

```<code>if(isdigit(str[0]))
  cout << 'ok'
else
  cout << 'not ok'
</code>```

extra credit 1. Using this validate the whole string

extra credit 2. Find a different way to verify the whole string (there are many)

extra credit 3. Harder, find out why you got '4' from isdigit(str[0])

Body:
I want to check if my array has only numbers how can I check it out?

i try this example but this not working and i dont Understand why.

int main() {

char* str = new char[9];
cin >> str;

cout << isdigit(str[0])<<endl;

system("pause");
return 0;
}

input:

1234

output:
4

what i want is:

input:
1234

print: ok

input:

12fg

print: not ok (because the character in my array)

I look forward to your help and explanation

thank's.

Body:
try this

if(isdigit(str[0]))
  cout << 'ok'
else
  cout << 'not ok'

extra credit 1. Using this validate the whole string

extra credit 2. Find a different way to verify the whole string (there are many)

extra credit 3. Harder, find out why you got '4' from isdigit(str[0])


问:
Is there a simple way to convert data base rows to JSON in Golang
Currently on what I've seen so far is that, converting database rows to JSON or to []map[string]interface{} is not simple. I have to create two slices and then loop through columns and create keys every time.

...Some code

```<code>tableData := make([]map[string]interface{}, 0)
  values := make([]interface{}, count)
  valuePtrs := make([]interface{}, count)
  for rows.Next() {
      for i := 0; i < count; i++ {
          valuePtrs[i] = &values[i]
      }
      rows.Scan(valuePtrs...)
      entry := make(map[string]interface{})
      for i, col := range columns {
          var v interface{}
          val := values[i]
          b, ok := val.([]byte)
          if ok {
              v = string(b)
          } else {
              v = val
          }
          entry[col] = v
      }
      tableData = append(tableData, entry)
  }
</code>```

Is there any package for this ? Or I am missing some basics here

答:
One thing you could do is create a struct that models your data.

**Note: I am using MS SQLServer

So lets say you want to get a user

```<code>type User struct {
    ID int `json:"id,omitempty"`
    UserName string `json:"user_name,omitempty"`
    ...
}
</code>```

then you can do this

```<code>func GetUser(w http.ResponseWriter, req *http.Request) {
    var r Role
    params := mux.Vars(req)

    db, err := sql.Open("mssql", "server=ServerName")
    if err != nil {
        log.Fatal(err)
    }

    err1 := db.QueryRow("select Id, UserName from [Your Datavse].dbo.Users where Id = ?", params["id"]).Scan(&r.ID, &r.Name)
    if err1 != nil {
        log.Fatal(err1)
    }
    json.NewEncoder(w).Encode(&r)

    if err != nil {
        log.Fatal(err)
    }

}
</code>```

Here are the imports I used

```<code>import (
    "database/sql"
    "net/http"

    "log"

    "encoding/json"

    _ "github.com/denisenkom/go-mssqldb"
    "github.com/gorilla/mux"
)
</code>```

This allowed me to get data from the database and get it into JSON.

This takes a while to code, but it works really well.

Body:
Currently on what I've seen so far is that, converting database rows to JSON or to []map[string]interface{} is not simple. I have to create two slices and then loop through columns and create keys every time.

...Some code

tableData := make([]map[string]interface{}, 0)
  values := make([]interface{}, count)
  valuePtrs := make([]interface{}, count)
  for rows.Next() {
      for i := 0; i < count; i++ {
          valuePtrs[i] = &values[i]
      }
      rows.Scan(valuePtrs...)
      entry := make(map[string]interface{})
      for i, col := range columns {
          var v interface{}
          val := values[i]
          b, ok := val.([]byte)
          if ok {
              v = string(b)
          } else {
              v = val
          }
          entry[col] = v
      }
      tableData = append(tableData, entry)
  }

Is there any package for this ? Or I am missing some basics here

Body:
One thing you could do is create a struct that models your data.

**Note: I am using MS SQLServer

So lets say you want to get a user

type User struct {
    ID int `json:"id,omitempty"`
    UserName string `json:"user_name,omitempty"`
    ...
}

then you can do this

func GetUser(w http.ResponseWriter, req *http.Request) {
    var r Role
    params := mux.Vars(req)

    db, err := sql.Open("mssql", "server=ServerName")
    if err != nil {
        log.Fatal(err)
    }

    err1 := db.QueryRow("select Id, UserName from [Your Datavse].dbo.Users where Id = ?", params["id"]).Scan(&r.ID, &r.Name)
    if err1 != nil {
        log.Fatal(err1)
    }
    json.NewEncoder(w).Encode(&r)

    if err != nil {
        log.Fatal(err)
    }

}

Here are the imports I used

import (
    "database/sql"
    "net/http"

    "log"

    "encoding/json"

    _ "github.com/denisenkom/go-mssqldb"
    "github.com/gorilla/mux"
)

This allowed me to get data from the database and get it into JSON.

This takes a while to code, but it works really well.


问:
Using only string with Flex/Bison
I am new in Flex/Bison. I want to use only strings for values (is a language translator). I have this for test:

example.l:

```<code>%option noyywrap nodefault

%{
#include <string.h>
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%
</code>```

example.y:

```<code>%{
#include <stdio.h>
#define YYSTYPE char const *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
     | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
     | NUMBER '>' NUMBER  { printf("%s > %s\n",$1,$3); }
     | NUMBER '<' NUMBER  { printf("%s < %s\n",$1,$3); }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
</code>```

When I compiled:

```<code>bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
 [0-9]+ { yylval=strdup(yytext); return NUMBER; }
         ^
</code>```

But work as awaited.

If I don't use #define YYSTYPE char const * and use instead the %union:

```<code>%union {
   char * txt;
}

%token <txt> NUMBER
</code>```

And change the assignation to [0-9]+ { yylval.txt=strdup(yytext); return NUMBER; }, it has no warning and works.

I tried thing like define the same YYSTYPE in flex file and cast the assignation without success. What is wrong? How to fix without using %union?

Thanks.

答:
You need move #define YYSTYPE char const * to example.l before #include "example.tab.h".

If you take a look inside example.tab.h you will find something like this:

```<code>#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
// ...
#endif
</code>```

This i mean you need define YYSTYPE before this code, i.e. before #include "example.tab.h. Otherwise, if YYSTYPE not defined on this moment, YYSTYPE will be defined as int.

Another possibility is use bison feature %define api.value.type  {char const *}, what you need to put in example.y. In that case example.tab.h will be generated with YYSTYPE of char const * type.

Title: Using only string with Flex/Bison

Body:
I am new in Flex/Bison. I want to use only strings for values (is a language translator). I have this for test:

example.l:

%option noyywrap nodefault

%{
#include <string.h>
#include "example.tab.h"
%}

%%

[ \t\n] {;}
"<="    {return LEFT;}
"=>"    {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }

%%

example.y:

%{
#include <stdio.h>
#define YYSTYPE char const *
%}

%token NUMBER
%token LEFT "<=" RIGHT "=>"

%%

start: %empty | start tokens

tokens:
       NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
     | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
     | NUMBER '>' NUMBER  { printf("%s > %s\n",$1,$3); }
     | NUMBER '<' NUMBER  { printf("%s < %s\n",$1,$3); }

%%

main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }

When I compiled:

bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
 [0-9]+ { yylval=strdup(yytext); return NUMBER; }
         ^

But work as awaited.

If I don't use #define YYSTYPE char const * and use instead the %union:

%union {
   char * txt;
}

%token <txt> NUMBER

And change the assignation to [0-9]+ { yylval.txt=strdup(yytext); return NUMBER; }, it has no warning and works.

I tried thing like define the same YYSTYPE in flex file and cast the assignation without success. What is wrong? How to fix without using %union?

Thanks.

Body:
You need move #define YYSTYPE char const * to example.l before #include "example.tab.h".

If you take a look inside example.tab.h you will find something like this:

#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef int YYSTYPE;
// ...
#endif

This i mean you need define YYSTYPE before this code, i.e. before #include "example.tab.h. Otherwise, if YYSTYPE not defined on this moment, YYSTYPE will be defined as int.

Another possibility is use bison feature %define api.value.type  {char const *}, what you need to put in example.y. In that case example.tab.h will be generated with YYSTYPE of char const * type.


问:
making a loop for click function?
I am trying to make the following functions work continually as a loop as it is to control open panels in an accordion but I can only seem to get this function to run the once to add the class to the initial clicked element (upon 1st click) and once again to remove the class (upon 2nd click) from the element upon clicking another panel in the accordion. Then it no longer adds or removes classes with the click function? Please help, I am pretty new to all this! Thanks

$(document).ready(function() {
  $('dt').click(function() {
    //alert( "Handler for .click() called." );

    $(this).next().andSelf().addClass('.openAcc');
    $('dt').click(function() {
      $('dt').next().andSelf().removeClass('.openAcc');

    });
  });
});```

basically i want to be able to click on any dt element in the accordion and either turn on or off the previous/current accordions class

答:
You are adding new click handlers every time you click, and they will be active at the same time, one will undo the effect of the other, ...etc.

It often is a bad sign when event handlers are assigned within a handler for the same event.

In fact, jQuery has a nice function for what you want: toggleClass:

```<code>$(document).ready(function (){
    $('dt').click(function() {
        $(this).next().andSelf().toggleClass('.openAcc');
    });
});
</code>```

Title: making a loop for click function?

Body:
I am trying to make the following functions work continually as a loop as it is to control open panels in an accordion but I can only seem to get this function to run the once to add the class to the initial clicked element (upon 1st click) and once again to remove the class (upon 2nd click) from the element upon clicking another panel in the accordion. Then it no longer adds or removes classes with the click function? Please help, I am pretty new to all this! Thanks

$(document).ready(function() {
  $('dt').click(function() {
    //alert( "Handler for .click() called." );

    $(this).next().andSelf().addClass('.openAcc');
    $('dt').click(function() {
      $('dt').next().andSelf().removeClass('.openAcc');

    });
  });
});

basically i want to be able to click on any dt element in the accordion and either turn on or off the previous/current accordions class

Body:
You are adding new click handlers every time you click, and they will be active at the same time, one will undo the effect of the other, ...etc.

It often is a bad sign when event handlers are assigned within a handler for the same event.

In fact, jQuery has a nice function for what you want: toggleClass:

$(document).ready(function (){
    $('dt').click(function() {
        $(this).next().andSelf().toggleClass('.openAcc');
    });
});


问:
LINQ binding refresh problem
I have a ListView bound to a LINQ to SQL object.  When I double click an article in the ListView it opens the article details window and allow the user to change article properties.

So far, it all works fine, but when the user saves and closes the article details, the ListView doesn't reflect the changes made (like the article's description for example). I don't want to implement INotifyPropertyChanged in all my LINQ classes because I use VS2010 to generate my Linq table schema, so it would be a pain to alter auto generated designer code... (and it will certainly override all my changes each time I will make a change to the table's schema)

How can I simply force the ListView to refresh the LINQ binding when the details window is closed?

Thank in advance for your help.

答: All Linq classes are generated as partial classes - this means you can create your own partial class that matches the Linq class and add any extra functionality required there.  Then when it is compiled, it will all work as one class.</p>

Title: LINQ binding refresh problem


问:
Setting background in a game without using Bitmap
I'm making a simple game, like this one, where you have to go through that little space between the 2 lines, but all my lines are descending and you can only move your character left/right at the bottom of the screen.

I've been wandering through a lot of topics (most from -2014) and found out that the best way to draw a background on a cansa is by using a bitmap. The problem is that this takes a lot of resources, my FPS dropping from 40+ to <20.

This is what I found :

```<code> canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.big_background),0,0,null);
</code>```

Is there any better way? Like setting the setContentView to a specific XML activity, knowing that in order for my lines to descend, I need to redraw them 30 times/ sec ?

答:
David has it right: save the Bitmap once and reuse it when you need to draw.

In your Activity, add private Bitmap bg;

In the onCreate(), add bg = BitmapFactory.decodeResource(getResources(),R.drawable.big_background);

You can now do canvas.drawBitmap(bg); without incurring the bitmap load penalty.

Body:
I'm making a simple game, like this one, where you have to go through that little space between the 2 lines, but all my lines are descending and you can only move your character left/right at the bottom of the screen.

I've been wandering through a lot of topics (most from -2014) and found out that the best way to draw a background on a cansa is by using a bitmap. The problem is that this takes a lot of resources, my FPS dropping from 40+ to <20.

This is what I found :

 canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.big_background),0,0,null);

Is there any better way? Like setting the setContentView to a specific XML activity, knowing that in order for my lines to descend, I need to redraw them 30 times/ sec ?


问:
Collection to store objects with combination of ids as unique
I have a class Test with attributes

```<code>--> Integer id1
--> Integer id2
--> String stringValue.
</code>```

So there are list of stringValues per (id1 and id2) combination of unique ids.
I want to be able store that in a collection.
Example:

```<code>  test1 : id1 = 1, id2 = 2 , stringValue = one
  test11 : id1 = 1, id2 = 2 , stringValues =two
  test111 : id1 = 1, id2 = 3 , stringValues =three
  test2 : id1 = 5, id2 = 3, stringValues = four
  test22: id1 = 5, id2 = 2, stringValues = five
  test222: id = 5, id2 = 3, stringValues = six
</code>```

Desired end result is store the objects as

```<code>-> {id = 1, id = 2, String = {one, two} }
-> {id = 1 , id =3 , String = {three}}
-> {id = 5, id = 3 , String = {four,six}}
-> {id = 5, id = 2 , String = {five}}
</code>```

I want to be able to store the list of 'test' objects in a collection.
I tried Set<> , overriding the equals and hashcode but it didnt work as expected.
Here you go

```<code>@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id1 == null) ? 0 : id1.hashCode());
        result = prime * result + ((id2 == null) ? 0 : id2.hashCode());
        return result;
    }

        @Override
    public boolean equals(Object obj) {
        if( obj instanceof Test){
            Test test = (Test) obj;
            return (test.id1 == this.id1 && test.id2 == this.id2);
        } else {
            return false;
        }
    }
</code>```

I loop through each object and store it in a SET. it does eliminate (redundant combination of [id1 and id2], but it also eliminates the respective string value.)
Oops I forgot to mention I get the data from a resultset retrieved from database.
so each row consists of id1, id2 and a string value(which is different for all rows). some rows will have a common id1 and id2 values

Can someone please suggest me with any pointers please ?

Thank you in advance

答:
Does that solve your problem?

```<code>import java.util.*;

public class Playground1 {
    public static void main(String[] args) {

        // fake resultset
        List<DBResultSetRowEmulation> resultSetEmulation = new ArrayList<>();
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 2, "one"));
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 2, "two"));
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 3, "three"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 3, "four"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 2, "five"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 3, "six"));

        Map<DoubleIndex, List<String>> resultData = new HashMap<>();

        // iterate through resultset
        for(DBResultSetRowEmulation row: resultSetEmulation) {
            DoubleIndex curRecordIdx = new DoubleIndex(row.a, row.b);
            if (resultData.containsKey(curRecordIdx)) {
                // append current string to some existing id1+id2 combination
                resultData.get(curRecordIdx).add(row.c);
            } else {
                // create a new list for new id1+id2 combination
                resultData.put(curRecordIdx, new ArrayList<>(Collections.singletonList(row.c)));
            }
        }

        System.out.println(resultData);
    }

    private static class DBResultSetRowEmulation {
        Integer a, b;
        String c;

        DBResultSetRowEmulation(Integer a, Integer b, String c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    }

    private static class DoubleIndex {
        private Integer a,b;

        public DoubleIndex(Integer a, Integer b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            DoubleIndex that = (DoubleIndex) o;

            return a.equals(that.a) && b.equals(that.b);
        }

        @Override
        public int hashCode() {
            int result = a.hashCode();
            result = 31 * result + b.hashCode();
            return result;
        }

        @Override
        public String toString() {
            return "id{" +
                    "a=" + a +
                    ", b=" + b +
                    '}';
        }
    }
}
</code>```

output:

{id{a=1, b=2}=[one, two],

id{a=1, b=3}=[three],

id{a=5, b=2}=[five],

id{a=5, b=3}=[four, six]}

You will have to figure out how to sort that result by yourself.

Body:
I have a class Test with attributes

--> Integer id1
--> Integer id2
--> String stringValue.

So there are list of stringValues per (id1 and id2) combination of unique ids.
I want to be able store that in a collection.
Example:

  test1 : id1 = 1, id2 = 2 , stringValue = one
  test11 : id1 = 1, id2 = 2 , stringValues =two
  test111 : id1 = 1, id2 = 3 , stringValues =three
  test2 : id1 = 5, id2 = 3, stringValues = four
  test22: id1 = 5, id2 = 2, stringValues = five
  test222: id = 5, id2 = 3, stringValues = six

Desired end result is store the objects as

-> {id = 1, id = 2, String = {one, two} }
-> {id = 1 , id =3 , String = {three}}
-> {id = 5, id = 3 , String = {four,six}}
-> {id = 5, id = 2 , String = {five}}

I want to be able to store the list of 'test' objects in a collection.
I tried Set<> , overriding the equals and hashcode but it didnt work as expected.
Here you go

@Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id1 == null) ? 0 : id1.hashCode());
        result = prime * result + ((id2 == null) ? 0 : id2.hashCode());
        return result;
    }

        @Override
    public boolean equals(Object obj) {
        if( obj instanceof Test){
            Test test = (Test) obj;
            return (test.id1 == this.id1 && test.id2 == this.id2);
        } else {
            return false;
        }
    }

I loop through each object and store it in a SET. it does eliminate (redundant combination of [id1 and id2], but it also eliminates the respective string value.)
Oops I forgot to mention I get the data from a resultset retrieved from database.
so each row consists of id1, id2 and a string value(which is different for all rows). some rows will have a common id1 and id2 values

Can someone please suggest me with any pointers please ?

Thank you in advance

Body:
Does that solve your problem?

import java.util.*;

public class Playground1 {
    public static void main(String[] args) {

        // fake resultset
        List<DBResultSetRowEmulation> resultSetEmulation = new ArrayList<>();
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 2, "one"));
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 2, "two"));
        resultSetEmulation.add(new DBResultSetRowEmulation(1, 3, "three"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 3, "four"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 2, "five"));
        resultSetEmulation.add(new DBResultSetRowEmulation(5, 3, "six"));

        Map<DoubleIndex, List<String>> resultData = new HashMap<>();

        // iterate through resultset
        for(DBResultSetRowEmulation row: resultSetEmulation) {
            DoubleIndex curRecordIdx = new DoubleIndex(row.a, row.b);
            if (resultData.containsKey(curRecordIdx)) {
                // append current string to some existing id1+id2 combination
                resultData.get(curRecordIdx).add(row.c);
            } else {
                // create a new list for new id1+id2 combination
                resultData.put(curRecordIdx, new ArrayList<>(Collections.singletonList(row.c)));
            }
        }

        System.out.println(resultData);
    }

    private static class DBResultSetRowEmulation {
        Integer a, b;
        String c;

        DBResultSetRowEmulation(Integer a, Integer b, String c) {
            this.a = a;
            this.b = b;
            this.c = c;
        }
    }

    private static class DoubleIndex {
        private Integer a,b;

        public DoubleIndex(Integer a, Integer b) {
            this.a = a;
            this.b = b;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            DoubleIndex that = (DoubleIndex) o;

            return a.equals(that.a) && b.equals(that.b);
        }

        @Override
        public int hashCode() {
            int result = a.hashCode();
            result = 31 * result + b.hashCode();
            return result;
        }

        @Override
        public String toString() {
            return "id{" +
                    "a=" + a +
                    ", b=" + b +
                    '}';
        }
    }
}

output:

{id{a=1, b=2}=[one, two],

id{a=1, b=3}=[three],

id{a=5, b=2}=[five],

id{a=5, b=3}=[four, six]}

You will have to figure out how to sort that result by yourself.


问:
Overflow hidden no having affect
I have a simple progress bar, it has a borderRadius and overflow set to hidden. I have a child of this, it has no borderRadius, and it is overflowing outside of the corners. Here is my markup:

```<code>        <View style={style.progressbar}>
            <View style={[style.progressbarfill, { width:'50%' }]} />
        </View>

const style = {
    progressbar: {
        backgroundColor: '#ccc',
        height: 25,
        width: '90%',
        borderRadius: 12,
        overflow: 'hidden'
    },
    progressbarfill: {
        backgroundColor: 'springgreen',
        width: '10%',
        height: '100%'
    }
}
</code>```

This is what it looks like:

I put arrows on where the green is covering the border. The green should not overflow outside the edges.

Does anyone know why this is?

答:
Actually I'm testing it right now, seems to be working fine on iOS, but Android is the one having the issue with the overflow right now. It looks like that is still getting more support currently. A temporary fix, is to just add the same borderRadius on the progressbarfill.

Here is the issue on the React Native Docs:

The overflow style property defaults to hidden and cannot be changed
  on Android  This is a result of how Android rendering works. This
  feature is not being worked on as it would be a significant
  undertaking and there are many more important tasks.

Another issue with overflow: 'hidden' on Android: a view is not
  clipped by the parent's borderRadius even if the parent has overflow:
  'hidden' enabled – the corners of the inner view will be visible
  outside of the rounded corners. This is only on Android; it works as
  expected on iOS. See the corresponding issue.

Title: Overflow hidden no having affect

Body:
I have a simple progress bar, it has a borderRadius and overflow set to hidden. I have a child of this, it has no borderRadius, and it is overflowing outside of the corners. Here is my markup:

        <View style={style.progressbar}>
            <View style={[style.progressbarfill, { width:'50%' }]} />
        </View>

const style = {
    progressbar: {
        backgroundColor: '#ccc',
        height: 25,
        width: '90%',
        borderRadius: 12,
        overflow: 'hidden'
    },
    progressbarfill: {
        backgroundColor: 'springgreen',
        width: '10%',
        height: '100%'
    }
}

This is what it looks like:

I put arrows on where the green is covering the border. The green should not overflow outside the edges.

Does anyone know why this is?


问:
Spyder: python and ipython intepreters not starting
I am a frequent user of spyder for developping in python and since a few days, when I execute spyder, no python or ipython interpreters can be started available within the spyder environnement.

The initial interpreter when I execute spyder is grayed out (like it is stopped), and when I click on the "play" button to start the interpreter, it stops right away and stays grayed out.

When I look at the execution options (F6) it is still possible to use an external terminal to run the scripts but I can't execute the scripts in a dedicated python interpreter neither can I execute it in the current python/ipython interpreter.

Does anyone have an idea about how I can resolve this?

I have updated matplotlib to 1.5 and some other libraries, prior to this problem.

答:
I had the same issue, also after updating matplotlib (and a number of other packages). I solved the problem by updating Spyder:</p>

```<code>sudo pip install --upgrade spyder
</code>```

Body:
I had the same issue, also after updating matplotlib (and a number of other packages). I solved the problem by updating Spyder:

sudo pip install --upgrade spyder


问:
How to configure a proxy in a .Net Core Console App
In previous .Net console applications we can avoid proxy 407 errors by including the following in app.config:

```<code><system.net>
  <defaultProxy useDefaultCredentials="true"/>
</system.net>
</code>```

.Net Core console app does not have app.config - how can we do the same?

Specifically for an Azure DocumentDB DocumentClient.

答:
It looks like that for now Azure-oriented team didn't implement such feature. Here is a link to recent github issue for Azure AD library, which states that

Currently ADAL for .NET doesn’t support WebProxy configuration.

Please configure proxy at the system level. Httpclient used by Adal should be able to use it.

Production team has planned to add this function in future version, but currently they don’t have estimation time.

As far as one can see, there is no such feature available in Microsoft.Azure.Documents.Client namespace or in Microsoft.Azure.Documents namespace, so for now you have to resolve it on system level. You can probably create a github issue or contact the team on MSDN or by email.

As for general .Net Core app, you can use the HttpClientHandler class' DefaultProxyCredentials property, so the code will be like this:

```<code>var handler = new HttpClientHandler { UseDefaultCredentials = true };
using (var client = new HttpClient(handler))
{
    // http call here
}
</code>```

Body:
In previous .Net console applications we can avoid proxy 407 errors by including the following in app.config:

<system.net>
  <defaultProxy useDefaultCredentials="true"/>
</system.net>

.Net Core console app does not have app.config - how can we do the same?

Specifically for an Azure DocumentDB DocumentClient.

Body:
It looks like that for now Azure-oriented team didn't implement such feature. Here is a link to recent github issue for Azure AD library, which states that

Currently ADAL for .NET doesn’t support WebProxy configuration.

Please configure proxy at the system level. Httpclient used by Adal should be able to use it.

Production team has planned to add this function in future version, but currently they don’t have estimation time.

As far as one can see, there is no such feature available in Microsoft.Azure.Documents.Client namespace or in Microsoft.Azure.Documents namespace, so for now you have to resolve it on system level. You can probably create a github issue or contact the team on MSDN or by email.

As for general .Net Core app, you can use the HttpClientHandler class' DefaultProxyCredentials property, so the code will be like this:

var handler = new HttpClientHandler { UseDefaultCredentials = true };
using (var client = new HttpClient(handler))
{
    // http call here
}


问:
Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin
When I build the project with dependencies, it gives this error.

Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin:2.10.4:jar (attach-javadocs) on project appointmentscheduling-api: MavenReportException: Error while generating Javadoc:

Previously I could build it properly. I didn't change anything, I tried a backup sample as well. But this error come always. Tried re-installing javadoc plugin. There are some answers which says to change the pom.xml file. They didn't work for me either. Somebody help me to solve this please.

Thanks in advance

答:
Have you upgraded to JDK8 lately? You might be running into this problem. The solution would be one of:

Launch Maven with JDK < 8

Apply workaround from link above


问:
String validation with multiple levels required using CMD command
I have three requirements I need to meet when validating a password.  I have figure out with the help of others how to verify that the password is at least seven characters long and the user name is not part of the password.

My last requirement is to check to see if a string contains characters from three of the following four groups:

English uppercase characters (A through Z)

English lowercase characters (a through z)

Base 10 digits (0 through 9)

Non-alphabetic characters (for example, !, $, #, %)

For example (Hou$e or House1) would pass but (House, house or hou$e) would fail

The call to ":checkRequirement3" is where I would like to make this finial check.  The password is valid if all three requirements are meet.

```<code>@echo off
setlocal
set /p userName=Username:
set /p userPassword=Password:
call :strlen result userPassword
call :checkRequirement1
call :checkRequirement2
call :checkRequirement3

ECHO Finished
Pause
:strlen <resultVar> <stringVar>
REM THIS DETERMINES THE LENGTH OF THE PASSWORD
(
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" (
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)

(
    endlocal
    set "%~1=%len%"
    exit /b
)

:checkRequirement1
REM THIS CHECKS IF PASSWORD IS AT LEAST 7 CHARACTERS LONG
(
    if %result% GEQ 7 (
    exit /b
    )else (
    GOTO passwordFail
    )

:checkRequirement2
REM THIS CHECKS IF THE USER NAME IS INCLUDED IN THE PASSWORD
setlocal enabledelayedexpansion
set replacedUsername=!userPassword:%userName%=!
if not !replacedUsername!==%userPassword% (
GOTO passwordFail
)else (
exit /b
)

:checkRequirement3
REM THIS CHECKS IF THE PASSWORD CONTAINS CHARACTERS FROM 3 OF THE FOLLOWING GROUPS
REM English uppercase characters (A through Z)
REM English lowercase characters (a through z)
REM Base 10 digits (0 through 9)
REM Non-alphabetic characters (for example, !, $, #, %)

ECHO This Requirement not finished
Pause
exit /b

:passwordFail
ECHO Password Failed Requirement
PAUSE
exit /b
)
</code>```

答:
This will correctly verify that the password is using 3 out of the 4 groups.</p>

```<code>setlocal enabledelayedexpansion
SET /P userPassword=UserPassword:
SET /P userPassword=UserPassword=%userPassword:&=^&%
SET /a count=0
echo %userPassword:&=^&% | findstr /R /C:"[ABCDEFGHIJKLMNOPQRSTUVWXYZ]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[abcdefghijklmnopqrstuvwxyz]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[!@#&$%%^]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[0123456789]">null&if not errorlevel 1 SET /a count+=1

    If %count% GEQ 3 (
        echo Password Meets requirement
        exit /b
    ) else (
        goto passwordFail
    )
</code>```

Body:
I have three requirements I need to meet when validating a password.  I have figure out with the help of others how to verify that the password is at least seven characters long and the user name is not part of the password.

My last requirement is to check to see if a string contains characters from three of the following four groups:

English uppercase characters (A through Z)

English lowercase characters (a through z)

Base 10 digits (0 through 9)

Non-alphabetic characters (for example, !, $, #, %)

For example (Hou$e or House1) would pass but (House, house or hou$e) would fail

The call to ":checkRequirement3" is where I would like to make this finial check.  The password is valid if all three requirements are meet.

@echo off
setlocal
set /p userName=Username:
set /p userPassword=Password:
call :strlen result userPassword
call :checkRequirement1
call :checkRequirement2
call :checkRequirement3

ECHO Finished
Pause
:strlen <resultVar> <stringVar>
REM THIS DETERMINES THE LENGTH OF THE PASSWORD
(
    setlocal EnableDelayedExpansion
    set "s=!%~2!#"
    set "len=0"
    for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
        if "!s:~%%P,1!" NEQ "" (
            set /a "len+=%%P"
            set "s=!s:~%%P!"
        )
    )
)

(
    endlocal
    set "%~1=%len%"
    exit /b
)

:checkRequirement1
REM THIS CHECKS IF PASSWORD IS AT LEAST 7 CHARACTERS LONG
(
    if %result% GEQ 7 (
    exit /b
    )else (
    GOTO passwordFail
    )

:checkRequirement2
REM THIS CHECKS IF THE USER NAME IS INCLUDED IN THE PASSWORD
setlocal enabledelayedexpansion
set replacedUsername=!userPassword:%userName%=!
if not !replacedUsername!==%userPassword% (
GOTO passwordFail
)else (
exit /b
)

:checkRequirement3
REM THIS CHECKS IF THE PASSWORD CONTAINS CHARACTERS FROM 3 OF THE FOLLOWING GROUPS
REM English uppercase characters (A through Z)
REM English lowercase characters (a through z)
REM Base 10 digits (0 through 9)
REM Non-alphabetic characters (for example, !, $, #, %)

ECHO This Requirement not finished
Pause
exit /b

:passwordFail
ECHO Password Failed Requirement
PAUSE
exit /b
)

Body:
This will correctly verify that the password is using 3 out of the 4 groups.

setlocal enabledelayedexpansion
SET /P userPassword=UserPassword:
SET /P userPassword=UserPassword=%userPassword:&=^&%
SET /a count=0
echo %userPassword:&=^&% | findstr /R /C:"[ABCDEFGHIJKLMNOPQRSTUVWXYZ]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[abcdefghijklmnopqrstuvwxyz]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[!@#&$%%^]">null&if not errorlevel 1 SET /a count+=1
echo %userPassword:&=^&% | findstr /R /C:"[0123456789]">null&if not errorlevel 1 SET /a count+=1

    If %count% GEQ 3 (
        echo Password Meets requirement
        exit /b
    ) else (
        goto passwordFail
    )


问:
Extracting numbers and slashes from a string
I have the following string

```<code>Policy 023203232/02/05 saved successfully
</code>```

And I need to extract 023203232/02/05 from the above string and I have written the following code

```<code>puts a[/\d+\/\d+\/\d+/]
</code>```

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

```<code>Policy 023203232/02/05 saved successfully
</code>```

Then

```<code>023203232/02/05
</code>```

If string is

```<code>Policy 023203232/02/05/06 saved successfully
</code>```

Then

```<code>023203232/02/05/06
</code>```

If string is

```<code>Policy 023203232/02/05/06/08 saved successfully
</code>```

Then

```<code>023203232/02/05/06/08
</code>```

How to write such a generic regular expression?

Body:
I have the following string

Policy 023203232/02/05 saved successfully

And I need to extract 023203232/02/05 from the above string and I have written the following code

puts a[/\d+\/\d+\/\d+/]

And it works fine. But If the number increases with the slashes like, 023203232/02/05/06 I have to include one more \d+ but I don't know how many slashes and number would repeat this way, So any one can suggest me to write some generic solution

If string is

Policy 023203232/02/05 saved successfully

Then

023203232/02/05

If string is

Policy 023203232/02/05/06 saved successfully

Then

023203232/02/05/06

If string is

Policy 023203232/02/05/06/08 saved successfully

Then

023203232/02/05/06/08

How to write such a generic regular expression?

Body:
This one looks for a serie of digits or slashes:

str = "Policy 023203232/02/05/07/3434343/56 saved successfully 09/56/3"
p str.match(/[0-9\/]+/)[0] # => "023203232/02/05/07/3434343/56"


答:
Instead of worrying about a loop, you can just remove all .openAcc classes, then add it to the current one.

$(document).ready(function (){
    $('dt').click(function() {
    //alert( "Handler for .click() called." );

        $('.openAcc').removeClass('.openAcc');
        $(this).next().andSelf().addClass('.openAcc');

    });
});
```

Optimized code with help from @squint

Title: making a loop for click function?

Body:
Instead of worrying about a loop, you can just remove all .openAcc classes, then add it to the current one.

$(document).ready(function (){
    $('dt').click(function() {
    //alert( "Handler for .click() called." );

        $('.openAcc').removeClass('.openAcc');
        $(this).next().andSelf().addClass('.openAcc');

    });
});

Optimized code with help from @squint


问:
Webpack doesn't recognize function parameters
I have defined a function and want to pack everything with webpack using node. Here is the function:

```<code>var makeReq = require('./makeReq.js');
var api = "sampleApi";

function videosDetails(videos) {

    var n = videos.length;
    var ids;

    for (var i = 0; i < n; i++) {
        var id = videos[i];
        ids += id.toString() + ','  ;
    };

    var url = api.concat(ids);
    var req = makeReq.makeReq(url);

    for (var i = 0; i < n; i++) {
        videos[i].details = req.items[i].contentDetails;
        videos[i].details = req.items[i].statistics;
    };

    return videos;
};

module.exports = {
    videosDetails: videosDetails()
}
</code>```

I get the error when compiling on Chrome's Console:

```<code>Uncaught TypeError: Cannot read property 'length' of undefined
at videosDetails (app.bundle.js:197)
at Object.<anonymous> (app.bundle.js:217)
at __webpack_require__ (app.bundle.js:20)
</code>```

Do not understand why it is not recognized when it is a function parameter. Thanks in advance for your time.

答:
You're calling videosDetails() with no argument in:

```<code>module.exports = {
    videosDetails: videosDetails()
}
</code>```

You export the return value of videosDetails not the function itself. As you're calling it with no arguments, videos will be undefined.

You probably wanted to export the function:

```<code>module.exports = {
    videosDetails: videosDetails
}
</code>```

Body:
I have defined a function and want to pack everything with webpack using node. Here is the function:

var makeReq = require('./makeReq.js');
var api = "sampleApi";

function videosDetails(videos) {

    var n = videos.length;
    var ids;

    for (var i = 0; i < n; i++) {
        var id = videos[i];
        ids += id.toString() + ','  ;
    };

    var url = api.concat(ids);
    var req = makeReq.makeReq(url);

    for (var i = 0; i < n; i++) {
        videos[i].details = req.items[i].contentDetails;
        videos[i].details = req.items[i].statistics;
    };

    return videos;
};

module.exports = {
    videosDetails: videosDetails()
}

I get the error when compiling on Chrome's Console:

Uncaught TypeError: Cannot read property 'length' of undefined
at videosDetails (app.bundle.js:197)
at Object.<anonymous> (app.bundle.js:217)
at __webpack_require__ (app.bundle.js:20)

Do not understand why it is not recognized when it is a function parameter. Thanks in advance for your time.

Body:
You're calling videosDetails() with no argument in:

module.exports = {
    videosDetails: videosDetails()
}

You export the return value of videosDetails not the function itself. As you're calling it with no arguments, videos will be undefined.

You probably wanted to export the function:

module.exports = {
    videosDetails: videosDetails
}


问:
Creating Executable Jar with Maven includes Jgoodies GUI
Im developing a java program and im using jgoodies for its GUI. I was making executable jar from my project, before developing GUI. It was working from command line. But when i developed gui for my project and made a package from it, it didnt work. It compiles successfully but when i tried to execute it, it throws errors:

```<code>D:\Documents and Settings\Administrator\Desktop\GPAT\target>java -jar gpat-1.0-SNAPSHOT-jar-with-dependencies.jar
Exception in thread "main" java.lang.IllegalArgumentException: Invalid unit name 'default'. Must be one of: px, dlu, pt, mm, cm, in
    at com.jgoodies.forms.layout.ConstantSize$Unit.valueOf(ConstantSize.java:349)
    at com.jgoodies.forms.layout.ConstantSize.valueOf(ConstantSize.java:146)
    at com.jgoodies.forms.layout.FormSpec.decodeAtomicSize(FormSpec.java:309)
    at com.jgoodies.forms.layout.FormSpec.parseAndInitSize(FormSpec.java:255)
    at com.jgoodies.forms.layout.FormSpec.parseAndInitValues(FormSpec.java:233)
    at com.jgoodies.forms.layout.FormSpec.<init>(FormSpec.java:159)
    at com.jgoodies.forms.layout.ColumnSpec.<init>(ColumnSpec.java:138)
    at com.jgoodies.forms.layout.ColumnSpec.decodeSpecs(ColumnSpec.java:177)
    at com.jgoodies.forms.layout.FormLayout.<init>(FormLayout.java:276)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.initComponents(GPATGUI.java:349)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.<init>(GPATGUI.java:31)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.main(GPATGUI.java:36)
</code>```

I added the dependencies correctfully i suppose. Does this error make any sense for anyone? Thanks for reading.

答: Seems like your setting one of your form constraints to use the default unit, which JGoodies don't like.

Body:
Im developing a java program and im using jgoodies for its GUI. I was making executable jar from my project, before developing GUI. It was working from command line. But when i developed gui for my project and made a package from it, it didnt work. It compiles successfully but when i tried to execute it, it throws errors:

D:\Documents and Settings\Administrator\Desktop\GPAT\target>java -jar gpat-1.0-SNAPSHOT-jar-with-dependencies.jar
Exception in thread "main" java.lang.IllegalArgumentException: Invalid unit name 'default'. Must be one of: px, dlu, pt, mm, cm, in
    at com.jgoodies.forms.layout.ConstantSize$Unit.valueOf(ConstantSize.java:349)
    at com.jgoodies.forms.layout.ConstantSize.valueOf(ConstantSize.java:146)
    at com.jgoodies.forms.layout.FormSpec.decodeAtomicSize(FormSpec.java:309)
    at com.jgoodies.forms.layout.FormSpec.parseAndInitSize(FormSpec.java:255)
    at com.jgoodies.forms.layout.FormSpec.parseAndInitValues(FormSpec.java:233)
    at com.jgoodies.forms.layout.FormSpec.<init>(FormSpec.java:159)
    at com.jgoodies.forms.layout.ColumnSpec.<init>(ColumnSpec.java:138)
    at com.jgoodies.forms.layout.ColumnSpec.decodeSpecs(ColumnSpec.java:177)
    at com.jgoodies.forms.layout.FormLayout.<init>(FormLayout.java:276)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.initComponents(GPATGUI.java:349)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.<init>(GPATGUI.java:31)
    at com.alcatel.lucent.tr.gsat.gpat.GPATGUI.main(GPATGUI.java:36)

I added the dependencies correctfully i suppose. Does this error make any sense for anyone? Thanks for reading.


问:
Rounding a Calculation in Java
This is the question:

Ernesto’s Eggs has different wholesale prices for their eggs, based upon the number sold:

0 up to but not including 4 dozen: $0.50 per dozen

4 dozen up to but not including 6 dozen: $0.45 per dozen

6 dozen up to but not including 11 dozen: $0.40 per dozen

11 dozen or more dozen: $0.35 per dozen

Extra eggs are priced at 1/12 the per dozen price.

a)Write a program that asks the user for the number of eggs, and then calculates the bill. The program output should look similar to:

Enter number of eggs: 126

Your cost is $0.40 per dozen or 0.033 per egg.

Your bill comes to $4.20

This is what I have written but I don't have the numbers rounded correctly.

```<code>/*
Program 1 (Ernestos Eggs)
 */
package eggs;

import java.util.Scanner;

/**
 *
 * @author Laptop
 */
public class Eggs {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
     Scanner sc= new Scanner(System.in);

   System.out.print("Enter number of eggs: ");

   int numberofeggs=sc.nextInt();

   int numberofdozens=numberofeggs/12;

   if(numberofeggs>=0 && numberofeggs<48){

   double costpereggs= 0.50*(1/12);

   double total= (0.50*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.50 per dozen or " +costpereggs+ " per egg.");
   System.out.print("Your bill comes to $" +total);
    }

   else if (numberofeggs>=48 && numberofeggs<72){

   double costpereggs= 0.45*(1/12);

   double total= (0.45*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.45 per dozen or  " +costpereggs+ "per egg.");
   System.out.println("Your bill comes to $" +total);

}
   else if (numberofeggs>=72 && numberofeggs<132) {

   double costpereggs= 0.40*(1/12);

   double total= ((0.40*numberofdozens)+costpereggs);

  System.out.println("Your cost is $0.40 per dozen or " +costpereggs+ " per egg.");
  System.out.println("Your bill comes to $" +total);

   }
   else {

  double costpereggs= 0.35*(1/12);

  double total= (0.35*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.35 per dozen or  " +costpereggs+ "per egg.");
   System.out.println("Your bill comes to $" +total);

    }
    }
}
</code>```

答:
Why are you adding cost per egg to the total? That is irrelevant to the total.

```<code>double total = numberofdozens *0.35;
double costpereggs = total/numberofeggs;
</code>```

That should be what you're looking to do.

Title: Rounding a Calculation in Java

Body:
This is the question:

Ernesto’s Eggs has different wholesale prices for their eggs, based upon the number sold:

0 up to but not including 4 dozen: $0.50 per dozen

4 dozen up to but not including 6 dozen: $0.45 per dozen

6 dozen up to but not including 11 dozen: $0.40 per dozen

11 dozen or more dozen: $0.35 per dozen

Extra eggs are priced at 1/12 the per dozen price.

a)Write a program that asks the user for the number of eggs, and then calculates the bill. The program output should look similar to:

Enter number of eggs: 126

Your cost is $0.40 per dozen or 0.033 per egg.

Your bill comes to $4.20

This is what I have written but I don't have the numbers rounded correctly.

/*
Program 1 (Ernestos Eggs)
 */
package eggs;

import java.util.Scanner;

/**
 *
 * @author Laptop
 */
public class Eggs {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
     Scanner sc= new Scanner(System.in);

   System.out.print("Enter number of eggs: ");

   int numberofeggs=sc.nextInt();

   int numberofdozens=numberofeggs/12;

   if(numberofeggs>=0 && numberofeggs<48){

   double costpereggs= 0.50*(1/12);

   double total= (0.50*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.50 per dozen or " +costpereggs+ " per egg.");
   System.out.print("Your bill comes to $" +total);
    }

   else if (numberofeggs>=48 && numberofeggs<72){

   double costpereggs= 0.45*(1/12);

   double total= (0.45*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.45 per dozen or  " +costpereggs+ "per egg.");
   System.out.println("Your bill comes to $" +total);

}
   else if (numberofeggs>=72 && numberofeggs<132) {

   double costpereggs= 0.40*(1/12);

   double total= ((0.40*numberofdozens)+costpereggs);

  System.out.println("Your cost is $0.40 per dozen or " +costpereggs+ " per egg.");
  System.out.println("Your bill comes to $" +total);

   }
   else {

  double costpereggs= 0.35*(1/12);

  double total= (0.35*numberofdozens)+costpereggs;

   System.out.println("Your cost is $0.35 per dozen or  " +costpereggs+ "per egg.");
   System.out.println("Your bill comes to $" +total);

    }
    }
}

Body:
Why are you adding cost per egg to the total? That is irrelevant to the total.

double total = numberofdozens *0.35;
double costpereggs = total/numberofeggs;

That should be what you're looking to do.


问:
Is String str = new String("my string") really less efficient?
I often saw people saying String str = new String("my string") is less efficient than writing String str = "my string", because the former creates a static "my string" object and then new's a String object that gets copied from the static one.

However, given that the language here is so simple and unambiguous, I can hardly imagine that Java optimizer won't take any effort to simply convert the former to the latter. Why would it really choose to do it the more laborious way? What can any negative side effects be if Java does optimize it?

答:
It's not an issue of performance. It's just doing something in an unnecessarily complicated way. Unless you're working with interned Strings to do comparisons with ==, the code will work the same way too.

Java won't optimize anything because there's nothing to optimize. If you use String literals, identical ones are reduced to the same instance in the string pool, so

```<code>String foo = "foo";
String bar = "foo";
System.out.println(foo == bar); // True, the same object
</code>```

However with the explicit constructor

```<code>String foo = "foo";
String bar = new String("foo");
System.out.println(foo == bar); // False, bar is explicitly created as a new object with the constructor
</code>```

However as you still should use equals() for all object comparisons, you won't see any difference while running your code.

Body:
It's not an issue of performance. It's just doing something in an unnecessarily complicated way. Unless you're working with interned Strings to do comparisons with ==, the code will work the same way too.

Java won't optimize anything because there's nothing to optimize. If you use String literals, identical ones are reduced to the same instance in the string pool, so

String foo = "foo";
String bar = "foo";
System.out.println(foo == bar); // True, the same object

However with the explicit constructor

String foo = "foo";
String bar = new String("foo");
System.out.println(foo == bar); // False, bar is explicitly created as a new object with the constructor

However as you still should use equals() for all object comparisons, you won't see any difference while running your code.


问:
Can't open a Python interpreter in Spyder 2.2.5 (Ubuntu 14.04)
A few weeks ago, I opened Spyder and found that I could not interact with the default Python interpreter console, which appeared greyed-out (screenshot below).

Consequently, I am not able to run Python scripts from within the IDE. I have tried rebooting my machine, opening new interpreters and IPython interpreters, but the result is always the same. I recently tried running spyder --reset in the terminal to erase my settings, but it did not help.

The only recent changes to my Python installation I made were in a virtualenv where I installed Python3, but I am not convinced this is related.

答:
I had the same issue, also after updating packages. I solved the problem by updating Spyder:</p>

```<code>sudo pip install --upgrade spyder
</code>```

Body:
I had the same issue, also after updating packages. I solved the problem by updating Spyder:

sudo pip install --upgrade spyder


问:
How to use REDHAWK Shared Libraries dependencies with Devices?
I am using REDHAWK 2.0.5 on CentOS 7. I am adding Shared Library (SoftPkg) References (for example rh.dsp) to my Device via the Implementations tab in the IDE. This allows the headers and libraries of rh.dsp (located in $SDRROOT/dom/deps/rh/dsp) to be found, and the Device builds without issue. However, when the device launches in the Sandbox, an error occurs, stating that /deps/rh/dsp/dsp.spd.xml could not be found. When the Device is launched in the Domain, the Domain Manager complains "error while loading shared libraries: libdsp.so.0: cannot open shared object file: No such file or directory".

I would like to be able to use the REDHAWK Shared Libraries with Devices in the same manner as Components.

I have no problem launching Components with a similar set up. I have printed out the LD_LIBRARY_PATH in the constructor method of Components, and observed that the necessary paths are being set for me. When launched in the Sandbox, the LD_LIBRARY_PATH includes paths to the dependencies in $SDRROOT/dom/deps. When launched in the Domain, the dependencies are cached inside $SDRROOT/dev, and the LD_LIBRARY_PATH includes these paths.

I was able to get my Device to launch in the Sandbox by copying $SDRROOT/dom/deps to $SDRROOT/dev/. The /deps/rh/dsp/dsp.spd.xml file was now being found. The LD_LIBRARY_PATH now included paths to the dependencies in $SDRROOT/dev/deps (to my surprise, this also means the seemingly required pkgconfig file is not determining these paths). Does this mean $SDRROOT/dev should have its own deps? Why are the Devices looking here and not in $SDRROOT/dom?

Copying $SDRROOT/dom/deps to $SDRROOT/dev/ did not allow me to launch the device in the Domain. It still cannot open libdsp.so.0.

I encounter this same issue with other Shared Libraries as well. This includes my own, and the "rh" Shared Libraries included with my REDHAWK installation (blueFileLib, fftlib, RedhawkDevUtils).

Am I missing something that would allow me to use Shared Libraries with a Device? Or is this only supported for Components?

答:
REDHAWK shared libraries are really meant for use with components not devices. Consider a setup where your domain is on machine A, and you have several GPPs running on different machines. You don't want to have to manage all the application dependencies across all the GPPs, and in fact some applications may have conflicting dependency versions. These issues are solved by REDHAWK shared libraries. When you launch your application the domain will copy all of the components executables as well as their dependencies over to the GPP and into its own folder. Something then needs to set the LD_LIBRARY_PATH prior to launching the executable. This occurs here via the LoadableDevice class.

For devices however they run on a node and are not deployed via the domain. Or started by a LoadableDevice. They are started and run by hand by the user on a specific hardware resource through the nodeBooter executable and a DeviceManager so it is up to the user to make sure that hardware resource has all the runtime dependencies.

If you really wanted to you could build the REDHAWK DSP library and install it into a system directory:

```<code>  ./reconf
  ./configure --prefix=/usr/local --libdir=/usr/local/lib
  make -j3
  sudo make install
</code>```

This will install the DSP library into /usr/local/lib rather than the SDRROOT however it will also put the XML files into odd places in /usr/local which may not be what you want either.

Body:
REDHAWK shared libraries are really meant for use with components not devices. Consider a setup where your domain is on machine A, and you have several GPPs running on different machines. You don't want to have to manage all the application dependencies across all the GPPs, and in fact some applications may have conflicting dependency versions. These issues are solved by REDHAWK shared libraries. When you launch your application the domain will copy all of the components executables as well as their dependencies over to the GPP and into its own folder. Something then needs to set the LD_LIBRARY_PATH prior to launching the executable. This occurs here via the LoadableDevice class.

For devices however they run on a node and are not deployed via the domain. Or started by a LoadableDevice. They are started and run by hand by the user on a specific hardware resource through the nodeBooter executable and a DeviceManager so it is up to the user to make sure that hardware resource has all the runtime dependencies.

If you really wanted to you could build the REDHAWK DSP library and install it into a system directory:

  ./reconf
  ./configure --prefix=/usr/local --libdir=/usr/local/lib
  make -j3
  sudo make install

This will install the DSP library into /usr/local/lib rather than the SDRROOT however it will also put the XML files into odd places in /usr/local which may not be what you want either.


问:
Bootstrap Equal Column Heights
I am trying to make my Bootstrap column's all the same height. Right now if one column has more content than another the columns float around and things don't look "square".

Here is a fiddle example of what I mean:

https://jsfiddle.net/jjq9gygr/

I have tried the display: flex approach but since my html does not have a new .row container for every 3 col-xs-4 columns, all the columns go on the same row instead of wrapping to the next line after 3 columns. I hope that makes sense.

If there is a way to keep the HTML as is and get the result I am after that would be great. Any ideas or recommendations are helpful.

```<code><div class="container">
<div class="row">
    <div class="col-xs-4 red">
  <h3>
  Column 1
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 pink">
<h3>
  Column 2
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 yellow">
  <h3>
  Column 3
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 orange">
  <h3>
  Column 4
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 blue">
  <h3>
  Column 5
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 green">
  <h3>
  Column 6
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
    <div class="col-xs-4 navy">
  <h3>
  Column 7
  </h3>
        <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>
</div>
</code>```

答:
Tell your rows flex containers and tell them to wrap.

```<code>.row {
    display: flex;
    flex-wrap: wrap;
}
</code>```

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
.row {
  display: flex;
  flex-wrap: wrap;
}

.col-xs-4 {
  margin-bottom: 30px;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.yellow {
  background-color: yellow;
}

.orange {
  background-color: orange;
}

.blue {
  background-color: MediumTurquoise;
}

.green {
  background-color: green;
}

.navy {
  background-color: PaleGoldenRod;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">

    <div class="col-xs-4 red">
      <h3>Column 1</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 pink">
      <h3>Column 2</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 yellow">
      <h3>Column 3</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 orange">
      <h3>Column 4</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 blue">
      <h3>Column 5</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 green">
      <h3>Column 6</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 navy">
      <h3>Column 7</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

  </div>
</div></code>```

If you're just starting your project you could switch to Bootstrap 4 which has flexbox baked into the grid system. Since BS4 doesn't have xs you'd need to make a minor adjustment to your column classes from .col-xs-4 to .col-4.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');

.col-4 {
  margin-bottom: 30px;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.yellow {
  background-color: yellow;
}

.orange {
  background-color: orange;
}

.blue {
  background-color: MediumTurquoise;
}

.green {
  background-color: green;
}

.navy {
  background-color: PaleGoldenRod;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="row">

    <div class="col-4 red">
      <h3>Column 1</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 pink">
      <h3>Column 2</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 yellow">
      <h3>Column 3</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 orange">
      <h3>Column 4</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 blue">
      <h3>Column 5</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 green">
      <h3>Column 6</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 navy">
      <h3>Column 7</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

  </div>
</div></code>```

Title: Bootstrap Equal Column Heights

Body:
I am trying to make my Bootstrap column's all the same height. Right now if one column has more content than another the columns float around and things don't look "square".

Here is a fiddle example of what I mean:

https://jsfiddle.net/jjq9gygr/

I have tried the display: flex approach but since my html does not have a new .row container for every 3 col-xs-4 columns, all the columns go on the same row instead of wrapping to the next line after 3 columns. I hope that makes sense.

If there is a way to keep the HTML as is and get the result I am after that would be great. Any ideas or recommendations are helpful.

  Column 1

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 2

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 3

Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 4

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 5

Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 6

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

  Column 7

Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text.

Body:
Tell your rows flex containers and tell them to wrap.

.row {
    display: flex;
    flex-wrap: wrap;
}

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');
.row {
  display: flex;
  flex-wrap: wrap;
}

.col-xs-4 {
  margin-bottom: 30px;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.yellow {
  background-color: yellow;
}

.orange {
  background-color: orange;
}

.blue {
  background-color: MediumTurquoise;
}

.green {
  background-color: green;
}

.navy {
  background-color: PaleGoldenRod;
}

<div class="container">
  <div class="row">

    <div class="col-xs-4 red">
      <h3>Column 1</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 pink">
      <h3>Column 2</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 yellow">
      <h3>Column 3</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 orange">
      <h3>Column 4</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 blue">
      <h3>Column 5</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 green">
      <h3>Column 6</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-xs-4 navy">
      <h3>Column 7</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

  </div>
</div>

If you're just starting your project you could switch to Bootstrap 4 which has flexbox baked into the grid system. Since BS4 doesn't have xs you'd need to make a minor adjustment to your column classes from .col-xs-4 to .col-4.

@import url('https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css');

.col-4 {
  margin-bottom: 30px;
}

.red {
  background-color: red;
}

.pink {
  background-color: pink;
}

.yellow {
  background-color: yellow;
}

.orange {
  background-color: orange;
}

.blue {
  background-color: MediumTurquoise;
}

.green {
  background-color: green;
}

.navy {
  background-color: PaleGoldenRod;
}

<div class="container">
  <div class="row">

    <div class="col-4 red">
      <h3>Column 1</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 pink">
      <h3>Column 2</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 yellow">
      <h3>Column 3</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 orange">
      <h3>Column 4</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 blue">
      <h3>Column 5</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 green">
      <h3>Column 6</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

    <div class="col-4 navy">
      <h3>Column 7</h3>
      <p>Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. Differnt amount of text. </p>
    </div>

  </div>
</div>


问:
Typically long running query?
I inherited a poorly designed SQL Server implementation, with horrible database schemas, and several pitifully slow queries/views that take hours, or even days, to execute.

I'm curious: What might an experienced DBA/SQL programmer consider to be an unusually long time for a query to take? In my professional experience I'm not used to seeing queries (for views or reports, etc) that take more than maybe an hour or two to run. We have several here that take 1-2 days or more!

(This database has no relationships, no Primary Keys, no Foreign Keys, hardly any indexes, duplicate data all over the place, old data that shouldn't even be in the tables, temp tables everywhere, and so on...ugh!)

What do you consider within the realm of acceptable or normal for a lengthy query process?

I'm trying to do a sanity check to determine how awful this database really is...

答:
This isn't an answer to your question, it's just easier to offer this script to you here than in a comment.

You might want to run this query and see what SQL Server thinks are the missing indexes it needs to perform better (a short-term solution while you migrate to your new schema and database).  DO NOT BLINDLY APPLY THESE INDEXES. These are merely suggestions for you to consider, that SQL Server itself has identified as being useful when it runs.  You might select one or two, perhaps tweaking include columns, and AFTER TESTING, apply some of them to help you speed up your existing system (I forget where this query came from, so I'm sadly unable to attribute the original author):

```<code>SELECT
  migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,
  (migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS [cumulative_impact],
  OBJECT_NAME(OBJECT_ID) as TableName,
  'CREATE INDEX [missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
  + '_' + LEFT (PARSENAME(mid.statement, 1), 32) + ']'
  + ' ON ' + mid.statement
  + ' (' + ISNULL (mid.equality_columns,'')
    + CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END
    + ISNULL (mid.inequality_columns, '')
  + ')'
  + ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
  migs.*, mid.database_id, mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) > 10
  AND database_id = DB_ID()
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC
</code>```

Further, you can use the following script to find the "longest running queries" (along with their SQL Plans).  There's a TON of information here, so play with the ORDER BY to bring different kinds of issues to your attention at the top (for instance, the longest running queries might run only once or twice, while one that runs thousand of times might not take SO long, but might consume far more resources all told):

```<code>SELECT [St].Text,
       [Qp].[Query_Plan],
       [Qs].*
  FROM (SELECT TOP 50 *
          FROM [Sys].[Dm_Exec_Query_Stats]
         ORDER BY [Total_Worker_Time] DESC
) AS [Qs]
       CROSS APPLY [Sys].[Dm_Exec_Sql_Text] ([Qs].[Sql_Handle]) AS [St]
       CROSS APPLY [Sys].[Dm_Exec_Query_Plan] ([Qs].[Plan_Handle]) AS [Qp]
 WHERE ([Qs].[Max_Worker_Time] > 300 OR [Qs].[Max_Elapsed_Time] > 300)
   AND [Qs].execution_count > 1
 ORDER BY min_elapsed_time DESC, max_elapsed_time DESC
</code>```

These queries only return data from running instances.  Stopping and restarting SQL Server erases all the collected data, so these queries are only really valuable for systems that have been up and running in "real world" situations for a while.

I hope you find these useful.

Title: Typically long running query?

Body:
This isn't an answer to your question, it's just easier to offer this script to you here than in a comment.

You might want to run this query and see what SQL Server thinks are the missing indexes it needs to perform better (a short-term solution while you migrate to your new schema and database).  DO NOT BLINDLY APPLY THESE INDEXES. These are merely suggestions for you to consider, that SQL Server itself has identified as being useful when it runs.  You might select one or two, perhaps tweaking include columns, and AFTER TESTING, apply some of them to help you speed up your existing system (I forget where this query came from, so I'm sadly unable to attribute the original author):

SELECT
  migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) AS improvement_measure,
  (migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans)) AS [cumulative_impact],
  OBJECT_NAME(OBJECT_ID) as TableName,
  'CREATE INDEX [missing_index_' + CONVERT (varchar, mig.index_group_handle) + '_' + CONVERT (varchar, mid.index_handle)
  + '_' + LEFT (PARSENAME(mid.statement, 1), 32) + ']'
  + ' ON ' + mid.statement
  + ' (' + ISNULL (mid.equality_columns,'')
    + CASE WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL THEN ',' ELSE '' END
    + ISNULL (mid.inequality_columns, '')
  + ')'
  + ISNULL (' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement,
  migs.*, mid.database_id, mid.[object_id]
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (migs.user_seeks + migs.user_scans) > 10
  AND database_id = DB_ID()
ORDER BY migs.avg_total_user_cost * migs.avg_user_impact * (migs.user_seeks + migs.user_scans) DESC

Further, you can use the following script to find the "longest running queries" (along with their SQL Plans).  There's a TON of information here, so play with the ORDER BY to bring different kinds of issues to your attention at the top (for instance, the longest running queries might run only once or twice, while one that runs thousand of times might not take SO long, but might consume far more resources all told):

SELECT [St].Text,
       [Qp].[Query_Plan],
       [Qs].*
  FROM (SELECT TOP 50 *
          FROM [Sys].[Dm_Exec_Query_Stats]
         ORDER BY [Total_Worker_Time] DESC
) AS [Qs]
       CROSS APPLY [Sys].[Dm_Exec_Sql_Text] ([Qs].[Sql_Handle]) AS [St]
       CROSS APPLY [Sys].[Dm_Exec_Query_Plan] ([Qs].[Plan_Handle]) AS [Qp]
 WHERE ([Qs].[Max_Worker_Time] > 300 OR [Qs].[Max_Elapsed_Time] > 300)
   AND [Qs].execution_count > 1
 ORDER BY min_elapsed_time DESC, max_elapsed_time DESC

These queries only return data from running instances.  Stopping and restarting SQL Server erases all the collected data, so these queries are only really valuable for systems that have been up and running in "real world" situations for a while.

I hope you find these useful.


问:
angular template enum is undefined in controller function
I have the following in my angular(4) app:

```<code>export enum RegisterAccomodationStatus {
    noFixedAbode = 1,
    sofaSurfing = 2,
    accommodation = 3,
    other = 4
}
</code>```

Within my template I have:

```<code><button (click)="setCurrentAccomStatus(attendance, registerAccomodationStatus.noFixedAbode)" type="button" class="btn btn-default">NFA</button>
<button (click)="setCurrentAccomStatus(attendance, registerAccomodationStatus.sofaSurfing)" type="button" class="btn btn-default">Sofa</button>
</code>```

I set a property in my component:

```<code>registerAccomodationStatus: RegisterAccomodationStatus = RegisterAccomodationStatus.other;
</code>```

And then finally my function:

```<code>setCurrentAccomStatus(registerAttendance: RegisterAttendance, accomStatusId: RegisterAccomodationStatus) {
        console.log(accomStatusId);
        registerAttendance.accomodationStatus = accomStatusId;

        this.registerService.updateGuestAttendance(registerAttendance)
            .subscribe(registerAtt => registerAttendance = registerAtt);
    }
</code>```

When clicking one of the buttons console.log(accomStatusId); is giving undefined but I'm following the examples I've found on the net to do this.

What am I doing wrong?

答:
You should define property like:

```<code>registerAccomodationStatus = RegisterAccomodationStatus;
</code>```

Plunker Example

Body:
I have the following in my angular(4) app:

export enum RegisterAccomodationStatus {
    noFixedAbode = 1,
    sofaSurfing = 2,
    accommodation = 3,
    other = 4
}

Within my template I have:

<button (click)="setCurrentAccomStatus(attendance, registerAccomodationStatus.noFixedAbode)" type="button" class="btn btn-default">NFA</button>
<button (click)="setCurrentAccomStatus(attendance, registerAccomodationStatus.sofaSurfing)" type="button" class="btn btn-default">Sofa</button>

I set a property in my component:

registerAccomodationStatus: RegisterAccomodationStatus = RegisterAccomodationStatus.other;

And then finally my function:

setCurrentAccomStatus(registerAttendance: RegisterAttendance, accomStatusId: RegisterAccomodationStatus) {
        console.log(accomStatusId);
        registerAttendance.accomodationStatus = accomStatusId;

        this.registerService.updateGuestAttendance(registerAttendance)
            .subscribe(registerAtt => registerAttendance = registerAtt);
    }

When clicking one of the buttons console.log(accomStatusId); is giving undefined but I'm following the examples I've found on the net to do this.

What am I doing wrong?

Body:
You should define property like:

registerAccomodationStatus = RegisterAccomodationStatus;

Plunker Example


问:
Drawing traffic light, Error in passing of variables I think
I'm trying to  fill each circle with a colour. The paintComponent method is supposed to create the general outline of a traffic light.
Then the other methods are supposed to fill each circle with a different color, depending on what color the traffic light is going to be. I get the error, that it cant find symbol( e.g

TrafficLight.java:56: error: cannot find symbol
        g2.fill(circle3);

I didnt think I had to pass the circle variables into the other methods, if they were in the same class. I tried adding the circle variables and then i get identifier expected. Pretty sure there's something about the passing of variables that im not getting, but any help would be appreciated

```<code>import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class TrafficLight extends JComponent
{
public void paintComponent(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    Rectangle box= new Rectangle(100,800,200,700);
    g2.setPaint(Color.BLACK);
    g2.fill(box);
    g2.draw(box);

    Ellipse2D.Double circle1=new Ellipse2D.Double(200,200,200,200);
    g2.draw(circle1);

    Ellipse2D.Double circle2=new Ellipse2D.Double(200,200,200,400);
    g2.draw(circle2);

    Ellipse2D.Double circle3=new Ellipse2D.Double(200,200,200,600);
    g2.draw(circle3);
}

public void drawRed(Graphics g)
{
    Graphics2D g2=(Grpahics2D) g;

    g2.setPaint(Color.RED);
    g2.fill(circle1);
    g2.setPaint(Color.BLACK);
    g2.fill(circle2);
    g2.fill(circle3);
}

public void drawGreen(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    g2.setPaint(Color.GREEN);
    g2.fill(circle3);
    g2.setPaint(Color.BLACK);
    g2.fill(circle2);
    g2.fill(circle1);
}

public void drawYellow(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    g2.setPaint(Color.YELLOW);
    g2.fill(circle2);
    g2.setPaint(Color.BLACK);
    g2.fill(circle1);
    g2.fill(circle3);
}
</code>```

}

答:
The entire code is missing.
But the general solution is to have the paintComponent method do all.
So have a state red/green/yellow.

```<code>public class TrafficLight extends JComponent {

    public enum Light { RED, GREEN, YELLOW, BLACK }

    private Light light = Light.BLACK;

    public void setLight(Light light) {
        this.light = light;
        repaint(50L); // Repaint almost immediately.
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        ...
        // Draw red bulb
        g2.setPaint(light == Light.RED ? Color.RED : Color.BLACK);
        ...
        // Draw yellow bulb
        g2.setPaint(light == Light.YELLOW ? Color.YELLOW : Color.BLACK);
        ...
        // Draw green bulb
        g2.setPaint(light == Light.GREEN ? Color.GREEN : Color.BLACK);
</code>```

Switching the light then alters the state and causes a repaint. There are some repaint methods.

Instead of the enum one might use Color light;, but that is not so clear.
Also consider an enum value BLACK, for semaphores without electricity.

To handle automatic timed switching, one might use a swing Timer.

Body:
I'm trying to  fill each circle with a colour. The paintComponent method is supposed to create the general outline of a traffic light.
Then the other methods are supposed to fill each circle with a different color, depending on what color the traffic light is going to be. I get the error, that it cant find symbol( e.g

TrafficLight.java:56: error: cannot find symbol
        g2.fill(circle3);

I didnt think I had to pass the circle variables into the other methods, if they were in the same class. I tried adding the circle variables and then i get identifier expected. Pretty sure there's something about the passing of variables that im not getting, but any help would be appreciated

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

public class TrafficLight extends JComponent
{
public void paintComponent(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    Rectangle box= new Rectangle(100,800,200,700);
    g2.setPaint(Color.BLACK);
    g2.fill(box);
    g2.draw(box);

    Ellipse2D.Double circle1=new Ellipse2D.Double(200,200,200,200);
    g2.draw(circle1);

    Ellipse2D.Double circle2=new Ellipse2D.Double(200,200,200,400);
    g2.draw(circle2);

    Ellipse2D.Double circle3=new Ellipse2D.Double(200,200,200,600);
    g2.draw(circle3);
}

public void drawRed(Graphics g)
{
    Graphics2D g2=(Grpahics2D) g;

    g2.setPaint(Color.RED);
    g2.fill(circle1);
    g2.setPaint(Color.BLACK);
    g2.fill(circle2);
    g2.fill(circle3);
}

public void drawGreen(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    g2.setPaint(Color.GREEN);
    g2.fill(circle3);
    g2.setPaint(Color.BLACK);
    g2.fill(circle2);
    g2.fill(circle1);
}

public void drawYellow(Graphics g)
{
    Graphics2D g2= (Graphics2D) g;

    g2.setPaint(Color.YELLOW);
    g2.fill(circle2);
    g2.setPaint(Color.BLACK);
    g2.fill(circle1);
    g2.fill(circle3);
}

}

Body:
The entire code is missing.
But the general solution is to have the paintComponent method do all.
So have a state red/green/yellow.

public class TrafficLight extends JComponent {

    public enum Light { RED, GREEN, YELLOW, BLACK }

    private Light light = Light.BLACK;

    public void setLight(Light light) {
        this.light = light;
        repaint(50L); // Repaint almost immediately.
    }

    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        ...
        // Draw red bulb
        g2.setPaint(light == Light.RED ? Color.RED : Color.BLACK);
        ...
        // Draw yellow bulb
        g2.setPaint(light == Light.YELLOW ? Color.YELLOW : Color.BLACK);
        ...
        // Draw green bulb
        g2.setPaint(light == Light.GREEN ? Color.GREEN : Color.BLACK);

Switching the light then alters the state and causes a repaint. There are some repaint methods.

Instead of the enum one might use Color light;, but that is not so clear.
Also consider an enum value BLACK, for semaphores without electricity.

To handle automatic timed switching, one might use a swing Timer.


问:
Windows UI Automation tools (Visual UIAVerify, Inspect.exe) recognizes the Buttons as Pane
I am using UI Automation library - TestStack.White to automate a Windows Application, where I utilize Inspect.exe to get the UI Elements from the WinForms. I have had no issues with the Inspect.exe so far except currently I am stuck with an issue in my development machine where the tool started recognizing the "Buttons" as "Pane" and the behavior is same across Visual UIA Verify, TestStack(White). Eventually all the tests are getting failed since it couldn't identify the Buttons (returns Null).

Here's what it looks like now,

[]

Here's what it used to look and it looks in a Fresh VM,

Expected,
[]

Can someone please through some light regarding this behavior or point out what would have gone wrong here ?

Thanks in Advance !

答:
Hmm... It looks like a bug in UIAutomationCore.dll or a target application issue. I think you can't do something with that on client side. But some workarounds are possible. It's still recognized as a class name with BUTTON inside. So it's possible to do some part of your automation with a tool that can support both UI Automation (for complicated controls like WinForms list views etc) and Win32 API (like here, when it has NativeWindowHandle and adequate ClassName).

If you can consider changing the automation tool, one of the options is pywinauto. It can use Win32 API or UI Automation under the hood by your choice. The high level API is almost the same. So you can easily switch between 2 backends for different actions (having 2 different Application objects connected to one target app instance). Getting Started Guide will bring you initial guidance for the core concept.