问:
HSQL database user lacks privilege or object not found error
I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.

I created data base using the following details

```<code>Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA
</code>```

I created a table named ALBUM under "MYDB" schema

In spring configuration file:

```<code><bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dbcpDataSource" />
</bean>

<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:file:mydb" />
    <property name="username" value="SA" />
    <property name="password" value="SA" />
</bean>
</code>```

And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());

And It gives me exception:

```<code>org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</code>```

If I execute same query through SQL editor of hsqldb it executes fine.  Can you please help me with this.

答:
You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege.
Also change the url of database in spring configuration file accordingly when running DB in server mode.

Sample command to run DB in server mode
$java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test

Format of URL in configuration file
jdbc:hsqldb:hsql://localhost/Test

Body:
I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.

I created data base using the following details

Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA

I created a table named ALBUM under "MYDB" schema

In spring configuration file:

<bean id="jdbcTemplate"
    class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
    <constructor-arg ref="dbcpDataSource" />
</bean>

<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
    <property name="url" value="jdbc:hsqldb:file:mydb" />
    <property name="username" value="SA" />
    <property name="password" value="SA" />
</bean>

And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());

And It gives me exception:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

If I execute same query through SQL editor of hsqldb it executes fine.  Can you please help me with this.


来源: stackexchange

问:
Convert index to column names
I am trying to take the index of a dataframe and swap it with the column header names.

For example:

```<code>Index Header1 Header2 Header3                    Index   0  1  2  3

0                                                Header1

1                                       ===>     Header2

2                                                Header3

3
</code>```

答: See DataFrame.T, which will swap the rows and columns.

ContentLicense: CC BY-SA 4.0

Title: Convert index to column names

Body:
I am trying to take the index of a dataframe and swap it with the column header names.

For example:

Index Header1 Header2 Header3                    Index   0  1  2  3

0                                                Header1

1                                       ===>     Header2

2                                                Header3

3


答:
You can create a temporary table, populate it with the past 30 days and use that in your query. From PHP code:</p>

```<code>// create table with past 30 days
$buffer = "CREATE TEMPORARY TABLE IF NOT EXIST past_month (val DATETIME NOT NULL );";
$now = new DateTime(now);
for($i=30;$i>0;$i++)
{
    $buffer += "INSERT INTO past_month VALUES(" . $now . ");";
    $now->sub(new DateInterval('P1D'));
}
mysql_query($buffer);

// the query
$sql= "SELECT
           val,
           (SELECT COUNT(IP)
            FROM table
            WHERE DATE_FORMAT(CREATED_DATE,'%Y-%m-%d) = DATE_FORMAT(val,'%Y-%m-%d') As                UNIQUE_IPS
       FROM
           past_month";
$result = mysql_query($sql);
</code>```

ContentLicense: CC BY-SA 3.0

Title: How do I create an array of data for 30 days from database table where some dates are not entered?

Body:
Let's say you have a simple table with:

ID  IP                  CREATED_DATE
-------------------------------------------------------
1   111.111.111.111     2011-03-28 14:12:31
2   111.111.111.111     2011-03-29 03:38:12
3   222.222.222.222     2011-04-02 12:04:45
4   111.111.111.111     2011-04-02 22:13:23
5   333.333.333.333     2011-04-03 05:53:15
6   222.222.222.222     2011-04-05 02:13:51
7   111.111.111.111     2011-04-07 11:45:34

I need to query the last 30 days and get a count of unique ips and total rows per day even if there are no entries for that day. So days that are not entered would obviously just be 0 as the array value for both unique and total rows.

Body:
You can create a temporary table, populate it with the past 30 days and use that in your query. From PHP code:

// create table with past 30 days
$buffer = "CREATE TEMPORARY TABLE IF NOT EXIST past_month (val DATETIME NOT NULL );";
$now = new DateTime(now);
for($i=30;$i>0;$i++)
{
    $buffer += "INSERT INTO past_month VALUES(" . $now . ");";
    $now->sub(new DateInterval('P1D'));
}
mysql_query($buffer);

// the query
$sql= "SELECT
           val,
           (SELECT COUNT(IP)
            FROM table
            WHERE DATE_FORMAT(CREATED_DATE,'%Y-%m-%d) = DATE_FORMAT(val,'%Y-%m-%d') As                UNIQUE_IPS
       FROM
           past_month";
$result = mysql_query($sql);


问:
Oracle how to transpose multiple rows into aggregate column
I have table

```<code>OWNER       TABLE_NAME      COLUMN_NAME     ATTRIBUTE_ID
-------     -------         -------         -------
USER        CC_CASES        X_OIB           0
USER        CC_CASES        X_OIB_2         0
USER        CC_CASES        X_JMBG          1
USER        CC_CASES        X_JMBG_2        1
USER        CC_CASES        FIRST_NAME      2
USER        CC_CASES        FIRST_NAME_2    2
USER        CC_CASES        LAST_NAME       3
USER        CC_CASES        LAST_NAME_2     3
SUBSCRIBER  CC_CONTACT      X_OIB           0
SUBSCRIBER  CC_CONTACT      X_MB_OIB        0
SUBSCRIBER  CC_CONTACT      X_JMBG          1
SUBSCRIBER  CC_CONTACT      X_X_JMBG_2      1
SUBSCRIBER  CC_CONTACT      FIRST_NAME      2
SUBSCRIBER  CC_CONTACT      LAST_NAME       3
</code>```

And I'm trying to transpose it to put each different ID in a different columns, and group it by table name and column name separated by comma.

I need output like:

```<code>OWNER       TABLE_NAME      OIB_COL         JMBG_COL            FIRST_NAME_COL              LAST_NAME_COL
-------     -------         -------         -------             -------                     -------
USER        CC_CASES        X_OIB,X_OIB_2   X_JMBG,X_JMBG_2     FIRST_NAME,FIRST_NAME_2     LAST_NAME,LAST_NAME_2
CC_CASES    CC_CONTACT      X_OIB,X_MB_OIB  X_JMBG,X_X_JMBG_2   FIRST_NAME                  LAST_NAME
</code>```

I have about 8 different id. I tried to do with a PIVOT function. I also tried with a LISTAGG function, but I can't get the result I want.

答:
You can use conditional aggregation:

```<code>select
    owner,
    table_name,
    listagg(case when attribute_id = 0 then column_name end, ',')
        within group(order by column_name) oib_col,
    listagg(case when attribute_id = 1 then column_name end, ',')
        within group(order by column_name) jmbg_col,
    listagg(case when attribute_id = 2 then column_name end, ',')
        within group(order by column_name) first_name_col,
    listagg(case when attribute_id = 3 then column_name end, ',')
        within group(order by column_name) last_name_col
from mytable
group by owner, table_name
order by owner, table_name
</code>```

Demo on DB Fiddle:

```
OWNER    | TABLE_NAME | OIB_COL        | JMBG_COL          | FIRST_NAME_COL          | LAST_NAME_COL
:------- | :--------- | :------------- | :---------------- | :---------------------- | :--------------------
CC_CASES | CC_CONTACT | X_MB_OIB,X_OIB | X_JMBG,X_X_JMBG_2 | FIRST_NAME              | LAST_NAME
USER     | CC_CASES   | X_OIB,X_OIB_2  | X_JMBG,X_JMBG_2   | FIRST_NAME,FIRST_NAME_2 | LAST_NAME,LAST_NAME_2
```

Body:
I have table

OWNER       TABLE_NAME      COLUMN_NAME     ATTRIBUTE_ID
-------     -------         -------         -------
USER        CC_CASES        X_OIB           0
USER        CC_CASES        X_OIB_2         0
USER        CC_CASES        X_JMBG          1
USER        CC_CASES        X_JMBG_2        1
USER        CC_CASES        FIRST_NAME      2
USER        CC_CASES        FIRST_NAME_2    2
USER        CC_CASES        LAST_NAME       3
USER        CC_CASES        LAST_NAME_2     3
SUBSCRIBER  CC_CONTACT      X_OIB           0
SUBSCRIBER  CC_CONTACT      X_MB_OIB        0
SUBSCRIBER  CC_CONTACT      X_JMBG          1
SUBSCRIBER  CC_CONTACT      X_X_JMBG_2      1
SUBSCRIBER  CC_CONTACT      FIRST_NAME      2
SUBSCRIBER  CC_CONTACT      LAST_NAME       3

And I'm trying to transpose it to put each different ID in a different columns, and group it by table name and column name separated by comma.

I need output like:

OWNER       TABLE_NAME      OIB_COL         JMBG_COL            FIRST_NAME_COL              LAST_NAME_COL
-------     -------         -------         -------             -------                     -------
USER        CC_CASES        X_OIB,X_OIB_2   X_JMBG,X_JMBG_2     FIRST_NAME,FIRST_NAME_2     LAST_NAME,LAST_NAME_2
CC_CASES    CC_CONTACT      X_OIB,X_MB_OIB  X_JMBG,X_X_JMBG_2   FIRST_NAME                  LAST_NAME

I have about 8 different id. I tried to do with a PIVOT function. I also tried with a LISTAGG function, but I can't get the result I want.

Body:
You can use conditional aggregation:

select
    owner,
    table_name,
    listagg(case when attribute_id = 0 then column_name end, ',')
        within group(order by column_name) oib_col,
    listagg(case when attribute_id = 1 then column_name end, ',')
        within group(order by column_name) jmbg_col,
    listagg(case when attribute_id = 2 then column_name end, ',')
        within group(order by column_name) first_name_col,
    listagg(case when attribute_id = 3 then column_name end, ',')
        within group(order by column_name) last_name_col
from mytable
group by owner, table_name
order by owner, table_name

Demo on DB Fiddle:

OWNER    | TABLE_NAME | OIB_COL        | JMBG_COL          | FIRST_NAME_COL          | LAST_NAME_COL
:------- | :--------- | :------------- | :---------------- | :---------------------- | :--------------------
CC_CASES | CC_CONTACT | X_MB_OIB,X_OIB | X_JMBG,X_X_JMBG_2 | FIRST_NAME              | LAST_NAME
USER     | CC_CASES   | X_OIB,X_OIB_2  | X_JMBG,X_JMBG_2   | FIRST_NAME,FIRST_NAME_2 | LAST_NAME,LAST_NAME_2


问:
In Brian Gladman's AES implementation, how is aes_encrypt_key128 being mapped to aes_xi?
I'm able to follow the code path up to a certain point.  Briefly:

The program accepts an ASCII hexadecimal string and converts it to binary.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L366-L382

If arg[3] is an “E”, it defines an aes_encrypt_ctx struct and passes the key, the calculated key_len value, and the aes_encrypt_ctx stuct to aes_encrypt_key.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L409-L412

aes_encrypt_key is defined in aeskey.c.  Depending on key_len, the function aes_encrypt_key<NNN> is called.  They key and the struct are passed to the function.  https://github.com/BrianGladman/aes/blob/master/aeskey.c#L545-L547

But where is the aes_encrypt_key128 function?

This line appears to be my huckleberry:

```<code>#  define aes_xi(x) aes_ ## x
</code>```

So hopefully I'm onto something.  It's mapping aes_encrypt_key128 to aes_xi(encrypt_key128), right?

```<code>AES_RETURN aes_xi(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1])
{   uint32_t    ss[4];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#ifdef ENC_KS_UNROLL
    ke4(cx->ks, 0);  ke4(cx->ks, 1);
    ke4(cx->ks, 2);  ke4(cx->ks, 3);
    ke4(cx->ks, 4);  ke4(cx->ks, 5);
    ke4(cx->ks, 6);  ke4(cx->ks, 7);
    ke4(cx->ks, 8);
#else
    {   uint32_t i;
        for(i = 0; i < 9; ++i)
            ke4(cx->ks, i);
    }
#endif
    ke4(cx->ks, 9);
    cx->inf.l = 0;
    cx->inf.b[0] = 10 * AES_BLOCK_SIZE;

#ifdef USE_VIA_ACE_IF_PRESENT
    if(VIA_ACE_AVAILABLE)
        cx->inf.b[1] = 0xff;
#endif
    MARK_AS_ENCRYPTION_CTX(cx);
    return EXIT_SUCCESS;
}
</code>```

I see some pattern replacement happening here.  I guess at this point I was wondering if you could point me to the docs that explain this feature of #define?

答:
Here are some docs which explain token concatenation. You can also take this as a suggestion about where to search systematically for reliable docs:

The C standard. At this website you can download WG14 N1570, which is quite similar to the C11 standard (it's a pre-standard draft, but it's basically the same as the standard except you don't have to pay for it.) There's an HTML version of this document at http://port70.net/~nsz/c/c11/n1570.html, which is handy for constructing links. With that in mind, I can point you at the actual standard definition of ## in §6.10.3.3 of the standard.

The C standard can be a bit rough going if you're not already an expert in C. It makes very few concessions for learners. A more readable document is Gnu GCC's C Preprocessor (CPP) manual, although it is does not always distinguish between standard features and GCC extensions. Still, it's quite readable and there's lots of useful information. The ## operator is explained in Chapter 3.5

cppreference.com is better known as a C++ reference site, but it also contains documentation about C. It's language is almost as telegraphic as the C++/C standards, and it is not always 100% accurate (although it is very good), but it has several advantages. For one thing, it combines documentation for different standard versions, so it is really useful for knowing when a feature entered the language (and consequently which compiler version you will need to use the feature). Also, it is well cross-linked, so it's very easy to navigate. Here's what it has to say about the preprocessor; you'll find documentation about ## here.

Body:
I'm able to follow the code path up to a certain point.  Briefly:

The program accepts an ASCII hexadecimal string and converts it to binary.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L366-L382

If arg[3] is an “E”, it defines an aes_encrypt_ctx struct and passes the key, the calculated key_len value, and the aes_encrypt_ctx stuct to aes_encrypt_key.  https://github.com/BrianGladman/aes/blob/master/aesxam.c#L409-L412

aes_encrypt_key is defined in aeskey.c.  Depending on key_len, the function aes_encrypt_key<NNN> is called.  They key and the struct are passed to the function.  https://github.com/BrianGladman/aes/blob/master/aeskey.c#L545-L547

But where is the aes_encrypt_key128 function?

This line appears to be my huckleberry:

#  define aes_xi(x) aes_ ## x

So hopefully I'm onto something.  It's mapping aes_encrypt_key128 to aes_xi(encrypt_key128), right?

AES_RETURN aes_xi(encrypt_key128)(const unsigned char *key, aes_encrypt_ctx cx[1])
{   uint32_t    ss[4];

    cx->ks[0] = ss[0] = word_in(key, 0);
    cx->ks[1] = ss[1] = word_in(key, 1);
    cx->ks[2] = ss[2] = word_in(key, 2);
    cx->ks[3] = ss[3] = word_in(key, 3);

#ifdef ENC_KS_UNROLL
    ke4(cx->ks, 0);  ke4(cx->ks, 1);
    ke4(cx->ks, 2);  ke4(cx->ks, 3);
    ke4(cx->ks, 4);  ke4(cx->ks, 5);
    ke4(cx->ks, 6);  ke4(cx->ks, 7);
    ke4(cx->ks, 8);
#else
    {   uint32_t i;
        for(i = 0; i < 9; ++i)
            ke4(cx->ks, i);
    }
#endif
    ke4(cx->ks, 9);
    cx->inf.l = 0;
    cx->inf.b[0] = 10 * AES_BLOCK_SIZE;

#ifdef USE_VIA_ACE_IF_PRESENT
    if(VIA_ACE_AVAILABLE)
        cx->inf.b[1] = 0xff;
#endif
    MARK_AS_ENCRYPTION_CTX(cx);
    return EXIT_SUCCESS;
}

I see some pattern replacement happening here.  I guess at this point I was wondering if you could point me to the docs that explain this feature of #define?


问:
Test if something is not undefined in JavaScript
I'm checking if(response[0].title !== undefined), but I get the error:

Uncaught TypeError: Cannot read property 'title' of undefined.

答:
In some of these answers there is a fundamental misunderstanding about how to use typeof.

Incorrect

```<code>if (typeof myVar === undefined) {
</code>```

Correct

```<code>if (typeof myVar === 'undefined') {
</code>```

The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.

Addendum

Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.

```<code>let undefined = 42;
</code>```

And here is an example of how you can use this to prove the first method is incorrect:

https://jsfiddle.net/p6zha5dm/

Body:
In some of these answers there is a fundamental misunderstanding about how to use typeof.

Incorrect

if (typeof myVar === undefined) {

Correct

if (typeof myVar === 'undefined') {

The reason is that typeof returns a string. Therefore, you should be checking that it returned the string "undefined" rather than undefined (not enclosed in quotation marks), which is itself one of JavaScript's primitive types. The typeof operator will never return a value of type undefined.

Addendum

Your code might technically work if you use the incorrect comparison, but probably not for the reason you think. There is no preexisting undefined variable in JavaScript - it's not some sort of magic keyword you can compare things to. You can actually create a variable called undefined and give it any value you like.

let undefined = 42;

And here is an example of how you can use this to prove the first method is incorrect:

https://jsfiddle.net/p6zha5dm/


问:
How to verify self-signed certificate?
I use Net::Jabber::Client to send messages via XMPP.

The server I am connecting to uses self-signed certificate:

```<code>DEBUG: .../IO/Socket/SSL.pm:2853: new ctx 45728400
DEBUG: .../IO/Socket/SSL.pm:1540: start handshake
DEBUG: .../IO/Socket/SSL.pm:717: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:750: using SNI with hostname my.host.name
DEBUG: .../IO/Socket/SSL.pm:785: request OCSP stapling
DEBUG: .../IO/Socket/SSL.pm:806: set socket to non-blocking to enforce timeout=10
DEBUG: .../IO/Socket/SSL.pm:819: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:822: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:832: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:842: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:862: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:819: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:2754: did not get stapled OCSP response
DEBUG: .../IO/Socket/SSL.pm:2707: ok=0 [0] /CN=my.host.name/CN=my.host.name
DEBUG: .../IO/Socket/SSL.pm:822: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:825: SSL connect attempt failed

DEBUG: .../IO/Socket/SSL.pm:825: local error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../IO/Socket/SSL.pm:828: fatal SSL error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../IO/Socket/SSL.pm:1963: downgrading SSL only, not closing socket
DEBUG: .../IO/Socket/SSL.pm:2875: free ctx 45728400 open=
DEBUG: .../IO/Socket/SSL.pm:2879: free ctx 45728400 callback
DEBUG: .../IO/Socket/SSL.pm:2886: OK free ctx 45728400
</code>```

I have found that I can pass SSL_fingerprint and/or SSL_verifycn_name to pass verification of self-signed certificate.

To make it just work I hack this

```<code>my %ssl_params = (
    SSL_verify_mode => $self->{SIDS}->{newconnection}->{ssl_verify},
    SSL_hostname    => 'my.host.name',
    SSL_verifycn_name => 'my.host.name',
);
</code>```

without success =(

I try to use ->get_fingerprint to obtain finger print and pass it to SSL_fingerprint parameter, but:

```<code>IO::Socket::SSL->start_SSL(
    $self->{SIDS}->{$sid}->{sock},
    $self->{SIDS}->{$sid}->{ssl_params}
) or die "$IO::Socket::SSL::SSL_ERROR";
</code>```

fail with error:

```<code>SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed at
</code>```

Which option to pass to IO::Socket::SSL to verify self-signed certificate?

答:
Typically this occurs when encrypting via localhost, where a certificate per se hardly plays a role.

Modules that involve IO::Socket::SSL can be used with an additional parameter to prevent crashing with "certificate verify failed".

To solve that issue in the long-term, at the top, add this line:

```<code>use IO::Socket::SSL qw(SSL_VERIFY_NONE);

$smtp = Net::SMTPS->new('localhost',
   doSSL => 'starttls',
   Port => 587,
   SSL_verify_mode => SSL_VERIFY_NONE
);
</code>```

Title: How to verify self-signed certificate?

Body:
I use Net::Jabber::Client to send messages via XMPP.

The server I am connecting to uses self-signed certificate:

DEBUG: .../IO/Socket/SSL.pm:2853: new ctx 45728400
DEBUG: .../IO/Socket/SSL.pm:1540: start handshake
DEBUG: .../IO/Socket/SSL.pm:717: ssl handshake not started
DEBUG: .../IO/Socket/SSL.pm:750: using SNI with hostname my.host.name
DEBUG: .../IO/Socket/SSL.pm:785: request OCSP stapling
DEBUG: .../IO/Socket/SSL.pm:806: set socket to non-blocking to enforce timeout=10
DEBUG: .../IO/Socket/SSL.pm:819: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:822: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:832: ssl handshake in progress
DEBUG: .../IO/Socket/SSL.pm:842: waiting for fd to become ready: SSL wants a read first
DEBUG: .../IO/Socket/SSL.pm:862: socket ready, retrying connect
DEBUG: .../IO/Socket/SSL.pm:819: call Net::SSLeay::connect
DEBUG: .../IO/Socket/SSL.pm:2754: did not get stapled OCSP response
DEBUG: .../IO/Socket/SSL.pm:2707: ok=0 [0] /CN=my.host.name/CN=my.host.name
DEBUG: .../IO/Socket/SSL.pm:822: done Net::SSLeay::connect -> -1
DEBUG: .../IO/Socket/SSL.pm:825: SSL connect attempt failed

DEBUG: .../IO/Socket/SSL.pm:825: local error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../IO/Socket/SSL.pm:828: fatal SSL error: SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
DEBUG: .../IO/Socket/SSL.pm:1963: downgrading SSL only, not closing socket
DEBUG: .../IO/Socket/SSL.pm:2875: free ctx 45728400 open=
DEBUG: .../IO/Socket/SSL.pm:2879: free ctx 45728400 callback
DEBUG: .../IO/Socket/SSL.pm:2886: OK free ctx 45728400

I have found that I can pass SSL_fingerprint and/or SSL_verifycn_name to pass verification of self-signed certificate.

To make it just work I hack this

my %ssl_params = (
    SSL_verify_mode => $self->{SIDS}->{newconnection}->{ssl_verify},
    SSL_hostname    => 'my.host.name',
    SSL_verifycn_name => 'my.host.name',
);

without success =(

I try to use ->get_fingerprint to obtain finger print and pass it to SSL_fingerprint parameter, but:

IO::Socket::SSL->start_SSL(
    $self->{SIDS}->{$sid}->{sock},
    $self->{SIDS}->{$sid}->{ssl_params}
) or die "$IO::Socket::SSL::SSL_ERROR";

fail with error:

SSL connect attempt failed error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed at

Which option to pass to IO::Socket::SSL to verify self-signed certificate?

Body:
Typically this occurs when encrypting via localhost, where a certificate per se hardly plays a role.

Modules that involve IO::Socket::SSL can be used with an additional parameter to prevent crashing with "certificate verify failed".

To solve that issue in the long-term, at the top, add this line:

use IO::Socket::SSL qw(SSL_VERIFY_NONE);

$smtp = Net::SMTPS->new('localhost',
   doSSL => 'starttls',
   Port => 587,
   SSL_verify_mode => SSL_VERIFY_NONE
);


问:
Data structure padding
What is data structure padding in c++ and how do i check the number of bytes padded bytes?</p>

```<code>class a { public: int x; int y; int z; };
</code>```

答:
```<code>struct A
{
    char c;
    int i;
};

int main(int argc, char *argv[])
{
    A a;

    cout << "sizeof struct = " << sizeof(A) << endl;

    cout << "sizeof items  = " << sizeof(a.c) + sizeof(a.i) << endl;

    return 0;
}
</code>```

Title: Data structure padding

Body:
What is data structure padding in c++ and how do i check the number of bytes padded bytes?

class a { public: int x; int y; int z; };


问:
How to bring object out of a for loop
I have the following method that should return a product object if its name attribute matches the input string.

```<code>public Product find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return product;
        }
   }
}
</code>```

Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?

答:
You can use stream and findFirst to return Optional with first matching Product or empty Optional

```<code>this.Products.stream()
             .filter(p->p.getName().equalsIgnoreCase(nameInput))
             .findFirst();
</code>```

You can also use orElse methods on Optional to return default value

Title: How to bring object out of a for loop

Body:
I have the following method that should return a product object if its name attribute matches the input string.

public Product find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return product;
        }
   }
}

Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?

Body:
You can use stream and findFirst to return Optional with first matching Product or empty Optional

this.Products.stream()
             .filter(p->p.getName().equalsIgnoreCase(nameInput))
             .findFirst();

You can also use orElse methods on Optional to return default value


答:
If you just want to swap the labels without transposing the values in the dataframe (assuming it is square):</p>

```<code>df.index, df.columns = df.columns, df.index
</code>```

Title: Convert index to column names

Body:
If you just want to swap the labels without transposing the values in the dataframe (assuming it is square):

df.index, df.columns = df.columns, df.index


问:
How do I capture a tap on a custom card view in a ZStack?
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

```<code>import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}
</code>```

答:
Thank you both, Natalia and Mac3n

It got me thinking and I've ended up using a VStack

Happy to hear any comments. I'm not sure it's the best approach.

I've done away with the offsets and used two frames in the card view - one for the rectangle and one for the ZStack. I'm still trying to figure out the math for the .frame on the VStack however. It seems to be a multiple of the number of cards + the real height of a card, plus some variable I can't pin down.

```<code>import SwiftUI

struct BetterCards: View {

    let multiplier:CGFloat = 6

    var body: some View {

        ScrollView {
            Text("HEADER").background(Color(.blue))
            VStack {
                CardView(title: " Card", color: .black)
                CardView(title: "adidas", color: .blue)
                CardView(title: "Puma", color: .green)
                CardView(title: "Le Crueset", color: .yellow)
//                CardView(title: "adidas", color: .blue)
//                CardView(title: "OnlyLyon", color: .green)
//                CardView(title: "Le Crueset", color: .yellow)
                CardView(title: "adidas", color: .blue)
                CardView(title: "Sandusk", color: .orange)
//                CardView(title: "Le Crueset", color: .pink)
                }
            .frame(width: 400, height: multiplier * 60 + (430 - ( 52 )))
            .padding()
            .background(Color.gray)
            Text("FOOTER").background(Color(.blue))
        }
        .background(Color.yellow)
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color

    var body: some View {
        ZStack {
             Rectangle()
                .fill(color)
                .cornerRadius(10)
                .frame(width: 370, height: 430)
            VStack {
                Text(title)
                    .font(.largeTitle)
                    .bold()
                    .foregroundColor(isYellow ? .yellow : .white)
                    .padding()
                Spacer()
                }
        }
        .frame(width: 370, height: 60)
        .onTapGesture {
                self.isYellow.toggle()
                print("Tapped: \(self.title)")
        }
        .shadow(radius: 2.0)
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}
</code>```

Body:
I'm trying pretty hard to recreate something like the Wallet view, but cannot really figure it out. I've hard-coded offsets into my ZStack, but of course I want to avoid that too. It seems like the offsets are keeping the taps from registering at all. Here is my code so far, tapping a card should change its title's colour between white and yellow.

Eventually, of course, I want to add animations to the stack of cards and be able to "pull" one from it place to make it the primary view. But I have to figure out how to catch the taps first...

I used this video as a base, but it doesn't really go as far as I'd like:

https://nsscreencast.com/episodes/399-swiftui-transforms-and-animations

import SwiftUI

struct BetterCards: View {
    var body: some View {

        ScrollView (.vertical) {
                ZStack {
                    CardView(title: "adidas", color: .blue, offset: 0.0)
                    CardView(title: "Le Crueset", color: .pink, offset: 90.0)
                    CardView(title: " Card", color: .black, offset: 180.0)
                    CardView(title: "Sandusk", color: .orange, offset: 270.0)
            }
        }
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color
    let offset: CGFloat

    var body: some View {

        Button(action: {
            self.isYellow.toggle()
        }) {
            ZStack {
                 Rectangle()
                    .fill(color)
                    .cornerRadius(10)
                    .frame(width: 320, height: 210)
                VStack {
                    Text(title)
                        .font(.largeTitle)
                        .bold()
                        .foregroundColor(isYellow ? .yellow : .white)
                        .padding()
                    Spacer()
                }

            }.shadow(radius: 2.0)
            .offset(x: 0, y: offset)

            }.onTapGesture {
            print("Tapped: \(self.title)")
        }
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}

Body:
Thank you both, Natalia and Mac3n

It got me thinking and I've ended up using a VStack

Happy to hear any comments. I'm not sure it's the best approach.

I've done away with the offsets and used two frames in the card view - one for the rectangle and one for the ZStack. I'm still trying to figure out the math for the .frame on the VStack however. It seems to be a multiple of the number of cards + the real height of a card, plus some variable I can't pin down.

import SwiftUI

struct BetterCards: View {

    let multiplier:CGFloat = 6

    var body: some View {

        ScrollView {
            Text("HEADER").background(Color(.blue))
            VStack {
                CardView(title: " Card", color: .black)
                CardView(title: "adidas", color: .blue)
                CardView(title: "Puma", color: .green)
                CardView(title: "Le Crueset", color: .yellow)
//                CardView(title: "adidas", color: .blue)
//                CardView(title: "OnlyLyon", color: .green)
//                CardView(title: "Le Crueset", color: .yellow)
                CardView(title: "adidas", color: .blue)
                CardView(title: "Sandusk", color: .orange)
//                CardView(title: "Le Crueset", color: .pink)
                }
            .frame(width: 400, height: multiplier * 60 + (430 - ( 52 )))
            .padding()
            .background(Color.gray)
            Text("FOOTER").background(Color(.blue))
        }
        .background(Color.yellow)
    }
}

struct CardView: View {

    @State var isYellow: Bool = false

    let title: String
    let color: Color

    var body: some View {
        ZStack {
             Rectangle()
                .fill(color)
                .cornerRadius(10)
                .frame(width: 370, height: 430)
            VStack {
                Text(title)
                    .font(.largeTitle)
                    .bold()
                    .foregroundColor(isYellow ? .yellow : .white)
                    .padding()
                Spacer()
                }
        }
        .frame(width: 370, height: 60)
        .onTapGesture {
                self.isYellow.toggle()
                print("Tapped: \(self.title)")
        }
        .shadow(radius: 2.0)
    }
}

struct BetterCards_Previews: PreviewProvider {
    static var previews: some View {
        BetterCards()
    }
}


问:
Line break gone after XSLT transformation
My XML:

```<code><root>
  <summary>
     <article_1>some data\n</article_1>
  </summary>
  <summary>
     <article_1>some data\n</article_1>
  </summary>
  .
  .
  .
</root>
</code>```

I am trying to copy all summary tags to separate files, but when XSLT transformation is done I am loosing line breaks in the newly created files.

My XSLT:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" version="1.0" encoding="UTF-8" standalone="yes"/>
<xsl:template match="summary">
  <xsl:result-document href="{@summary}.xml">
    <xsl:copy-of select="." />
  </xsl:result-document>
</xsl:template>
</xsl:stylesheet>
</code>```

What am I doing wrong, and why are there no line breaks in my newly created XML anymore?

答:
If your XML input uses CDATA, you can do  linefeed-treatment="preserve" in your XSL

Example:
XML input

```<code><data>
  <Alert>
        <![CDATA[PredniOD
         Ca32mg Mane
         Cholenthly]]>
   </Alert>
</data>
</code>```

XSL 1.0

```<code><fo:block linefeed-treatment="preserve">
     <xsl:value-of select="data/Alert" />
 </fo:block>
</code>```

Output

```<code> PredniOD
 Ca32mg Mane
 Cholenthly
</code>```

Other useful ones

white-space-collapse="false"
white-space-treatment="preserve"

Body:
My XML:

<root>

     <article_1>some data
</article_1>

     <article_1>some data
</article_1>

  .
  .
  .
</root>

I am trying to copy all summary tags to separate files, but when XSLT transformation is done I am loosing line breaks in the newly created files.

My XSLT:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" version="1.0" encoding="UTF-8" standalone="yes"/>
<xsl:template match="summary">
  <xsl:result-document href="{@summary}.xml">
    <xsl:copy-of select="." />
  </xsl:result-document>
</xsl:template>
</xsl:stylesheet>

What am I doing wrong, and why are there no line breaks in my newly created XML anymore?

Body:
If your XML input uses CDATA, you can do  linefeed-treatment="preserve" in your XSL

Example:
XML input

<data>
  <Alert>
        <![CDATA[PredniOD
         Ca32mg Mane
         Cholenthly]]>
   </Alert>
</data>

XSL 1.0

<fo:block linefeed-treatment="preserve">
     <xsl:value-of select="data/Alert" />
 </fo:block>

Output

 PredniOD
 Ca32mg Mane
 Cholenthly

Other useful ones

white-space-collapse="false"
white-space-treatment="preserve"


问:
How to fill a cell based on the result of an If Statement
Let's say that I have three columns: ID, Make, and Model. I want to be able to have an if-Statement check the cells containing "Make" and "Model", and if they are a certain grouping, I want excel to be able to return the value that should go into "ID".

I hope this example demonstrates what I am trying to accomplish.

```<code>Id      Make            Model
34138   Honda           Accord
1946    Acura           MDX
368     Toyota          Camry
</code>```

A column is "ID". B Column is "Make" C Column is "Model". Imagine ID is blank after Toyota Camry ID# 368 but Make and Model information is available in various combinations for hundreds of entries. I need the if Statement to check the B column and C Column and if "Honda" + "Accord" Lines up (there could be Honda Civic and the rest of the Honda fleet on this list) I want the ID to be put in automatically. If Honda and Accord, then ID = 34138

答:
Try -

```<code>=SUMPRODUCT((B2:B100="Honda")*(C2:C100="Accord")*A2:A100)
</code>```

or array formula -

```<code>{=INDEX(A2:A100,MATCH(1,(B2:B100="Honda")*(C2:C100="Accord"),0))}
</code>```

Array formula after editing is confirmed by pressing ctrl + shift + enter

Body:
Let's say that I have three columns: ID, Make, and Model. I want to be able to have an if-Statement check the cells containing "Make" and "Model", and if they are a certain grouping, I want excel to be able to return the value that should go into "ID".

I hope this example demonstrates what I am trying to accomplish.

Id      Make            Model
34138   Honda           Accord
1946    Acura           MDX
368     Toyota          Camry

A column is "ID". B Column is "Make" C Column is "Model". Imagine ID is blank after Toyota Camry ID# 368 but Make and Model information is available in various combinations for hundreds of entries. I need the if Statement to check the B column and C Column and if "Honda" + "Accord" Lines up (there could be Honda Civic and the rest of the Honda fleet on this list) I want the ID to be put in automatically. If Honda and Accord, then ID = 34138

Body:
Try -

=SUMPRODUCT((B2:B100="Honda")*(C2:C100="Accord")*A2:A100)

or array formula -

{=INDEX(A2:A100,MATCH(1,(B2:B100="Honda")*(C2:C100="Accord"),0))}

Array formula after editing is confirmed by pressing ctrl + shift + enter


问:
Class X is not abstract and does not implement fun writeToParcel() defined in android.os.Parcelable
In my Android app, I want to add a Bundle including a Place object described below to my Intent. Since serializable was slow and not recommended, I preferred Parcelable.

Althoug I use Kotlin 1.3.31, I have problems parcelizing some data classes. Example:

```<code>import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class Place(val street: String, val postal: String, val city: String) : Parcelable
</code>```

and Android Studio complains:

Class 'Place' is not abstract and does not implement abstract member
  public abstract fun writeToParcel(p0: Parcel!, p1: Int): Unit defined
  in android.os.Parcelable

According to some tutorials

That’s it! You don’t need to write any parcel methods anymore!

https://android.jlelse.eu/yet-another-awesome-kotlin-feature-parcelize-5439718ba220

and I do not want to use

```<code>androidExtensions {
    experimental = true
}
</code>```

in production stuff.

What alternatives would I have here?

答:
In my scenario, I have already used the Kotlin plugin version higher than 1.3.40.

But I still got the Android Studio Error, compile success, but IDE complaint about the @Parcelize annotation.

Maybe you got this as well.

Here is the solution.

Check your Kotlin plugin version which you are configured in Gradle is the same version bundled in Android Studio.

I got the error because my Gradle koltin plugin version is 1.3.61 and the Android Studio bundled version is 1.3.50

How to upgrade the kotlin plugin version？

Tools -> Kotlin -> Configure kotlin plugin update

check the latest version and install it, keep the two versions are the same.

Body:
In my Android app, I want to add a Bundle including a Place object described below to my Intent. Since serializable was slow and not recommended, I preferred Parcelable.

Althoug I use Kotlin 1.3.31, I have problems parcelizing some data classes. Example:

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize
data class Place(val street: String, val postal: String, val city: String) : Parcelable

and Android Studio complains:

Class 'Place' is not abstract and does not implement abstract member
  public abstract fun writeToParcel(p0: Parcel!, p1: Int): Unit defined
  in android.os.Parcelable

According to some tutorials

That’s it! You don’t need to write any parcel methods anymore!

https://android.jlelse.eu/yet-another-awesome-kotlin-feature-parcelize-5439718ba220

and I do not want to use

androidExtensions {
    experimental = true
}

in production stuff.

What alternatives would I have here?


问:
Deploying Google Cloud Endpoints configuration fails Google API Linter recommendations
Update: Cloud Endpoints Portal is being deprecated and will no longer be available after 21 March 2023.

After following Deploying the Endpoints configuration I have successfully deployed my compiled .proto file and gRPC API configuration file.

Great. I decided to be be a good citizen and use Google's API Linter on my .proto.

This resulted in a number of recommendations to include various annotations. The annotations required new proto imports;

Before

syntax = "proto3";
package api.v1;

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1;
}

...blah,blah
```
<p><strong>After</strong></p>
<pre class="lang-proto prettyprint-override"><code>syntax = "proto3";
package api.v1;

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1 [
    (google.api.field_behavior) = REQUIRED,
    (google.api.resource_reference).type = "api.v1.HelloWorld/Foo"
  ];
}
...blah,blah
</code>```

The annotations require four new proto files to be imported:

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";
```
<p>All are part of Google's Common API protos, therefore I cloned the repo into <code>/Users/Jack/api-common-protos/</code> with:</p>
```git clone https://github.com/googleapis/api-common-protos.git
```
<p>...and include it when compiling my <code>.proto</code> file:</p>
```python3 -m grpc_tools.protoc --proto_path=api
                             --proto_path=/Users/Jack/api-common-protos/google
                             api/v1/foo.proto
```
<p>No errors. Great. Finally I deploy the API:</p>
```gcloud endpoints services deploy api_descriptor.pb api-config.yaml
```
<p>This completes. However, the Developer Portal now shows:</p>
```We encountered the following errors while processing this API specification:

API parse error: Error: ENOENT: no such file or directory, open '/tmp/google/api/client.proto'

Please correct these errors and try again.
```

Scrot:

If I remove the annotation (and required imports), the Endpoints Developer Portal for my API works fine.

答: This is a bug in the developer portal. I have reported it to the team responsible. See Google's API Linter suggestions with Google Cloud Endpoints? which I posted to google-cloud-endpoints@googlegroups.com.

Body:
Update: Cloud Endpoints Portal is being deprecated and will no longer be available after 21 March 2023.

After following Deploying the Endpoints configuration I have successfully deployed my compiled .proto file and gRPC API configuration file.

Great. I decided to be be a good citizen and use Google's API Linter on my .proto.

This resulted in a number of recommendations to include various annotations. The annotations required new proto imports;

Before

syntax = "proto3";
package api.v1;

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1;
}

...blah,blah

After

syntax = "proto3";
package api.v1;

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

// Request message for Get method.
message GetFooRequest {
  // The field will contain name of the resource requested.
  string name = 1 [
    (google.api.field_behavior) = REQUIRED,
    (google.api.resource_reference).type = "api.v1.HelloWorld/Foo"
  ];
}
...blah,blah

The annotations require four new proto files to be imported:

import "google/api/annotations.proto";
import "google/api/client.proto";
import "google/api/field_behavior.proto";
import "google/api/resource.proto";

All are part of Google's Common API protos, therefore I cloned the repo into /Users/Jack/api-common-protos/ with:

git clone https://github.com/googleapis/api-common-protos.git

...and include it when compiling my .proto file:

python3 -m grpc_tools.protoc --proto_path=api
                             --proto_path=/Users/Jack/api-common-protos/google
                             api/v1/foo.proto

No errors. Great. Finally I deploy the API:

gcloud endpoints services deploy api_descriptor.pb api-config.yaml

This completes. However, the Developer Portal now shows:

We encountered the following errors while processing this API specification:

API parse error: Error: ENOENT: no such file or directory, open '/tmp/google/api/client.proto'

Please correct these errors and try again.

Scrot:

If I remove the annotation (and required imports), the Endpoints Developer Portal for my API works fine.


答:
You could do:

```<code>public Optional<Product> find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return Optional.of(product)
        }
   }
    return Optional.empty();
}
</code>```

or, even better, replace the ForEach loop with a Stream.

then you can use with ifPresent

```<code>  find("Stackoverflow").ifPresent(consumer)
</code>```

Title: How to bring object out of a for loop

Body:
You could do:

public Optional<Product> find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return Optional.of(product)
        }
   }
    return Optional.empty();
}

or, even better, replace the ForEach loop with a Stream.

then you can use with ifPresent

  find("Stackoverflow").ifPresent(consumer)


问:
How to enable highlighting on a line KMZ in Google Earth?
I am trying to figure out how to highlight a line segment when I hover over it in Google Earth.

This is what it currently looks like when I hover over it. Notice that the whole line stays blue:
Imgur

This is what I want it to look like when I hover over it. The segment should change color:
Imgur

Is there a way to do this with code? Do I need to convert it to a different file type?

答:
To change a line in Google Earth when you mouse over or hover on it then you need the KML to define a StyleMap that with a style for "normal" mode and another for "highlight" mode.

In the example below, the line shows a thin blue line by default showing the normal style, but changes to a thicker purple line when you hover the mouse over the line which then switches to the highlight style.

Example:

```<code><?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
       <Style id="sn">
          <LineStyle>
            <color>7fff0000</color>
            <width>2</width>
          </LineStyle>
          <PolyStyle>
            <color>7fff0000</color>
          </PolyStyle>
        </Style>
        <Style id="sh">
          <LineStyle>
            <color>7fff00ff</color>
            <width>8</width>
          </LineStyle>
          <PolyStyle>
            <color>7f00ff00</color>
          </PolyStyle>
        </Style>
        <StyleMap id="msn">
            <Pair>
                <key>normal</key>
                <styleUrl>#sn</styleUrl>
            </Pair>
            <Pair>
                <key>highlight</key>
                <styleUrl>#sh</styleUrl>
            </Pair>
        </StyleMap>

    <Placemark>
      <name>Style Map example</name>
      <styleUrl>#msn</styleUrl>
      <LineString>
        <tessellate>1</tessellate>
        <altitudeMode>absolute</altitudeMode>
        <coordinates>
          -112.265654928602,36.09447672602546,2357
          -112.2660384528238,36.09342608838671,2357
          -112.2668139013453,36.09251058776881,2357
          -112.2677826834445,36.09189827357996,2357
          -112.2688557510952,36.0913137941187,2357
          -112.2694810717219,36.0903677207521,2357
          -112.2695268555611,36.08932171487285,2357
          -112.2690144567276,36.08850916060472,2357
          -112.2681528815339,36.08753813597956,2357
          -112.2670588176031,36.08682685262568,2357
          -112.2657374587321,36.08646312301303,2357
        </coordinates>
      </LineString>
    </Placemark>
  </Document>
</kml>
</code>```

Body:
To change a line in Google Earth when you mouse over or hover on it then you need the KML to define a StyleMap that with a style for "normal" mode and another for "highlight" mode.

In the example below, the line shows a thin blue line by default showing the normal style, but changes to a thicker purple line when you hover the mouse over the line which then switches to the highlight style.

Example:

<?xml version="1.0" encoding="utf-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
  <Document>
       <Style id="sn">
          <LineStyle>
            <color>7fff0000</color>
            <width>2</width>
          </LineStyle>
          <PolyStyle>
            <color>7fff0000</color>
          </PolyStyle>
        </Style>
        <Style id="sh">
          <LineStyle>
            <color>7fff00ff</color>
            <width>8</width>
          </LineStyle>
          <PolyStyle>
            <color>7f00ff00</color>
          </PolyStyle>
        </Style>
        <StyleMap id="msn">
            <Pair>
                <key>normal</key>
                <styleUrl>#sn</styleUrl>
            </Pair>
            <Pair>
                <key>highlight</key>
                <styleUrl>#sh</styleUrl>
            </Pair>
        </StyleMap>

    <Placemark>
      <name>Style Map example</name>
      <styleUrl>#msn</styleUrl>
      <LineString>
        <tessellate>1</tessellate>
        <altitudeMode>absolute</altitudeMode>
        <coordinates>
          -112.265654928602,36.09447672602546,2357
          -112.2660384528238,36.09342608838671,2357
          -112.2668139013453,36.09251058776881,2357
          -112.2677826834445,36.09189827357996,2357
          -112.2688557510952,36.0913137941187,2357
          -112.2694810717219,36.0903677207521,2357
          -112.2695268555611,36.08932171487285,2357
          -112.2690144567276,36.08850916060472,2357
          -112.2681528815339,36.08753813597956,2357
          -112.2670588176031,36.08682685262568,2357
          -112.2657374587321,36.08646312301303,2357
        </coordinates>
      </LineString>
    </Placemark>
  </Document>
</kml>


问:
T-SQL: Deleting all duplicate rows but keeping one
I have a table with a very large amount of rows. Duplicates are not allowed but due to a problem with how the rows were created I know there are some duplicates in this table.
I need to eliminate the extra rows from the perspective of the key columns. Some other columns may have slightly different data but I do not care about that. I still need to keep one of these rows however. SELECT DISTINCT won't work because it operates on all columns and I need to suppress duplicates based on the key columns.

How can I delete the extra rows but still keep one efficiently?

答:
Example query:

```<code>DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)
</code>```

Here fields are column on which you want to group the duplicate rows.

Body:
Example query:

DELETE FROM Table
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM Table
GROUP BY Field1, Field2, Field3, ...
)

Here fields are column on which you want to group the duplicate rows.


问:
collections.Counter, is there any way to avoid adding string values?
For example, I have two dictionaries. </p>

<pre class="lang-py prettyprint-override"><code>>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
</code>```

<p>I am using collections.Counter for counting purposes.</p>

```<code>>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}
</code>```

<p>Is there any way to add only integer type values? i.e when added it adds up integer type values only.</p>

```<code>>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}
</code>```

答:
You can define your own function to add two Counterobjects like the ones you have in your question. This is necessary because the default method for adding Counter objects can't handle non-numeric values in them like you're putting in yours.

```<code>from collections import Counter

def add_counters(a, b):
    """ Add numerical counts from two Counters. """
    if not isinstance(a, Counter) or not isinstance(a, Counter):
        return NotImplemented
    result = Counter()
    for elem, count in a.items():
        newcount = count + b[elem]
        try:
            if newcount > 0:
                result[elem] = newcount
        except TypeError:
            result[elem] = count  # Just copy value.

    for elem, count in b.items():
        if elem not in a and count > 0:
            result[elem] = count

    return result

dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
dict_c = add_counters(Counter(dict_a), Counter(dict_b))
print(dict_c)  # -> Counter({'total': 50, 'remaining': 39, 'group': 'group_a'})
</code>```

Note that the above may not be totally correct because any non-numeric items in the first Counter argument a that are just copied to the result may get overwritten by the second for loop so their final value be whatever's in the second Counter named b. It's that way because you haven't defined precisely what you want to happen in a case like that.

Body:
For example, I have two dictionaries.

>>> dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
>>> dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}

I am using collections.Counter for counting purposes.

>>> dict_c = Counter()
>>> dict_c.update(Counter(dict_a))
>>> dict_c.update(Counter(dict_b))
>>> print(dict_c)
{'toal': 50, 'remaining': 39, 'group': 'group_agroup_a'}

Is there any way to add only integer type values? i.e when added it adds up integer type values only.

>>> print(dict_c)
>>> {'toal': 50, 'remaining': 39, 'group': 'group_a'}

Body:
You can define your own function to add two Counterobjects like the ones you have in your question. This is necessary because the default method for adding Counter objects can't handle non-numeric values in them like you're putting in yours.

from collections import Counter

def add_counters(a, b):
    """ Add numerical counts from two Counters. """
    if not isinstance(a, Counter) or not isinstance(a, Counter):
        return NotImplemented
    result = Counter()
    for elem, count in a.items():
        newcount = count + b[elem]
        try:
            if newcount > 0:
                result[elem] = newcount
        except TypeError:
            result[elem] = count  # Just copy value.

    for elem, count in b.items():
        if elem not in a and count > 0:
            result[elem] = count

    return result

dict_a = {'total': 20, 'remaining': 10, 'group': 'group_a'}
dict_b = {'total': 30, 'remaining': 29, 'group': 'group_a'}
dict_c = add_counters(Counter(dict_a), Counter(dict_b))
print(dict_c)  # -> Counter({'total': 50, 'remaining': 39, 'group': 'group_a'})

Note that the above may not be totally correct because any non-numeric items in the first Counter argument a that are just copied to the result may get overwritten by the second for loop so their final value be whatever's in the second Counter named b. It's that way because you haven't defined precisely what you want to happen in a case like that.


问:
Generic interface with wildcard. '? extends Class' is not 'Class'
I'm learning Java and trying to implement a command bus but I'm really stuck on generics and wildcards.

Here's the CommandHandler interface:

```<code>public interface CommandHandler<C extends Command> {

    boolean supports(Command command);

    void handle(C command);
}
</code>```

CommandBus interface:

```<code>public interface CommandBus {

    void register(CommandHandler<? extends Command> handler);

    void handle(Command command);
}
</code>```

And the implementation of CommandBus:

```<code>public class SimpleCommandBus implements CommandBus {

    private List<CommandHandler<? extends Command>> handlers = new ArrayList<>();

    @Override
    public void register(CommandHandler<? extends Command> handler) {
        handlers.add(handler);
    }

    @Override
    public void handle(Command command) {
        for (CommandHandler<? extends Command> handler : handlers) {
            if (handler.supports(command)) {
                handler.handle(command); // <- problem here

                return;
            }
        }
    }
}
</code>```

The problem lies on this line: handler.handle(command);.

? extends Command is not Command.
I've tried many things. The only solution that worked is casting:

```<code>public void handle(Command command) {
    for (CommandHandler<? extends Command> handler : handlers) {
        CommandHandler<Command> castedHandler = (CommandHandler<Command>) handler;

        if (castedHandler.supports(command)) {
            castedHandler.handle(command);

            return;
        }
    }
}
</code>```

But I think there must be better way to do it.

答:
Think of the type

```<code>? extends Command
</code>```

as "some specific but unknown subtype of Command".

So, each CommandHandler in the list handles some specific but unknown subtype of Command.
You're passing an argument of type Command, but there is no way the compiler will agree that a particular CommandHandler will handle this type, since the compiler doesn't know which type it handles at all.

Since your supports method takes in any Command, it must probably do a type check.  What you could do is have it return Optional<C> instead of boolean.  An empty Optional if the type does not matches, a non-empty one created using a cast after an instanceof check.  Then use it like this:

```<code>handler.supports(command)
       .ifPresent(supportedCommand -> handler.handle(supportedCommand));
</code>```

But you could then ask why even use two methods.  You could just call handle and make it return true or false indicating the command was supported or not.  It would make type parameter C obsolete.

You see, the fact that you have a method supports which takes Command instead of C means that you expect clients to not know whether the type matches.  Having a handle method that requires a matching type at compile time doesn't make much sense then.

Body:
I'm learning Java and trying to implement a command bus but I'm really stuck on generics and wildcards.

Here's the CommandHandler interface:

public interface CommandHandler<C extends Command> {

    boolean supports(Command command);

    void handle(C command);
}

CommandBus interface:

public interface CommandBus {

    void register(CommandHandler<? extends Command> handler);

    void handle(Command command);
}

And the implementation of CommandBus:

public class SimpleCommandBus implements CommandBus {

    private List<CommandHandler<? extends Command>> handlers = new ArrayList<>();

    @Override
    public void register(CommandHandler<? extends Command> handler) {
        handlers.add(handler);
    }

    @Override
    public void handle(Command command) {
        for (CommandHandler<? extends Command> handler : handlers) {
            if (handler.supports(command)) {
                handler.handle(command); // <- problem here

                return;
            }
        }
    }
}

The problem lies on this line: handler.handle(command);.

? extends Command is not Command.
I've tried many things. The only solution that worked is casting:

public void handle(Command command) {
    for (CommandHandler<? extends Command> handler : handlers) {
        CommandHandler<Command> castedHandler = (CommandHandler<Command>) handler;

        if (castedHandler.supports(command)) {
            castedHandler.handle(command);

            return;
        }
    }
}

But I think there must be better way to do it.

Body:
Think of the type

? extends Command

as "some specific but unknown subtype of Command".

So, each CommandHandler in the list handles some specific but unknown subtype of Command.
You're passing an argument of type Command, but there is no way the compiler will agree that a particular CommandHandler will handle this type, since the compiler doesn't know which type it handles at all.

Since your supports method takes in any Command, it must probably do a type check.  What you could do is have it return Optional<C> instead of boolean.  An empty Optional if the type does not matches, a non-empty one created using a cast after an instanceof check.  Then use it like this:

handler.supports(command)
       .ifPresent(supportedCommand -> handler.handle(supportedCommand));

But you could then ask why even use two methods.  You could just call handle and make it return true or false indicating the command was supported or not.  It would make type parameter C obsolete.

You see, the fact that you have a method supports which takes Command instead of C means that you expect clients to not know whether the type matches.  Having a handle method that requires a matching type at compile time doesn't make much sense then.


问:
Converting number to a padded string
I am trying to convert numeric types to fixed length string representations with leading '0's (used in a GUI that can only deal with strings - and lexicographic sorting of numbers is really awkward).

Instead of creating the string on the spot where it is required, I figure it should be possible to make a nice template for others to use that also works with different arithmetic types.

```<code>template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>
std::string arithmeticToMaxLengthString(const T& value)
{
  std::string number, result;
  number = std::to_string( value );
  result = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, number );
  return result;
}

std::string lpad( char filler, std::string::size_type length, const std::string& input)
{
  std::string result;
  if( input.length() < length )
  {
     result.append( lenght - input.lenght(), filler ).append( input );
     return result;
  }
  return input;
}
</code>```

So far so good.
It compiles and I can use it.
BUT:

When I tried using it, I got a surprise.
Calling this function with an int32_t which is

```<code>typedef int int32_t;
</code>```

that has a value of 100 the result is the string "100", length 3.

I am pretty certain that no other template with such a bad name exists in the codebase (I have search through all of it, and all linked libraries), but I can not seem to understand what is wrong with the code I have produced.
To verify the code to be correct I have just copy-pasted it to the place it is called, which now basically looks like this:

```<code>myDataClass{
  int32_t     quantity;
  std::string numberAsString;
}

void setNumberString( myDataClass data )
{
   std::string result    = arithmeticToMaxLengthString( data.quantity );
   std::string reference = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, std::to_string(data.quantity) );
   std::cout << "quantity<" << data.quantity << "> numericLimits<" << std::numeric_limits<decltype(value)>::digits10 + 1 << ">" << std::endl;
   std::cout << "result  template: length<" << result.lenght()    << "> content<" << result    << ">" << std::endl;
   std::cout << "result reference: length<" << reference.lenght() << "> content<" << reference << ">" << std::endl;
}
</code>```

Now to my understanding the template "arithmeticToMaxLengthString" is called with int32_t as the type of the argument, which is a normal int, where "numeric_limits::digits10 + 1" gives me 10.
But when this funtion is now called with a quantity of say 100 the results differ.

```<code>quantity<100> numericLimits<10>
result  template: length<3> content<100>
result reference: length<10> content<0000000100>
</code>```

Am I missing something about templates, enable_if or numeric_limits?
In what way does the template differ (aside from the obvious enable_if) ?

答:
Your problem happens because you are passing a reference to arithmeticToMaxLengthString function. For reasons listed in another answer here, std::numeric_limits does not work with references.

Therefore, I am suggesting you to use template type T for getting the numerical limit instead of using decltype(value):

result = lpad('0', std::numeric_limits<T>::digits10 + 1, number);
```

Not only does it solve the problem, it looks much more elegant too.

Title: Converting number to a padded string

Body:
I am trying to convert numeric types to fixed length string representations with leading '0's (used in a GUI that can only deal with strings - and lexicographic sorting of numbers is really awkward).

Instead of creating the string on the spot where it is required, I figure it should be possible to make a nice template for others to use that also works with different arithmetic types.

template <typename T, typename std::enable_if<std::is_arithmetic<T>::value, T>::type* = nullptr>
std::string arithmeticToMaxLengthString(const T& value)
{
  std::string number, result;
  number = std::to_string( value );
  result = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, number );
  return result;
}

std::string lpad( char filler, std::string::size_type length, const std::string& input)
{
  std::string result;
  if( input.length() < length )
  {
     result.append( lenght - input.lenght(), filler ).append( input );
     return result;
  }
  return input;
}

So far so good.
It compiles and I can use it.
BUT:

When I tried using it, I got a surprise.
Calling this function with an int32_t which is

typedef int int32_t;

that has a value of 100 the result is the string "100", length 3.

I am pretty certain that no other template with such a bad name exists in the codebase (I have search through all of it, and all linked libraries), but I can not seem to understand what is wrong with the code I have produced.
To verify the code to be correct I have just copy-pasted it to the place it is called, which now basically looks like this:

myDataClass{
  int32_t     quantity;
  std::string numberAsString;
}

void setNumberString( myDataClass data )
{
   std::string result    = arithmeticToMaxLengthString( data.quantity );
   std::string reference = lpad( '0', std::numeric_limits<decltype(value)>::digits10 + 1, std::to_string(data.quantity) );
   std::cout << "quantity<" << data.quantity << "> numericLimits<" << std::numeric_limits<decltype(value)>::digits10 + 1 << ">" << std::endl;
   std::cout << "result  template: length<" << result.lenght()    << "> content<" << result    << ">" << std::endl;
   std::cout << "result reference: length<" << reference.lenght() << "> content<" << reference << ">" << std::endl;
}

Now to my understanding the template "arithmeticToMaxLengthString" is called with int32_t as the type of the argument, which is a normal int, where "numeric_limits::digits10 + 1" gives me 10.
But when this funtion is now called with a quantity of say 100 the results differ.

quantity<100> numericLimits<10>
result  template: length<3> content<100>
result reference: length<10> content<0000000100>

Am I missing something about templates, enable_if or numeric_limits?
In what way does the template differ (aside from the obvious enable_if) ?

Body:
Your problem happens because you are passing a reference to arithmeticToMaxLengthString function. For reasons listed in another answer here, std::numeric_limits does not work with references.

Therefore, I am suggesting you to use template type T for getting the numerical limit instead of using decltype(value):

result = lpad('0', std::numeric_limits<T>::digits10 + 1, number);

Not only does it solve the problem, it looks much more elegant too.


问:
Create persistend access to the viewer
I'm not really familiar with Autodesk's instruments, so maybe anyone could help me with Auth:

I have 2-legged auth with forge, and i need to refresh token automatically or simply make my viewer persistent.

Also any help/links/references on points of interest or  how to add floor switching feature to the project?

答:
Typically, when setting up the viewer, you provide a function the viewer will call whenever it needs a fresh 2-legged token. This function should make a request to your server-side logic to generate the new token. The Learn Forge - View Your Models tutorial guides you through this process, using different languages and runtimes. For example, here's how you could implement the token updating in Node.js:

https://github.com/Autodesk-Forge/learn.forge.viewmodels/blob/nodejs/routes/oauth.js#L26-L36

https://github.com/Autodesk-Forge/learn.forge.viewmodels/blob/nodejs/public/js/ForgeViewer.js#L46-L52

Btw. a "refresh token" is only available in 3-legged auth workflows.

For features like floor switching, take a look at these:

https://forge.autodesk.com/blog/view-each-floor-using-vertical-explode

https://twitter.com/ipetrbroz/status/1227901732023201795

Title: Create persistend access to the viewer


问:
Picker SelectedItem and two different DB Tables
I've been struggling with this for a bit, and can't seem to find a solution.
I have a Picker that displays a list of college terms. Binding it isn't the issue.
I also have a table of college courses. Each course needs to be attached to a specified term.
I have set the SelectedItem to a Property of the Terms table through the SelectedIndexChanged event.
On a separate page, I want to display the SelectedItem from the previous page and the list of college course attached to that term. Right now, the new page displays all the terms (with the name changed to the SelectedItem, and all the courses, regardless of which term they are attached to (through TermId).

I figured this would need to be done with a SQLite query using an inner join, but I can't seem to set the ListView ItemsSouce to that results of that query (even using ToList();), and am not even sure if thats something I should be doing.

I also thought about creating a new table, and inserting the values of the query into that table and binding it that way.

Any advice on the best way to accomplish this?

Terms table:

```<code> public class Terms
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string TermName { get; set; }
        public string TermStatus { get; set; }
        public DateTime TProjStart { get; set; }
        public DateTime TProjEnd { get; set; }
        public DateTime TActStart { get; set; }
        public DateTime TActEnd { get; set; }
        public string Pick { get; set; }
    }
</code>```

Courses Table:

```<code>public class Courses
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        public string CourseName { get; set; }
        public string CourseStatus { get; set; }
        public DateTime CourseStart { get; set; }
        public DateTime CourseEnd { get; set; }
        public string InstructName { get; set; }
        public string InstructEmail { get; set; }
        public string InstructPhone { get; set; }
        public string Notes { get; set; }
        public int TermId { get; set; }

    }
</code>```

The TermId is supposed to reference Terms.Id as a sort of foreignkey, but I can't seem to actually make it a foreignkey, so I was thinking I may need to manually set it.
Picker SelectedIndexChanged event:

```<code>public void termPicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
            {
                var pick = (Terms)termPicker.SelectedItem;

                if (termPicker.SelectedItem != null)
                {
                    conn.Execute($"UPDATE Terms SET Pick ='{pick.TermName}'");

                }
                else
                {
                    var refresh = new Page1();
                    Navigation.InsertPageBefore(refresh, this);
                    Navigation.PopAsync();

                }
</code>```

答:
Now just need to figure out a way to display only the courses attached
  to the selected term

```<code>var courses = db.Table<Courses>().Where(c => c.TermId == selectedTerm).ToList();
</code>```

Body:
I've been struggling with this for a bit, and can't seem to find a solution.
I have a Picker that displays a list of college terms. Binding it isn't the issue.
I also have a table of college courses. Each course needs to be attached to a specified term.
I have set the SelectedItem to a Property of the Terms table through the SelectedIndexChanged event.
On a separate page, I want to display the SelectedItem from the previous page and the list of college course attached to that term. Right now, the new page displays all the terms (with the name changed to the SelectedItem, and all the courses, regardless of which term they are attached to (through TermId).

I figured this would need to be done with a SQLite query using an inner join, but I can't seem to set the ListView ItemsSouce to that results of that query (even using ToList();), and am not even sure if thats something I should be doing.

I also thought about creating a new table, and inserting the values of the query into that table and binding it that way.

Any advice on the best way to accomplish this?

Terms table:

 public class Terms
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        public string TermName { get; set; }
        public string TermStatus { get; set; }
        public DateTime TProjStart { get; set; }
        public DateTime TProjEnd { get; set; }
        public DateTime TActStart { get; set; }
        public DateTime TActEnd { get; set; }
        public string Pick { get; set; }
    }

Courses Table:

public class Courses
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }

        public string CourseName { get; set; }
        public string CourseStatus { get; set; }
        public DateTime CourseStart { get; set; }
        public DateTime CourseEnd { get; set; }
        public string InstructName { get; set; }
        public string InstructEmail { get; set; }
        public string InstructPhone { get; set; }
        public string Notes { get; set; }
        public int TermId { get; set; }

    }

The TermId is supposed to reference Terms.Id as a sort of foreignkey, but I can't seem to actually make it a foreignkey, so I was thinking I may need to manually set it.
Picker SelectedIndexChanged event:

public void termPicker_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (SQLiteConnection conn = new SQLiteConnection(App.DatabaseLocation))
            {
                var pick = (Terms)termPicker.SelectedItem;

                if (termPicker.SelectedItem != null)
                {
                    conn.Execute($"UPDATE Terms SET Pick ='{pick.TermName}'");

                }
                else
                {
                    var refresh = new Page1();
                    Navigation.InsertPageBefore(refresh, this);
                    Navigation.PopAsync();

                }

Body:
Now just need to figure out a way to display only the courses attached
  to the selected term

var courses = db.Table<Courses>().Where(c => c.TermId == selectedTerm).ToList();


问:
Maven error: "Cannot resolve com.github.ConnorLinfoot:ActionBarAPI:1.5.4"
I am creating a minecraft spigot plugin and I have to include an API from GitHub.

I used jitpack.io to get the code required to fetch the repository from GitHub and got an error: "Cannot resolve com.github.ConnorLinfoot:ActionBarAPI:1.5.4".

My pom.xml code:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ecohub</groupId>
    <artifactId>DeathSwap</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>spigotmc-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.github.ConnorLinfoot</groupId>
            <artifactId>ActionBarAPI</artifactId>
            <version>1.5.4</version>
        </dependency>
    </dependencies>
</project>
</code>```

What could be causing this issue?

答:
Seems like the dependency ActionBarAPI has no release and have no version published on the public repository that you placed on your pom.xml.
While using jitpack.io, in cases like this, you can place the commit version of the git project that you are looking for. In your case, checking the github page of ActionBarAPI, the project has no releases yet. If you decide to use even without any public release, with jitpack, you can refer the last commit hash as the version of your dependency. In other words, this should work:</p>

```<code><dependency>
    <groupId>com.github.ConnorLinfoot</groupId>
    <artifactId>ActionBarAPI</artifactId>
    <version>5b2d642d3df240cfd2545effcdcacec38405f9cf</version><!-- Replace with the last commit hash that you are looking for -->
</dependency>
</code>```

Body:
I am creating a minecraft spigot plugin and I have to include an API from GitHub.

I used jitpack.io to get the code required to fetch the repository from GitHub and got an error: "Cannot resolve com.github.ConnorLinfoot:ActionBarAPI:1.5.4".

My pom.xml code:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ecohub</groupId>
    <artifactId>DeathSwap</artifactId>
    <version>1.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>spigotmc-repo</id>
            <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
        </repository>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.spigotmc</groupId>
            <artifactId>spigot-api</artifactId>
            <version>1.8-R0.1-SNAPSHOT</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.github.ConnorLinfoot</groupId>
            <artifactId>ActionBarAPI</artifactId>
            <version>1.5.4</version>
        </dependency>
    </dependencies>
</project>

What could be causing this issue?

Body:
Seems like the dependency ActionBarAPI has no release and have no version published on the public repository that you placed on your pom.xml.
While using jitpack.io, in cases like this, you can place the commit version of the git project that you are looking for. In your case, checking the github page of ActionBarAPI, the project has no releases yet. If you decide to use even without any public release, with jitpack, you can refer the last commit hash as the version of your dependency. In other words, this should work:

<dependency>
    <groupId>com.github.ConnorLinfoot</groupId>
    <artifactId>ActionBarAPI</artifactId>
    <version>5b2d642d3df240cfd2545effcdcacec38405f9cf</version><!-- Replace with the last commit hash that you are looking for -->
</dependency>


问:
Calculate Categorical Data as a Percent of Each Category in a Pandas Data Frame Using GroupBy
I have a Pandas data frame with the column COLOR containing categorical data -

```<code>  ZIP    YEAR    COLOR
11111    1990        0
11111    1990        1
11111    2000        1
11111    2000        1
22222    1990        0
22222    1990        0
22222    2000        0
22222    2000        1
</code>```

How do I aggregate the data by the ZIP and YEAR columns (df.groupby(['ZIP', 'YEAR'])) and calculate the categorical data as a percent of each category such that the result resembles the data frame below?

```<code>  ZIP    YEAR        COLOR
                  0      1

11111    1990    50     50
         2000     0    100
22222    1990   100      0
         2000    50     50
</code>```

import pandas as pd

df = pd.DataFrame([{11111, 1990, 0},
                   {11111, 1990, 1},
                   {11111, 2000, 1},
                   {11111, 2000, 1},
                   {22222, 1990, 0},
                   {22222, 1990, 0},
                   {22222, 2000, 0},
                   {22222, 2000, 1}]
                  , columns=["ZIP", "YEAR", "COLOR"]
                 )
```

答:
Try:

df.groupby(["ZIP", "YEAR"])["COLOR"].value_counts(normalize=True).mul(100).unstack("COLOR").fillna(0)
```

<p>Outputs:</p>

<pre class="lang-py prettyprint-override"><code>COLOR           0      1
ZIP   YEAR
11111 1990   50.0   50.0
      2000    0.0  100.0
22222 1990  100.0    0.0
      2000   50.0   50.0
</code>```

Body:
I have a Pandas data frame with the column COLOR containing categorical data -

  ZIP    YEAR    COLOR
11111    1990        0
11111    1990        1
11111    2000        1
11111    2000        1
22222    1990        0
22222    1990        0
22222    2000        0
22222    2000        1

How do I aggregate the data by the ZIP and YEAR columns (df.groupby(['ZIP', 'YEAR'])) and calculate the categorical data as a percent of each category such that the result resembles the data frame below?

  ZIP    YEAR        COLOR
                  0      1

11111    1990    50     50
         2000     0    100
22222    1990   100      0
         2000    50     50

import pandas as pd

df = pd.DataFrame([{11111, 1990, 0},
                   {11111, 1990, 1},
                   {11111, 2000, 1},
                   {11111, 2000, 1},
                   {22222, 1990, 0},
                   {22222, 1990, 0},
                   {22222, 2000, 0},
                   {22222, 2000, 1}]
                  , columns=["ZIP", "YEAR", "COLOR"]
                 )

Body:
Try:

df.groupby(["ZIP", "YEAR"])["COLOR"].value_counts(normalize=True).mul(100).unstack("COLOR").fillna(0)

Outputs:

COLOR           0      1
ZIP   YEAR
11111 1990   50.0   50.0
      2000    0.0  100.0
22222 1990  100.0    0.0
      2000   50.0   50.0


答:
Since Java 8 you can return an Optional instead of a Product:

```<code>public Optional<Product> find(String nameInput){
  for(Product product : this.Products){
    if(product.getName().equalsIgnoreCase(nameInput)){
        return Optional.of(product);
    }
  }
  return Optional.empty();
}
</code>```

Additionally, as several other posters also mentioned, I would use the stream api instead of a for each loop.

Title: How to bring object out of a for loop

Body:
I have the following method that should return a product object if its name attribute matches the input string.

public Product find(String nameInput){
 for(Product product : this.Products){
        if(product.getName().equalsIgnoreCase(nameInput)){
            return product;
        }
   }
}

Its giving me the following error:

I know that I could return null at the end of the method, however is there a more elegant way to do this?

Body:
Since Java 8 you can return an Optional instead of a Product:

public Optional<Product> find(String nameInput){
  for(Product product : this.Products){
    if(product.getName().equalsIgnoreCase(nameInput)){
        return Optional.of(product);
    }
  }
  return Optional.empty();
}

Additionally, as several other posters also mentioned, I would use the stream api instead of a for each loop.


问:
A reference to the object of the class with dynamically allocated memory and destructor
Let's assume I have three classes:

```<code>class A{
};

class B{
   int S;
   A* arr;
   B(int s):S(s){
      arr = new A[S];
   }
   ~B(){
   delete [] arr;
   }
};

class C{
   B& b;
   C(B& b): b(b){}
};
</code>```

Should I define explicitly a destructor in class C? What would it look like?

答:
Should I define explicitly a destructor in class C?

To answer that question, you must know what your class does. Is the purpose of the class to manage allocated memory? Then, yes you probably need a destructor. Is the purpose to refer to an object managed by something else? Then why would you need a destructor? If you don't know what a destructor should do, then you quite often do not need one.

You should never use owning references, so there should be little reason for C to have a destructor, or it has to be changed drastically.

You also should not use owning bare pointers, so class B should also be changed. Easiest solution is to replace it with std::vector.

Body:
Let's assume I have three classes:

class A{
};

class B{
   int S;
   A* arr;
   B(int s):S(s){
      arr = new A[S];
   }
   ~B(){
   delete [] arr;
   }
};

class C{
   B& b;
   C(B& b): b(b){}
};

Should I define explicitly a destructor in class C? What would it look like?


答:
No, you don't need a destructor for C, but you do need a copy-constructor (as well as a move-constructor, copy-assignment operator and move-assignment operator) for class B if you want to correctly implement copy-semantics. As it is now if you were to make a copy of an object of class B, you would have to objects pointing to the same array - when the objects are destructed you would get a double delete causing undefined behavior.

You don't need to use a raw pointer. You can simply use a std::vector will handle the allocation of the elements as well as its destruction. That also means that you won't need to implement any other kinds of constructors or a destructor for B since std::vector handles copies and moves correctly.

Title: A reference to the object of the class with dynamically allocated memory and destructor


问:
Java: How to @SuppressWarnings unreachable code?
Sometimes when you are debugging, you have unreachable code fragment. Is there anyway to suppress the warning?</p>

答:
Java has (primitive) support for debugging like this in that simple if on boolean constants will not generate such warnings (and, indeed when the evaluation is false the compiler will remove the entire conditioned block).  So you can do:

```<code>if(false) {
    // code you don't want to run
    }
</code>```

Likewise, if you are temporarily inserting an early termination for debugging, you might do it like so:

```<code>if(true) { return blah; }
</code>```

or

```<code>if(true) { throw new RuntimeException("Blow Up!"); }
</code>```

And note that the Java specification explicitly declares that constantly false conditional blocks are removed at compile time, and IIRC, constantly true ones have the condition removed.  This includes such as:

```<code>public class Debug
{
static public final boolean ON=false;
}

...

if(Debug.ON) {
    ...
    }
</code>```

Body:
Java has (primitive) support for debugging like this in that simple if on boolean constants will not generate such warnings (and, indeed when the evaluation is false the compiler will remove the entire conditioned block).  So you can do:

if(false) {
    // code you don't want to run
    }

Likewise, if you are temporarily inserting an early termination for debugging, you might do it like so:

if(true) { return blah; }

or

if(true) { throw new RuntimeException("Blow Up!"); }

And note that the Java specification explicitly declares that constantly false conditional blocks are removed at compile time, and IIRC, constantly true ones have the condition removed.  This includes such as:

public class Debug
{
static public final boolean ON=false;
}

...

if(Debug.ON) {
    ...
    }