问:
"Temporary value dropped while borrowed" when using string.replace()
Can someone explain which exact temporary value is dropped and what the recommended way to do this operation is?</p>
```<code>fn main() {
    let mut a = &mut String::from("Hello Ownership");
    a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}
</code>```

答:
If you want to keep the &mut references (which are generally not needed in your case, of course), you can do something like this:

```<code>fn main() {
    let a = &mut String::from("Hello Ownership");
    let a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}
</code>```

The type of a would by &mut String. In the second line we do what's known as variable shadowing (not that it's needed) and the type is still &mut String.

That doesn't quite answer your question. I don't know why exactly your version doesn't compile, but at least I thought this info might be useful. (see below)

Update

Thanks to Solomon's findings, I wanted to add that apparently in this case:

```<code>let a = &mut ...;
let b = &mut ...;
</code>```

or this one (variable shadowing, basically the same as the above):

```<code>let a = &mut ...;
let a = &mut ...;
</code>```

, the compiler will automatically extend the lifetime of each temporary until the end of the enclosing block. However, in the case of:

```<code>let mut a = &mut ...;
a = &mut ...;
</code>```

, it seems the compiler simply doesn't do such lifetime extension, so that's why the OP's code doesn't compile, even though the code seems to be doing pretty much the same thing.

Body:
Can someone explain which exact temporary value is dropped and what the recommended way to do this operation is?

fn main() {
    let mut a = &mut String::from("Hello Ownership");
    a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}

Body:
If you want to keep the &mut references (which are generally not needed in your case, of course), you can do something like this:

fn main() {
    let a = &mut String::from("Hello Ownership");
    let a = &mut a.replace("Ownership", "World");
    println!("a is {}", a);
}

The type of a would by &mut String. In the second line we do what's known as variable shadowing (not that it's needed) and the type is still &mut String.

That doesn't quite answer your question. I don't know why exactly your version doesn't compile, but at least I thought this info might be useful. (see below)

Update

Thanks to Solomon's findings, I wanted to add that apparently in this case:

let a = &mut ...;
let b = &mut ...;

or this one (variable shadowing, basically the same as the above):

let a = &mut ...;
let a = &mut ...;

, the compiler will automatically extend the lifetime of each temporary until the end of the enclosing block. However, in the case of:

let mut a = &mut ...;
a = &mut ...;

, it seems the compiler simply doesn't do such lifetime extension, so that's why the OP's code doesn't compile, even though the code seems to be doing pretty much the same thing.


来源: stackexchange

问:
Unexpected behaviour involving UNION ALL in CTE with MYSQL
I've tried to re-create a minimal reproducible example but without success so I'll have to paste my actual query, I'm sorry for the name of the columns and tables in a foreign language.

The queries below have the same WITH preamble.

On MySQL 8.0.22 the following query

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine;
```
<p>returns a result set of 17 rows.</p>
<p>The query</p>
<pre class="lang-sql prettyprint-override"><code>WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), NULL
FROM CTE2
GROUP BY cinema, giorno, ora_inizio;
</code>```

returns a result set of 80 rows.

Instead of returning a result set of 80+17 = 97 rows the following query returns a result set of 18 rows

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine
UNION ALL
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), NULL
FROM CTE2
GROUP BY cinema, giorno, ora_inizio;
```
<p>Switching the selects I get a result set of 97 elements</p>
<pre class="lang-sql prettyprint-override"><code>WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine) AS ora_fine, NULL AS dipendente
FROM CTE2
GROUP BY cinema, giorno, ora_inizio
UNION ALL
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine;
</code>```

Is this a bug or is it caused by a syntactic error?

答:
In the file specified by log_error(see: show variables like 'log_error';) is the following info:

```<code>Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
7ff6a0662957    mysqld.exe!??$endl@DU?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@@Z()
7ff69f1e48e2    mysqld.exe!?ha_index_init@handler@@QEAAHI_N@Z()
7ff69f6646e7    mysqld.exe!?Init@?$IndexScanIterator@$0A@@@UEAA_NXZ()
7ff69f6d16b4    mysqld.exe!?Init@AggregateIterator@@UEAA_NXZ()
7ff69f6d2ecb    mysqld.exe!?Read@AppendIterator@@UEAAHXZ()
7ff69f5522be    mysqld.exe!?ExecuteIteratorQuery@Query_expression@@QEAA_NPEAVTHD@@@Z()
7ff69f553896    mysqld.exe!?execute@Query_expression@@QEAA_NPEAVTHD@@@Z()
7ff69f45e15e    mysqld.exe!?execute_inner@Sql_cmd_dml@@MEAA_NPEAVTHD@@@Z()
7ff69f45dfdc    mysqld.exe!?execute@Sql_cmd_dml@@UEAA_NPEAVTHD@@@Z()
7ff69f3bc9ec    mysqld.exe!?mysql_execute_command@@YAHPEAVTHD@@_N@Z()
7ff69f3b7b91    mysqld.exe!?dispatch_sql_command@@YAXPEAVTHD@@PEAVParser_state@@@Z()
7ff69f3b68c5    mysqld.exe!?dispatch_command@@YA_NPEAVTHD@@PEBTCOM_DATA@@W4enum_server_command@@@Z()
7ff69f3b7ed0    mysqld.exe!?do_command@@YA_NPEAVTHD@@@Z()
7ff69f21bab8    mysqld.exe!?modify_thread_cache_size@Per_thread_connection_handler@@SAXK@Z()
7ff6a05e0e8f    mysqld.exe!??$endl@DU?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@@Z()
7ff6a01c2edc    mysqld.exe!?my_thread_self_setname@@YAXPEBD@Z()
7ffc27026c0c    ucrtbase.dll!_recalloc()
7ffc27ac54e0    KERNEL32.DLL!BaseThreadInitThunk()
7ffc299e485b    ntdll.dll!RtlUserThreadStart()

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (24ba3a15230): WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, T3.ora_inizio, T3.ora_fine, T4.dipe
Connection ID (thread ID): 8
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.
</code>```

If this does not help (the info on crashing.html), you can always file a bug at: https://bugs.mysql.com/

For now the workaround is to change the query to (swap the piece before and after the UNION ALL):

```<code>WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), 0
FROM CTE2
GROUP BY cinema, giorno, ora_inizio
UNION ALL
SELECT T3.cinema, T3.giorno, T3.ora_inizio, T3.ora_fine, T4.dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine
;
</code>```

Another workaround could be to create (temporary) tables from the CTE1 and CTE2 result sets.
see this: DBFIDDLE

ContentLicense: CC BY-SA 4.0

Body:
I've tried to re-create a minimal reproducible example but without success so I'll have to paste my actual query, I'm sorry for the name of the columns and tables in a foreign language.

The queries below have the same WITH preamble.

On MySQL 8.0.22 the following query

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine;

returns a result set of 17 rows.

The query

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), NULL
FROM CTE2
GROUP BY cinema, giorno, ora_inizio;

returns a result set of 80 rows.

Instead of returning a result set of 80+17 = 97 rows the following query returns a result set of 18 rows

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine
UNION ALL
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), NULL
FROM CTE2
GROUP BY cinema, giorno, ora_inizio;

Switching the selects I get a result set of 97 elements

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine) AS ora_fine, NULL AS dipendente
FROM CTE2
GROUP BY cinema, giorno, ora_inizio
UNION ALL
SELECT T3.cinema, T3.giorno, ora_inizio, ora_fine, dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine;

Is this a bug or is it caused by a syntactic error?

Body:
In the file specified by log_error(see: show variables like 'log_error';) is the following info:

Attempting backtrace. You can use the following information to find out
where mysqld died. If you see no messages after this, something went
terribly wrong...
7ff6a0662957    mysqld.exe!??$endl@DU?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@@Z()
7ff69f1e48e2    mysqld.exe!?ha_index_init@handler@@QEAAHI_N@Z()
7ff69f6646e7    mysqld.exe!?Init@?$IndexScanIterator@$0A@@@UEAA_NXZ()
7ff69f6d16b4    mysqld.exe!?Init@AggregateIterator@@UEAA_NXZ()
7ff69f6d2ecb    mysqld.exe!?Read@AppendIterator@@UEAAHXZ()
7ff69f5522be    mysqld.exe!?ExecuteIteratorQuery@Query_expression@@QEAA_NPEAVTHD@@@Z()
7ff69f553896    mysqld.exe!?execute@Query_expression@@QEAA_NPEAVTHD@@@Z()
7ff69f45e15e    mysqld.exe!?execute_inner@Sql_cmd_dml@@MEAA_NPEAVTHD@@@Z()
7ff69f45dfdc    mysqld.exe!?execute@Sql_cmd_dml@@UEAA_NPEAVTHD@@@Z()
7ff69f3bc9ec    mysqld.exe!?mysql_execute_command@@YAHPEAVTHD@@_N@Z()
7ff69f3b7b91    mysqld.exe!?dispatch_sql_command@@YAXPEAVTHD@@PEAVParser_state@@@Z()
7ff69f3b68c5    mysqld.exe!?dispatch_command@@YA_NPEAVTHD@@PEBTCOM_DATA@@W4enum_server_command@@@Z()
7ff69f3b7ed0    mysqld.exe!?do_command@@YA_NPEAVTHD@@@Z()
7ff69f21bab8    mysqld.exe!?modify_thread_cache_size@Per_thread_connection_handler@@SAXK@Z()
7ff6a05e0e8f    mysqld.exe!??$endl@DU?$char_traits@D@std@@@std@@YAAEAV?$basic_ostream@DU?$char_traits@D@std@@@0@AEAV10@@Z()
7ff6a01c2edc    mysqld.exe!?my_thread_self_setname@@YAXPEBD@Z()
7ffc27026c0c    ucrtbase.dll!_recalloc()
7ffc27ac54e0    KERNEL32.DLL!BaseThreadInitThunk()
7ffc299e485b    ntdll.dll!RtlUserThreadStart()

Trying to get some variables.
Some pointers may be invalid and cause the dump to abort.
Query (24ba3a15230): WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT T3.cinema, T3.giorno, T3.ora_inizio, T3.ora_fine, T4.dipe
Connection ID (thread ID): 8
Status: NOT_KILLED

The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains
information that should help you find out what is causing the crash.

If this does not help (the info on crashing.html), you can always file a bug at: https://bugs.mysql.com/

For now the workaround is to change the query to (swap the piece before and after the UNION ALL):

WITH
    CTE1 AS (SELECT cinema, giorno, inizio, fine, dipendente
            FROM (SELECT cinema, giorno, dipendente, inizio, SEC_TO_TIME(TIME_TO_SEC(inizio) + TIME_TO_SEC(durata)) AS fine
                FROM Turni JOIN Dipendenti ON matricola = dipendente AND ruolo = 'Maschera'
                UNION ALL SELECT id, nome, NULL, apertura, apertura FROM Cinema, Giorni
                UNION ALL SELECT id, nome, NULL, chiusura, chiusura FROM Cinema, Giorni) AS T0),
    CTE2 AS (SELECT T1.cinema, T1.giorno, T1.inizio AS ora_inizio, MIN(T2.inizio) AS ora_fine
            FROM (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T1
                JOIN (SELECT cinema, giorno, inizio FROM CTE1 UNION ALL (SELECT cinema, giorno, fine FROM CTE1)) AS T2
                    ON T1.cinema = T2.cinema AND T1.giorno = T2.giorno
            WHERE T1.inizio < T2.inizio
            GROUP BY T1.cinema, T1.giorno, T1.inizio)
SELECT cinema, giorno, ora_inizio, MIN(ora_fine), 0
FROM CTE2
GROUP BY cinema, giorno, ora_inizio
UNION ALL
SELECT T3.cinema, T3.giorno, T3.ora_inizio, T3.ora_fine, T4.dipendente
FROM CTE2 AS T3 JOIN CTE1 AS T4 ON T3.cinema = T4.cinema AND T3.giorno = T4.giorno
WHERE inizio <= ora_inizio AND ora_fine <= fine
;

Another workaround could be to create (temporary) tables from the CTE1 and CTE2 result sets.
see this: DBFIDDLE


问:
Is there a maximum limit to a python array? How to handle large data?
I'm using a simple python array to store words fetched from a file.

```<code>words=[]
words.append(new_word)
</code>```

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.

答:
The issue occurred due to invalid character available in the file where the words are extracted. For more information about this issue read UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

Thank you everyone who helped in finding the root cause.

Body:
I'm using a simple python array to store words fetched from a file.

words=[]
words.append(new_word)

This code snippet works perfectly for files with small word counts. However when running the script for larger files, it hangs after some time.(when the array length is around 111166 and the letter count inside the array is high)

Is there a maximum limit for a python array?
Is there a workaround to for this?

Thanks in advance.


问:
Check to see if elements in a list have an SRC from a variable and then run code - jQuery / Javascript
So I wish to check a variable called SRC against the source of images in a list from my HTML and if it returns true then run a certain function.

It seems that it is not currently running properly, please see the link for a live example.

http://jsbin.com/exigop/4/edit

答:
I think you have error in setTimeout, try</p>

```<code>setTimeout(timeOut, 1000);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I think you have error in setTimeout, try

setTimeout(timeOut, 1000);


问:
Creating a data structure of integers and finding which component a given integer lies in
I have a set of 32 bit integers with which I will be making a data structure that will put these integers in different components ( like dsu ) the join operation has to be performed using bitwise and, if the bitwise and is not zero of two integers they lie in the same component, now given an integer how do I get ( assuming the data structure is already created for the prefix of this current integer ) the component in which this integer will lie? ex say [1,5,3,8] are given set of integers than (1,5,8) lie in one component because lsb for any pair will ensure non zero "bit and" and (8) will lie in it's own component, Or quite possibly entirely different algorithm that is much simpler if you can think of,

Edit :

It is possible however that two integers have bit and as zero but if third integer is introduced which has pairwise bit and non zero with both of them then all three will lie in same component ex [2,12, 6] 2 and 12 on operation give 0 but 2 and 6 do not and 12 and 6 do not so 6 will unify all three in one component.

Edit 2 : I am able to think of a naive algorithm that uses 32 length array for which one entry consists of linked list like structure ( like adjecentcy list ) that is if i'th bit is set then index i will contain all the integers with i'th set bit, but it could give me O(n) search, I'm thinking more towards dsu, but finding it difficult how to create it.

答:
The requirements imply that an incoming integer x should be joined with component C if and only if the bitwise AND of x with the (bitwise OR of all numbers in C) is nonzero.

A disjoint-set data structure would work well for this. The 'root' of each component could also maintain the bitwise OR of all of its members, which can be done with a separate hashmap, although this isn't strictly necessary.

You should also keep a hashmap from each bit-position to any member of the (unique, if it exists) component that has that bit-position set. When adding a new integer, scan over all of its set-bits: use this hashmap to find all the components to union, or whether to make a new component. This should give almost constant-time updates. There are also at most 1 + ceil(log_2(M)) different components at any time, where M is the largest integer you've seen, which would be at most 33.

If you want to avoid some of the complexity of the Disjoint-Set code, you could go with Paul Hankin's suggestion of a list of components. Depending on your programming language and whether you want to count duplicates, a component could be represented as a (bitmask, multiset) pair, where the bitmask is the bitwise OR of all members, and the multiset of members lets you print all members of a component and test for containment in O(1) time, although insertions could take longer (but still constant amortized time).

If you never need to print the members of a component or check whether a particular integer was ever actually added, it suffices to just store the bitmasks.


问:
Hide or show navbar in ReactJS?
I was wondering how to change the navbar behavior based on the webpage position. I've seen a lot of tutorials about how to hide/show a navbar on scroll, which vie managed to implement successfully, however that seems to just cover two states. I would like my navbar to have three: show when I scroll up, hide when I scroll down, and change opacity if I'm at the top of the website. I've tried using a variety of useEffects and event listeners but I'm quite new to react and js.

Here's a good example of the effect I'm looking for https://brittanychiang.com/. As you can see once you are at the top of the webpage the opacity changes as well as the drop shadow, it all seems to be 'stuck' at the top instead of the floating look when you scroll up/down. Using dev tools I've found that the navbar class does seem to have three different names depending on the location of the scrollbar.

Thanks in advance!

答:
You have to handle 'scroll' events using your component's lifecycle functions.

Please find this example for your header component. With some tweaks you may be able to use it.

Class component:

```<code>componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate // and use this on your header
    });
},
</code>```

Functional component:

```<code>const [headerPosition, setHeaderPosition] = useState(0)

const handleScroll = useCallback((event) => {
     let scrollTop = event.srcElement.body.scrollTop,
     itemTranslate = Math.min(0, scrollTop/3 - 60);

     setHeaderPosition({
        transform: itemTranslate // and use this on your header
     });
}, [setHeaderPosition])

useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
}, [handleScroll])
</code>```

Title: Hide or show navbar in ReactJS?

Body:
You have to handle 'scroll' events using your component's lifecycle functions.

Please find this example for your header component. With some tweaks you may be able to use it.

Class component:

componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate // and use this on your header
    });
},

Functional component:

const [headerPosition, setHeaderPosition] = useState(0)

const handleScroll = useCallback((event) => {
     let scrollTop = event.srcElement.body.scrollTop,
     itemTranslate = Math.min(0, scrollTop/3 - 60);

     setHeaderPosition({
        transform: itemTranslate // and use this on your header
     });
}, [setHeaderPosition])

useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
}, [handleScroll])


问:
Mounting Kubernetes config map as single file returns error: "caused: mount through procfd: not a directory: unknown"
This is my pod:

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main
```
<p>This is my config map:</p>
<pre class="lang-yaml prettyprint-override"><code>apiVersion: v1
kind: ConfigMap
metadata:
  name: config-main
data:
  config.tmpl: |
        # here goes my config content

</code>```

This produces the following error:

Error: failed to create containerd task: failed to create shim: OCI
runtime create failed: container_linux.go:380: starting container
process caused: process_linux.go:545: container init caused:
rootfs_linux.go:76: mounting
"/var/lib/kubelet/pods/dc66ebd1-90ef-4c25-bb69-4b3329f61a5a/volume-subpaths/config-main/podname/1"
to rootfs at "/etc/configs/config.tmpl" caused: mount through procfd:
not a directory: unknown

The container has pre-existing /etc/configs/config.tmpl file that I want to override

答:
I've managed to make it work:

mountPath must be a directory

using subPath didn't work for me, anyway official doc says "using a ConfigMap as a subPath volume mount will not receive ConfigMap updates", which isn't an option for me

so I guess you can't mount a single file, you always mount a directory but then you can optionally limit which files from the configmap's data you want there via items in a volume.

```<code>spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs
      name: config-main
      readOnly: true
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main
</code>```

Body:
This is my pod:

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs/config.tmpl
      name: config-main
      readOnly: true
      subPath: config.tmpl
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main

This is my config map:

apiVersion: v1
kind: ConfigMap
metadata:
  name: config-main
data:
  config.tmpl: |
        # here goes my config content

This produces the following error:

Error: failed to create containerd task: failed to create shim: OCI
runtime create failed: container_linux.go:380: starting container
process caused: process_linux.go:545: container init caused:
rootfs_linux.go:76: mounting
"/var/lib/kubelet/pods/dc66ebd1-90ef-4c25-bb69-4b3329f61a5a/volume-subpaths/config-main/podname/1"
to rootfs at "/etc/configs/config.tmpl" caused: mount through procfd:
not a directory: unknown

The container has pre-existing /etc/configs/config.tmpl file that I want to override

Body:
I've managed to make it work:

mountPath must be a directory

using subPath didn't work for me, anyway official doc says "using a ConfigMap as a subPath volume mount will not receive ConfigMap updates", which isn't an option for me

so I guess you can't mount a single file, you always mount a directory but then you can optionally limit which files from the configmap's data you want there via items in a volume.

spec:
  containers:
    volumeMounts:
    - mountPath: /etc/configs
      name: config-main
      readOnly: true
  volumes:
  - configMap:
      defaultMode: 420
      name: config-main
    name: config-main


问:
How can I add css class to the to the nested element using DOM?
I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.

And when the user clicks the button, the button should be hidden, image and text should become clear and visible.

I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...

let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");

images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blur {
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.hidden {
  display: none;
}</code>```

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

```

答:
```<code>for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}
</code>```

Here, in the conditions of the for loop, write "i < btns.length".

Body:
I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.

And when the user clicks the button, the button should be hidden, image and text should become clear and visible.

I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...

let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");

images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}

.blur {
  filter: blur(8px);
  -webkit-filter: blur(8px);
}
.hidden {
  display: none;
}

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

        <button class="btn">Open the Gift</button>

CONGRATULATIONS

Body:
for (let i = 0; i < btns; i++) {
  btns[i].addEventListener("click", function () {
    btns[i].classList.add("hidden");
  });
}

Here, in the conditions of the for loop, write "i < btns.length".


问:
Get difference of lists flutter dart
I have two lists [1,2,3,4,5,6,7] and [3,5,6,7,9,10]. I want to get the difference of the first list and the second list.

The expected output would be [1,2,4] since those are the only elements in only list 1 and not list 2.

I'm using Flutter and Dart. I looked this up on the internet, I know it seems like a simple question but I couldn't find anything.

Should be irrelevant but I'm using publishing for iOS

I'd prefer an answer without just a foreach loop, im looking to see if there is a library for it.

答:
Simple & Recommended Way to do this is</p>
```<code>var a = [1,2,3,4,5];
var b = [1,2];
a.removeWhere((element) => b.contains(element));
print(a); //[3, 4, 5]
</code>```

Title: Get difference of lists flutter dart

Body:
Simple & Recommended Way to do this is

var a = [1,2,3,4,5];
var b = [1,2];
a.removeWhere((element) => b.contains(element));
print(a); //[3, 4, 5]


问:
How can we Create JavaScript Objects which has functions
```<code>var cars = {
    "c1":"BMW",
    "c2":"Volvo",
    "c3":["Saab","jas"],
    "c4":{"Ford":"cdsnj", "Ford1":"cdsnj", "Ford2":"cdsnj"}
    "myMethod" = () =>{
        console.log("eFNJVSL")
    },
};
</code>```
<p>The way I tried </p>

答:
Replace the = with :

var cars = {
    "c1":"BMW",
    "c2":"Volvo",
    "c3":["Saab","jas"],
    "c4":{"Ford":"cdsnj", "Ford1":"cdsnj", "Ford2":"cdsnj"},
    "myMethod" : () =>{
        console.log("eFNJVSL")
    },
};```

Body:
var cars = {
    "c1":"BMW",
    "c2":"Volvo",
    "c3":["Saab","jas"],
    "c4":{"Ford":"cdsnj", "Ford1":"cdsnj", "Ford2":"cdsnj"}
    "myMethod" = () =>{
        console.log("eFNJVSL")
    },
};

The way I tried


问:
How to get access to inherited object properties in WCF?
The case is:

```<code>[ServiceContract]
public interface IInfo
{
    [DataMember]
    int Id{get;set;}
}

[DataContract]
[KnownType(typeof(Legal))]
public class Info
{
    [DataMember]
    public int Id { get; set; }
}

[DataContract]
public class Legal : Info
{
    [DataMember]
    public string ManagerName { get; set; }
}

[ServiceContract]
[ServiceKnownType(typeof(Legal))]
public interface IMyService
{
    [OperationContract]
    int DoWork(Info dto);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{

    public int DoWork(Info dto)
    {
        string name;
        if (dto is Legal)
            name = (dto as Legal).ManagerName;
        return dto.Id;
    }
}
</code>```

Is it possible to know the dto as Legal type and have access to the child properties?

I want to store the dto and I don't want to have many services for each child of info.

Passing Generics to service doesn't work, wsdl error,
Interface such as IInfo as input parameter doesn't work, casting error,
Base class like Info doesn't work, child props are not accessible,
stack overflow doesn't work, this is my 2nd time i post this prob but no answer!

答:
I'm passing a json as dto to MyService.
If i add "__type":"Legal:#Dto", MyService recognize the dto as Legal.
then (dto as Legal).ManagerName has value

This solution is working, actually passing __type is not handy way. I'll appreciate your better suggestions.

Body:
The case is:

[ServiceContract]
public interface IInfo
{
    [DataMember]
    int Id{get;set;}
}

[DataContract]
[KnownType(typeof(Legal))]
public class Info
{
    [DataMember]
    public int Id { get; set; }
}

[DataContract]
public class Legal : Info
{
    [DataMember]
    public string ManagerName { get; set; }
}

[ServiceContract]
[ServiceKnownType(typeof(Legal))]
public interface IMyService
{
    [OperationContract]
    int DoWork(Info dto);
}

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{

    public int DoWork(Info dto)
    {
        string name;
        if (dto is Legal)
            name = (dto as Legal).ManagerName;
        return dto.Id;
    }
}

Is it possible to know the dto as Legal type and have access to the child properties?

I want to store the dto and I don't want to have many services for each child of info.

Passing Generics to service doesn't work, wsdl error,
Interface such as IInfo as input parameter doesn't work, casting error,
Base class like Info doesn't work, child props are not accessible,
stack overflow doesn't work, this is my 2nd time i post this prob but no answer!


问:
How do I turn VSCode Word Wrap off as default?
VS Code Version 1.36.1 for Mac.

Every time when I open VSCode, the word wrap is on. I have to ⌥+Z to turn it off. Whenever I close VSCode and reopen it, I have to do this again.

While in the Settings, either in User or Workspace, Editor: Word Wrap is off.

What am I doing it wrong? How to fix it?

答:
I still encountered this issue in v1.64.2 on MacOS. I found a workaround in this Github thread answer. Setting or adding accessibility option to "on" worked for me.

```<code>"editor.accessibilitySupport": "on"
</code>```

Body:
I still encountered this issue in v1.64.2 on MacOS. I found a workaround in this Github thread answer. Setting or adding accessibility option to "on" worked for me.

"editor.accessibilitySupport": "on"


问:
Java Logger usage
I made a custom logger for my project by using java.util.logging:

public class SpotifyLogger {
    private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public SpotifyLogger(String loggerFilePath) throws IOException {
        Logger myLogger = Logger.getLogger("");
        // suppress console messaging
        Handler[] handlers = myLogger.getHandlers();
        if (handlers[0] instanceof ConsoleHandler) { //exception occurs here
            myLogger.removeHandler(handlers[0]);
        }
        // set level
        LOGGER.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        LOGGER.addHandler(textFileHandler);
    }
    public void log(String user, Exception e) {
        LOGGER.log(Level.SEVERE, user, e);
    }
}
```
<p>For the client and the server parts of my program, I create two separate Logger objects:</p>
<pre class="lang-java prettyprint-override"><code>// class member initialized as null, because of exception handling
private SpotifyLogger logger = null;
//...
//in constructor:
this.logger = new SpotifyLogger(LOGGER_FILE_NAME); // the LOGGER_FILE_NAME is different for the client and the server
</code>```

When I test my program manually, the loggers seem to work (the two log files contain exceptions that I have caused). Then, I wrote automatic tests. For each class that I am testing (a total of 5), I create a separate logger object with a different destination path. The tests (for whichever class comes first) work correctly. All other tests fail because I get an ArrayIndexOutOfBoundsException, when I initialize the logger for that particular class. The reason is that I am trying to access handlers[0], when handlers has 0 length. From what I understood after searching the web, this is because the logger is using parent handlers. I tried this:

public SpotifyLogger(String loggerFilePath) throws IOException {
    Logger myLogger = Logger.getLogger("");
    // suppress console messaging
    myLogger.setUseParentHandlers(false);
    Handler[] handlers = myLogger.getHandlers();
    if (handlers.length > 0) {
        if (handlers[0] instanceof ConsoleHandler) {
            myLogger.removeHandler(handlers[0]);
        }
    }
    //etc
}
```

I don't get an exception anymore but the logging doesn't work. What am I doing wrong?

答:
If you want different Loggers, you need to supply different names for each. Hence this line of your code (in SpotifyLogger constructor) always returns the same Logger.

Logger myLogger = Logger.getLogger("");
```
<p>This actually returns the <code>java.util.logging.LogManager.RootLogger</code> which has a single <code>Handler</code> which is an instance of <code>ConsoleLogger</code>. You subsequently remove that <code>Handler</code> in the first invocation of <code>SpotifyLogger</code> constructor, hence in every subsequent invocation, method <code>getHandlers</code> returns an empty array.</p>
<p>Since you only ever add <code>Handler</code>s to the global <code>Logger</code>, another <code>FileHandler</code> is added to the global logger every time <code>SpotifyLogger</code> constructor is called. I have not verified but I believe that a <code>Logger</code> will use the first, appropriate <code>Handler</code> in the array returned by method <code>getHandlers</code>, hence the behavior you are seeing whereby only the first log file is being written to, i.e. the file that you passed to the first invocation of <code>SpotifyLogger</code> constructor.</p>
<p>Note that you have not provided a reproducible example so I cannot verify any of the above with regard to your context. I only tested the code in your question in order to arrive at the above.</p>
<p>Consider the following rewrite of class <code>SpotifyLogger</code> – including a <code>main</code> method for testing purposes only.</p>
<pre class="lang-java prettyprint-override"><code>import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class SpotifyLogger {
    private static final String[]  NAMES = {"First", "Second"};
    private static int  count;

    private int  index;

    public SpotifyLogger(String loggerFilePath) throws IOException {
        index = count;
        Logger myLogger = Logger.getLogger(NAMES[count++]);
        myLogger.setUseParentHandlers(false);
        // set level
        myLogger.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        myLogger.addHandler(textFileHandler);
    }

    public void log(String user, Exception e) {
        Logger myLogger = Logger.getLogger(NAMES[index]);
        myLogger.log(Level.SEVERE, user, e);
    }

    public static void main(String[] args) {
        try {
            SpotifyLogger x = new SpotifyLogger("spotifyx.log");
            SpotifyLogger y = new SpotifyLogger("spotifyy.log");
            x.log("George", new Exception());
            y.log("Martha", new RuntimeException());
        }
        catch (IOException x) {
            x.printStackTrace();
        }
    }
}
</code>```

Note that you are correct regarding parent Handlers, hence the following line in the above code:

myLogger.setUseParentHandlers(false);
```
<p>After running the above code, the contents of file <em>spotifyx.log</em> is:</p>
<pre class="lang-none prettyprint-override"><code>Feb 12, 2022 2:12:28 PM javalogp.SpotifyLogger log
SEVERE: George
java.lang.Exception
    at javalogp/javalogp.SpotifyLogger.main(SpotifyLogger.java:38)
</code>```

And the contents of file spotifyy.log is:

Feb 12, 2022 2:12:28 PM javalogp.SpotifyLogger log
SEVERE: Martha
java.lang.RuntimeException
    at javalogp/javalogp.SpotifyLogger.main(SpotifyLogger.java:39)
```

And no log messages are written to the console.

Title: Java Logger usage

Body:
I made a custom logger for my project by using java.util.logging:

public class SpotifyLogger {
    private static final Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    public SpotifyLogger(String loggerFilePath) throws IOException {
        Logger myLogger = Logger.getLogger("");
        // suppress console messaging
        Handler[] handlers = myLogger.getHandlers();
        if (handlers[0] instanceof ConsoleHandler) { //exception occurs here
            myLogger.removeHandler(handlers[0]);
        }
        // set level
        LOGGER.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        LOGGER.addHandler(textFileHandler);
    }
    public void log(String user, Exception e) {
        LOGGER.log(Level.SEVERE, user, e);
    }
}

For the client and the server parts of my program, I create two separate Logger objects:

// class member initialized as null, because of exception handling
private SpotifyLogger logger = null;
//...
//in constructor:
this.logger = new SpotifyLogger(LOGGER_FILE_NAME); // the LOGGER_FILE_NAME is different for the client and the server

When I test my program manually, the loggers seem to work (the two log files contain exceptions that I have caused). Then, I wrote automatic tests. For each class that I am testing (a total of 5), I create a separate logger object with a different destination path. The tests (for whichever class comes first) work correctly. All other tests fail because I get an ArrayIndexOutOfBoundsException, when I initialize the logger for that particular class. The reason is that I am trying to access handlers[0], when handlers has 0 length. From what I understood after searching the web, this is because the logger is using parent handlers. I tried this:

public SpotifyLogger(String loggerFilePath) throws IOException {
    Logger myLogger = Logger.getLogger("");
    // suppress console messaging
    myLogger.setUseParentHandlers(false);
    Handler[] handlers = myLogger.getHandlers();
    if (handlers.length > 0) {
        if (handlers[0] instanceof ConsoleHandler) {
            myLogger.removeHandler(handlers[0]);
        }
    }
    //etc
}

I don't get an exception anymore but the logging doesn't work. What am I doing wrong?

Body:
If you want different Loggers, you need to supply different names for each. Hence this line of your code (in SpotifyLogger constructor) always returns the same Logger.

Logger myLogger = Logger.getLogger("");

This actually returns the java.util.logging.LogManager.RootLogger which has a single Handler which is an instance of ConsoleLogger. You subsequently remove that Handler in the first invocation of SpotifyLogger constructor, hence in every subsequent invocation, method getHandlers returns an empty array.

Since you only ever add Handlers to the global Logger, another FileHandler is added to the global logger every time SpotifyLogger constructor is called. I have not verified but I believe that a Logger will use the first, appropriate Handler in the array returned by method getHandlers, hence the behavior you are seeing whereby only the first log file is being written to, i.e. the file that you passed to the first invocation of SpotifyLogger constructor.

Note that you have not provided a reproducible example so I cannot verify any of the above with regard to your context. I only tested the code in your question in order to arrive at the above.

Consider the following rewrite of class SpotifyLogger – including a main method for testing purposes only.

import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class SpotifyLogger {
    private static final String[]  NAMES = {"First", "Second"};
    private static int  count;

    private int  index;

    public SpotifyLogger(String loggerFilePath) throws IOException {
        index = count;
        Logger myLogger = Logger.getLogger(NAMES[count++]);
        myLogger.setUseParentHandlers(false);
        // set level
        myLogger.setLevel(Level.SEVERE);
        // create a txt handler
        FileHandler textFileHandler = new FileHandler(loggerFilePath);
        SimpleFormatter simpleFormatter = new SimpleFormatter();
        textFileHandler.setFormatter(simpleFormatter);
        myLogger.addHandler(textFileHandler);
    }

    public void log(String user, Exception e) {
        Logger myLogger = Logger.getLogger(NAMES[index]);
        myLogger.log(Level.SEVERE, user, e);
    }

    public static void main(String[] args) {
        try {
            SpotifyLogger x = new SpotifyLogger("spotifyx.log");
            SpotifyLogger y = new SpotifyLogger("spotifyy.log");
            x.log("George", new Exception());
            y.log("Martha", new RuntimeException());
        }
        catch (IOException x) {
            x.printStackTrace();
        }
    }
}

Note that you are correct regarding parent Handlers, hence the following line in the above code:

myLogger.setUseParentHandlers(false);

After running the above code, the contents of file spotifyx.log is:

Feb 12, 2022 2:12:28 PM javalogp.SpotifyLogger log
SEVERE: George
java.lang.Exception
    at javalogp/javalogp.SpotifyLogger.main(SpotifyLogger.java:38)

And the contents of file spotifyy.log is:

Feb 12, 2022 2:12:28 PM javalogp.SpotifyLogger log
SEVERE: Martha
java.lang.RuntimeException
    at javalogp/javalogp.SpotifyLogger.main(SpotifyLogger.java:39)

And no log messages are written to the console.


问:
Warning: the running version of Bundler is older than the version that created the lockfile error
When I'm developing/testing, I'm keep getting this error in my console

```<code>Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.
</code>```

It's not blocking me at all but bugging me. I know that easiest solution is just updating my Gemfile.lock to this.

```<code>BUNDLED WITH
   2.1.2
</code>```

But I want to solve this permanently. I try to

```<code>gem uninstall bundler
</code>```

and then

```<code>gem install bundler -v 2.1.4
</code>```

It keeps me giving this error

```<code>Gem bundler-2.1.2 cannot be uninstalled because it is a default gem
</code>```

and when I try to first install 2.1.4 and then delete bundler 2.1.2 console gives me this output.

```<code>Gem bundler-2.1.2 cannot be uninstalled because it is a default gem
Successfully uninstalled bundler-2.1.4
</code>```

Is there any solution to this problem? Thanks in advance

答:
Another option is to update to the latest version:

```<code>gem update bundler
</code>```

Unless there is a specific reason for using an older version (for example, there is a bug in the latest version, or they are no longer compatible), then you can follow the warning message to just install that particular version:

Warning: the running version of Bundler (2.2.32) is older than the version that created the lockfile (2.3.4). We suggest you to upgrade to the version that created the lockfile by running gem install bundler:2.3.4.

```<code>gem install bundler:2.3.4
</code>```

Body:
When I'm developing/testing, I'm keep getting this error in my console

Warning: the running version of Bundler (2.1.2) is older than the version that created the lockfile (2.1.4). We suggest you to upgrade to the version that created the lockfile by running `gem install bundler:2.1.4`.

It's not blocking me at all but bugging me. I know that easiest solution is just updating my Gemfile.lock to this.

BUNDLED WITH
   2.1.2

But I want to solve this permanently. I try to

gem uninstall bundler

and then

gem install bundler -v 2.1.4

It keeps me giving this error

Gem bundler-2.1.2 cannot be uninstalled because it is a default gem

and when I try to first install 2.1.4 and then delete bundler 2.1.2 console gives me this output.

Gem bundler-2.1.2 cannot be uninstalled because it is a default gem
Successfully uninstalled bundler-2.1.4

Is there any solution to this problem? Thanks in advance

Body:
Another option is to update to the latest version:

gem update bundler

Unless there is a specific reason for using an older version (for example, there is a bug in the latest version, or they are no longer compatible), then you can follow the warning message to just install that particular version:

Warning: the running version of Bundler (2.2.32) is older than the version that created the lockfile (2.3.4). We suggest you to upgrade to the version that created the lockfile by running gem install bundler:2.3.4.

gem install bundler:2.3.4


问:
PKCE vs DCR for OAuth2 and Mobile Applications
I’m developing my own OAuth2 + OpenID Connect implementation. I am a bit confused about how to handle OAuth flows for native (specifically, Mobile) clients. So far, I am seeing that I need to use an Authentication Code Flow. However, based on my research, there are some details that seem to contradict each other(at least based on my current understanding).

First, standard practice seems to say that mobile apps are not inherently private and, as such, standard flows that make use of a back channel should not be used. As a work around, the PKCE extension can be used (and utilize the built-in device browser as opposed to a web view so the tokens and sensitive information are less likely to be leaked).

However, under the Protocol’s Dynamic Client Registration specification, it is also mentioned that mobile apps should use this method of client registration to get a valid client ID and client secret...  But, why would we do this when in an earlier section it was established that mobile applications were indeed public clients and couldn’t be trusted with confidential information like a client secret (which we are getting by using this DCR mechanism...

So, what am I not understanding? These two things seem to contradict one another. One claims mobile apps are public shouldn’t be trusted with a secret. Yet, in the recommended DCR mechanism, we assign them the secret we just established they can’t be trusted with.

Thanks.

答:
A bit late, but hope it helps. So part of the OAuth2.0 protocol is two components, the client_id, and client secret. The client and server must agree on those two values outside the protocol i.e. before the protocol start. Usually, the process is as follows. The client communicates with the Authorization Server using an out-of-bound communication channel to get these values and be registered at the server. There is two way this client registration can happen, statically and dynamically. Statically mean the client_id and secret do change, i.e. the client gets them once when he registers with the server. Dynamic client registration refers to the process of registering a client_id every time the client wants to use to protocol, i.e. a client secret will be generated for him every time (also by an outbound communication).

Now, Why use dynamic registration?

Dynamic client registration is better at managing clients across replicated authorization servers., The original OAuth use cases revolved around single-location APIs, such as those from companies providing web services. These APIs require specialized clients to talk to them, and those clients will need to talk to only a single API provider. In these cases, it doesn’t seem unreasonable to expect client developers to put in the effort to register their client with the API, because there’s only one provider.

Does Dynamic Client registration offer any security advantages?

No, both are vulnerable if used with a JavaScript or a Native Mobile Client (JavaScript client can be inspected, and Mobile apps can be decompiled). Hence, both of them require PKCE as an extra layer of security.


问:
C - Read input from text file (int,string,int,int)
First of all sorry for any english error.
So, I have this data in a .txt file

```<code>Codigo,Produto,StockMinimo,StockAtual
1,Couro,300,1000
2,Tecido,250,2000
...
</code>```

I want to skip the first line and read only the integers to a struct

I'm using the bellow function to count the line of the file:

```<code>int nrLinhasFicheiro(char *filename){
    char ch;
    FILE *file;
    file = fopen(filename, "r");
    int linhas = 0;
    if (file != NULL) {
         for (ch = getc(file); ch != EOF; ch = getc(file))
        if (ch == '\n')
            linhas = linhas + 1;
    }
    fclose(file);
    return linhas - 1;
}
</code>```

and this one to read the file to the struct "Stock" :

```<code>void carregarStock(Stock *stock, char *nomeFicheiro){
    int i = 0;
    int codigo; //stores "codigo" values
    char stringFake[40], *storeProduto; //variables to store first line and "Produto" string
    int minimo, quantidade;

    FILE *fp = fopen(nomeFicheiro, "r");

    int numeroLinhas = nrLinhasFicheiro(nomeFicheiro);

    if (fp != NULL){

        if(numeroLinhas >0){
            fscanf(fp, "%s",stringFake);//skip first line

            while(i< numeroLinhas){
                fscanf(fp, "%d,%s ,%d,%d", &codigo, storeProduto, &minimo, &quantidade);
                //fscanf(fp, "%d,%s %d,%d", &codigo, storeProduto, &minimo, &quantidade);  also tried this and don't work

                if(codigo==1){
                    stock->minStockCouro = minimo;
                    stock->couroStock = quantidade;
                }else if(codigo==2){
                    stock->minStockTecido = minimo;
                    stock->tecidoStock = quantidade;
                }else if(codigo==3){
                    stock->minStockBorracha = minimo;
                    stock->borrachaStock = quantidade;
                }else if(codigo==4){
                    stock->minStockCordoes = minimo;
                    stock->cordoesStock = quantidade;
                }else if(codigo==5){
                    stock->minStockPalmilhas = minimo;
                    stock->palmilhasStock = quantidade;
                }
                i++;
            }

        }else{
            puts("Error");
        }
    }else{
        puts(MSG_ERRO_LER_FICHEIRO);
    }
    fclose(fp);
}
</code>```

Function to print the struct:

```<code>void mostrarStock(Stock stock){
    puts("==============  Stock : =============\n");
    puts("Codigo | Produto | Stock Minimo | Stock Atual\n");
    printf("1\tCouro\t\t%d\t\t%d\n", stock.minStockCouro, stock.couroStock);
    printf("2\tTecido\t\t%d\t\t%d\n", stock.minStockTecido, stock.tecidoStock);
    printf("3\tBorracha\t%d\t\t%d\n", stock.minStockBorracha, stock.borrachaStock);
    printf("4\tCordões\t\t%d\t\t%d\n", stock.minStockCordoes, stock.cordoesStock);
    printf("5\tPalmilhas\t%d\t\t%d\n", stock.minStockPalmilhas, stock.palmilhasStock);

}
</code>```

This is how i call the function in main:

```<code>int main(int argc, char** argv) {

    char *nomeFicheiro1 = "tabela_stocks.txt";
    Stock stock;
    carregarStock(&stock, nomeFicheiro1);
    mostrarStock(stock);

    return (EXIT_SUCCESS);
}
</code>```

The function to print the struct doesn't print.
I guess the error is in

```<code>fscanf(fp, "%d,%s ,%d,%d", &codigo, storeProduto, &minimo, &quantidade);
</code>```

What am I doing wrong?

答:
You could create a helper function to read out the two integers from one line.

```<code>bool get_two(FILE *stream, int* a, int* b) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", a, b) == 2;
}
</code>```

You then just need to call that 5 times.

Example:

#include <stdbool.h>
#include <stdio.h>

typedef struct {
    int couroStock;
    int minStockCouro;
    int tecidoStock;
    int minStockTecido;
    int borrachaStock;
    int minStockBorracha;
    int cordoesStock;
    int minStockCordoes;
    int palmilhasStock;
    int minStockPalmilhas;
} Stock;

bool get_two(FILE *stream, int* a, int* b) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", a, b) == 2;
}

int main() {
    FILE *fp = fopen("tabela_stocks.txt", "r");
    if(fp) {
        Stock s;
        fscanf(fp, "%*[^\n]"); // skip first line

        if(get_two(fp, &s.couroStock, &s.minStockCouro) &&
           get_two(fp, &s.tecidoStock, &s.minStockTecido) &&
           get_two(fp, &s.borrachaStock, &s.minStockBorracha) &&
           get_two(fp, &s.cordoesStock, &s.minStockCordoes) &&
           get_two(fp, &s.palmilhasStock, &s.minStockPalmilhas))
        {
            printf("%d %d\n", s.couroStock, s.minStockCouro);
            printf("%d %d\n", s.tecidoStock, s.minStockTecido);
            printf("%d %d\n", s.borrachaStock, s.minStockBorracha);
            printf("%d %d\n", s.cordoesStock, s.minStockCordoes);
            printf("%d %d\n", s.couroStock, s.minStockCouro);
        }
        fclose(fp);
    }
}
```
<p>If <code>tabela_stocks.txt</code> contains</p>
```Codigo,Produto,StockMinimo,StockAtual
1,Couro,300,1000
2,Tecido,250,2000
3,Borracha,200,500
4,Cordões,500,2000
5,Palmilhas,500,1000
```
<p>Then the output will be</p>
```300 1000
250 2000
200 500
500 2000
300 1000
```
<hr />
<p>Since there are so many similarities between the different stocks in your <code>Stock</code> <code>struct</code>, you could break it down into smaller pieces and make a <code>struct</code> only holding information about <em>one</em> stock:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdbool.h>
#include <stdio.h>

typedef struct {
    int stock;
    int min_stock;
} Stock;

bool Stock_read(FILE *stream, Stock *s) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", &s->stock, &s->min_stock) == 2;
}

void Stock_print(const Stock *s) {
    printf("%d %d\n", s->stock, s->min_stock);
}
</code>```

With that you could create a Stocks type like this:

typedef struct {
    Stock Couro;
    Stock Tecido;
    Stock Borracha;
    Stock Cordoes;
    Stock Palmilhas;
} Stocks;

bool Stocks_read(FILE *stream, Stocks *s) {
    return
        Stock_read(stream, &s->Couro) &&
        Stock_read(stream, &s->Tecido) &&
        Stock_read(stream, &s->Borracha) &&
        Stock_read(stream, &s->Cordoes) &&
        Stock_read(stream, &s->Palmilhas);
}

void Stocks_print(const Stocks *s) {
    Stock_print(&s->Couro);
    Stock_print(&s->Tecido);
    Stock_print(&s->Borracha);
    Stock_print(&s->Cordoes);
    Stock_print(&s->Palmilhas);
}
```
<p>and reading and printing would become simpler:</p>
<pre class="lang-c prettyprint-override"><code>int main() {
    FILE *fp = fopen("tabela_stocks.txt", "r");
    if(fp) {
        Stocks s;
        fscanf(fp, "%*[^\n]"); // skip first line

        if(Stocks_read(fp, &s)) {
            Stocks_print(&s);
        }
        fclose(fp);
    }
}
</code>```

Looking closer at the Stocks struct you may want to consider using an array instead:

```<code>typedef struct {
    Stock stocks[5];
} Stocks;
</code>```

which would also simplify the rest of the code since you could loop over that array to read and print each Stock.

Body:
First of all sorry for any english error.
So, I have this data in a .txt file

Codigo,Produto,StockMinimo,StockAtual
1,Couro,300,1000
2,Tecido,250,2000
...

I want to skip the first line and read only the integers to a struct

I'm using the bellow function to count the line of the file:

int nrLinhasFicheiro(char *filename){
    char ch;
    FILE *file;
    file = fopen(filename, "r");
    int linhas = 0;
    if (file != NULL) {
         for (ch = getc(file); ch != EOF; ch = getc(file))
        if (ch == '\n')
            linhas = linhas + 1;
    }
    fclose(file);
    return linhas - 1;
}

and this one to read the file to the struct "Stock" :

void carregarStock(Stock *stock, char *nomeFicheiro){
    int i = 0;
    int codigo; //stores "codigo" values
    char stringFake[40], *storeProduto; //variables to store first line and "Produto" string
    int minimo, quantidade;

    FILE *fp = fopen(nomeFicheiro, "r");

    int numeroLinhas = nrLinhasFicheiro(nomeFicheiro);

    if (fp != NULL){

        if(numeroLinhas >0){
            fscanf(fp, "%s",stringFake);//skip first line

            while(i< numeroLinhas){
                fscanf(fp, "%d,%s ,%d,%d", &codigo, storeProduto, &minimo, &quantidade);
                //fscanf(fp, "%d,%s %d,%d", &codigo, storeProduto, &minimo, &quantidade);  also tried this and don't work

                if(codigo==1){
                    stock->minStockCouro = minimo;
                    stock->couroStock = quantidade;
                }else if(codigo==2){
                    stock->minStockTecido = minimo;
                    stock->tecidoStock = quantidade;
                }else if(codigo==3){
                    stock->minStockBorracha = minimo;
                    stock->borrachaStock = quantidade;
                }else if(codigo==4){
                    stock->minStockCordoes = minimo;
                    stock->cordoesStock = quantidade;
                }else if(codigo==5){
                    stock->minStockPalmilhas = minimo;
                    stock->palmilhasStock = quantidade;
                }
                i++;
            }

        }else{
            puts("Error");
        }
    }else{
        puts(MSG_ERRO_LER_FICHEIRO);
    }
    fclose(fp);
}

Function to print the struct:

void mostrarStock(Stock stock){
    puts("==============  Stock : =============\n");
    puts("Codigo | Produto | Stock Minimo | Stock Atual\n");
    printf("1\tCouro\t\t%d\t\t%d\n", stock.minStockCouro, stock.couroStock);
    printf("2\tTecido\t\t%d\t\t%d\n", stock.minStockTecido, stock.tecidoStock);
    printf("3\tBorracha\t%d\t\t%d\n", stock.minStockBorracha, stock.borrachaStock);
    printf("4\tCordões\t\t%d\t\t%d\n", stock.minStockCordoes, stock.cordoesStock);
    printf("5\tPalmilhas\t%d\t\t%d\n", stock.minStockPalmilhas, stock.palmilhasStock);

}

This is how i call the function in main:

int main(int argc, char** argv) {

    char *nomeFicheiro1 = "tabela_stocks.txt";
    Stock stock;
    carregarStock(&stock, nomeFicheiro1);
    mostrarStock(stock);

    return (EXIT_SUCCESS);
}

The function to print the struct doesn't print.
I guess the error is in

fscanf(fp, "%d,%s ,%d,%d", &codigo, storeProduto, &minimo, &quantidade);

What am I doing wrong?

Body:
You could create a helper function to read out the two integers from one line.

bool get_two(FILE *stream, int* a, int* b) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", a, b) == 2;
}

You then just need to call that 5 times.

Example:

#include <stdbool.h>
#include <stdio.h>

typedef struct {
    int couroStock;
    int minStockCouro;
    int tecidoStock;
    int minStockTecido;
    int borrachaStock;
    int minStockBorracha;
    int cordoesStock;
    int minStockCordoes;
    int palmilhasStock;
    int minStockPalmilhas;
} Stock;

bool get_two(FILE *stream, int* a, int* b) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", a, b) == 2;
}

int main() {
    FILE *fp = fopen("tabela_stocks.txt", "r");
    if(fp) {
        Stock s;
        fscanf(fp, "%*[^\n]"); // skip first line

        if(get_two(fp, &s.couroStock, &s.minStockCouro) &&
           get_two(fp, &s.tecidoStock, &s.minStockTecido) &&
           get_two(fp, &s.borrachaStock, &s.minStockBorracha) &&
           get_two(fp, &s.cordoesStock, &s.minStockCordoes) &&
           get_two(fp, &s.palmilhasStock, &s.minStockPalmilhas))
        {
            printf("%d %d\n", s.couroStock, s.minStockCouro);
            printf("%d %d\n", s.tecidoStock, s.minStockTecido);
            printf("%d %d\n", s.borrachaStock, s.minStockBorracha);
            printf("%d %d\n", s.cordoesStock, s.minStockCordoes);
            printf("%d %d\n", s.couroStock, s.minStockCouro);
        }
        fclose(fp);
    }
}

If tabela_stocks.txt contains

Codigo,Produto,StockMinimo,StockAtual
1,Couro,300,1000
2,Tecido,250,2000
3,Borracha,200,500
4,Cordões,500,2000
5,Palmilhas,500,1000

Then the output will be

300 1000
250 2000
200 500
500 2000
300 1000

Since there are so many similarities between the different stocks in your Stock struct, you could break it down into smaller pieces and make a struct only holding information about one stock:

#include <stdbool.h>
#include <stdio.h>

typedef struct {
    int stock;
    int min_stock;
} Stock;

bool Stock_read(FILE *stream, Stock *s) {
    return fscanf(stream, " %*[^,],%*[^,],%d,%d", &s->stock, &s->min_stock) == 2;
}

void Stock_print(const Stock *s) {
    printf("%d %d\n", s->stock, s->min_stock);
}

With that you could create a Stocks type like this:

typedef struct {
    Stock Couro;
    Stock Tecido;
    Stock Borracha;
    Stock Cordoes;
    Stock Palmilhas;
} Stocks;

bool Stocks_read(FILE *stream, Stocks *s) {
    return
        Stock_read(stream, &s->Couro) &&
        Stock_read(stream, &s->Tecido) &&
        Stock_read(stream, &s->Borracha) &&
        Stock_read(stream, &s->Cordoes) &&
        Stock_read(stream, &s->Palmilhas);
}

void Stocks_print(const Stocks *s) {
    Stock_print(&s->Couro);
    Stock_print(&s->Tecido);
    Stock_print(&s->Borracha);
    Stock_print(&s->Cordoes);
    Stock_print(&s->Palmilhas);
}

and reading and printing would become simpler:

int main() {
    FILE *fp = fopen("tabela_stocks.txt", "r");
    if(fp) {
        Stocks s;
        fscanf(fp, "%*[^\n]"); // skip first line

        if(Stocks_read(fp, &s)) {
            Stocks_print(&s);
        }
        fclose(fp);
    }
}

Looking closer at the Stocks struct you may want to consider using an array instead:

typedef struct {
    Stock stocks[5];
} Stocks;

which would also simplify the rest of the code since you could loop over that array to read and print each Stock.


问:
When should I use semicolons in SQL Server?
While checking some code on the web and scripts generated by SQL Server Management Studio I have noticed that some statements are ended with a semicolon.

So when should I use it?

答:
In SQL2008 BOL they say that in next releases semicolons will be required. Therefore, always use it.

Reference:

Transact-SQL Syntax Conventions (Transact-SQL)

Deprecated Database Engine Features in SQL Server 2008 R2 ("Features Not Supported in a Future Version of SQL Server" section, "Transact-SQL" area)

OwnerDisplayName: apinto

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Rich B

OwnerDisplayName: GSerg


问:
Heroku Postgres: AWS s3 presigned URL not working
I am 6 hours into this error and going mad.

I have created a heroku app using the CLI and pushed the git successfully however I need to initialise a bunch of tables using db.create_all() before the app works, but I have 6gb of data in my localhost postgres that I wish to migrate to heroku for use.

Instantiating the tables in the usual way (create_all) won't work because certain content is required from tables for the index page hence my tables must be pre-populated with said localhost data before it will work.

I have followed the documentation here to the letter and exported my .dump file and uploaded it to my bucket: https://devcenter.heroku.com/articles/heroku-postgres-import-export#import

Public sharing is enabled, and I have used setx commands to set ACCESS_KEY_ID and SECRET_ACCESS_KEY in the AWS CLI. I have also set heroku config:set AWS_ACCESS_KEY_ID=matching_aws_cli_blah AWS_SECRET_ACCESS_KEY=matching_aws_cli_blah.

Then using the command aws s3 presign s3_url I have copied the output (which I'll add looks different to AWS documentation I used https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/presign.html)

An example of how mine looks (randomly changed some figures)
https://mybucketname.s3.eu-west-2.amazonaws.com/mydb.dump?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=LLLLL4C7LLLLLLLNLLLQ%2FNNNNNN08%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201208T004613Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ll9d80nnnnc457ea83298fdnnnn4a25b0c9ll066f54e6ff8acf42dafnnnea8877 whereas the documentation provides a nice neat AWSAccessKeyId= variable.

I have only one bucket and the Block public access (bucket settings) is set to OFF and the file itself is share-able publicly. The object URL initialises the download fine, including in incognito.

When using the following command (as per heroku documentation)

heroku pg:backups:restore 'https://mybucketname.s3.eu-west-2.amazonaws.com/mydb.dump?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=LLLLL4C7LLLLLLLNLLLQ%2FNNNNNN08%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201208T004613Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ll9d80nnnnc457ea83298fdnnnn4a25b0c9ll066f54e6ff8acf42dafnnnea8877' DATABASE_URL

I get the following output to terminal.

```<code>Restoring... !
 !    An error occurred and the backup did not finish.
 !
 !    waiting for restore to complete
 !    pg_restore finished with errors
 !    waiting for download to complete
 !    download finished with errors
 !    please check the source URL and ensure it is publicly accessible
 !
 !    Run heroku pg:backups:info r001 for more details.
'X-Amz-Credential' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Date' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Expires' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-SignedHeaders' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Signature' is not recognized as an internal or external command,
operable program or batch file.
</code>```

which in the log file shows

```<code>=== Backup r001
Database:         BACKUP
Started at:       2020-12-08 00:47:33 +0000
Finished at:      2020-12-08 00:47:34 +0000
Status:           Failed
Type:             Manual
Backup Size:      0.00B (0% compression)

=== Backup Logs
2020-12-08 00:47:34 +0000 2020/12/08 00:47:34 aborting: could not write to output stream: Expected HTTP Status 200, received: "400 Bad Request"
2020-12-08 00:47:34 +0000 pg_restore: error: could not read from input file: end of file
2020-12-08 00:47:34 +0000 waiting for restore to complete
2020-12-08 00:47:34 +0000 pg_restore finished with errors
2020-12-08 00:47:34 +0000 waiting for download to complete
2020-12-08 00:47:34 +0000 download finished with errors
2020-12-08 00:47:34 +0000 please check the source URL and ensure it is publicly accessible
</code>```

Please can someone point where I am going wrong?

Thanks!

答:
In order to debug this, it might be useful to get the response error message from the request to your AWS url, which you can easily do with curl:

```<code>curl <SIGNED AWS URL>
</code>```

In my case I got the following message:

```<code>Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'eu-west-3'
</code>```

Which means that for some reason AWS is signing my URL with the wrong region. If I try to manually add the right region to my signed url then the request fails because the signatures don't match.

Instead, I need to make AWS sign the URL correctly by specifying the region in the presign command:

```<code>aws s3 presign s3://URL --region eu-west-3
</code>```

when I did this and used the resulting signed url with the heroku pg:backups:restore command, the request was successful and heroku was able to import my db.

Body:
I am 6 hours into this error and going mad.

I have created a heroku app using the CLI and pushed the git successfully however I need to initialise a bunch of tables using db.create_all() before the app works, but I have 6gb of data in my localhost postgres that I wish to migrate to heroku for use.

Instantiating the tables in the usual way (create_all) won't work because certain content is required from tables for the index page hence my tables must be pre-populated with said localhost data before it will work.

I have followed the documentation here to the letter and exported my .dump file and uploaded it to my bucket: https://devcenter.heroku.com/articles/heroku-postgres-import-export#import

Public sharing is enabled, and I have used setx commands to set ACCESS_KEY_ID and SECRET_ACCESS_KEY in the AWS CLI. I have also set heroku config:set AWS_ACCESS_KEY_ID=matching_aws_cli_blah AWS_SECRET_ACCESS_KEY=matching_aws_cli_blah.

Then using the command aws s3 presign s3_url I have copied the output (which I'll add looks different to AWS documentation I used https://awscli.amazonaws.com/v2/documentation/api/latest/reference/s3/presign.html)

An example of how mine looks (randomly changed some figures)
https://mybucketname.s3.eu-west-2.amazonaws.com/mydb.dump?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=LLLLL4C7LLLLLLLNLLLQ%2FNNNNNN08%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201208T004613Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ll9d80nnnnc457ea83298fdnnnn4a25b0c9ll066f54e6ff8acf42dafnnnea8877 whereas the documentation provides a nice neat AWSAccessKeyId= variable.

I have only one bucket and the Block public access (bucket settings) is set to OFF and the file itself is share-able publicly. The object URL initialises the download fine, including in incognito.

When using the following command (as per heroku documentation)

heroku pg:backups:restore 'https://mybucketname.s3.eu-west-2.amazonaws.com/mydb.dump?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=LLLLL4C7LLLLLLLNLLLQ%2FNNNNNN08%2Feu-west-2%2Fs3%2Faws4_request&X-Amz-Date=20201208T004613Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=ll9d80nnnnc457ea83298fdnnnn4a25b0c9ll066f54e6ff8acf42dafnnnea8877' DATABASE_URL

I get the following output to terminal.

Restoring... !
 !    An error occurred and the backup did not finish.
 !
 !    waiting for restore to complete
 !    pg_restore finished with errors
 !    waiting for download to complete
 !    download finished with errors
 !    please check the source URL and ensure it is publicly accessible
 !
 !    Run heroku pg:backups:info r001 for more details.
'X-Amz-Credential' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Date' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Expires' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-SignedHeaders' is not recognized as an internal or external command,
operable program or batch file.
'X-Amz-Signature' is not recognized as an internal or external command,
operable program or batch file.

which in the log file shows

=== Backup r001
Database:         BACKUP
Started at:       2020-12-08 00:47:33 +0000
Finished at:      2020-12-08 00:47:34 +0000
Status:           Failed
Type:             Manual
Backup Size:      0.00B (0% compression)

=== Backup Logs
2020-12-08 00:47:34 +0000 2020/12/08 00:47:34 aborting: could not write to output stream: Expected HTTP Status 200, received: "400 Bad Request"
2020-12-08 00:47:34 +0000 pg_restore: error: could not read from input file: end of file
2020-12-08 00:47:34 +0000 waiting for restore to complete
2020-12-08 00:47:34 +0000 pg_restore finished with errors
2020-12-08 00:47:34 +0000 waiting for download to complete
2020-12-08 00:47:34 +0000 download finished with errors
2020-12-08 00:47:34 +0000 please check the source URL and ensure it is publicly accessible

Please can someone point where I am going wrong?

Thanks!

Body:
In order to debug this, it might be useful to get the response error message from the request to your AWS url, which you can easily do with curl:

curl <SIGNED AWS URL>

In my case I got the following message:

Error parsing the X-Amz-Credential parameter; the region 'us-east-1' is wrong; expecting 'eu-west-3'

Which means that for some reason AWS is signing my URL with the wrong region. If I try to manually add the right region to my signed url then the request fails because the signatures don't match.

Instead, I need to make AWS sign the URL correctly by specifying the region in the presign command:

aws s3 presign s3://URL --region eu-west-3

when I did this and used the resulting signed url with the heroku pg:backups:restore command, the request was successful and heroku was able to import my db.


问:
Change/Get check state of CheckBox
I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.

JavaScript function

```<code>    function checkAddress()
    {
        if (checkAddress.checked == true)
        {
            alert("a");
        }
    }
</code>```

HTML

```<code><input type="checkbox" name="checkAddress" onchange="checkAddress()" />
</code>```

答:
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:

```<code><td>
    <input type="radio" name="bob" />
</td>
</code>```

You can easily get/set checked state as such:

```<code>$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});
</code>```

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!

Title: Change/Get check state of CheckBox

Body:
I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.

JavaScript function

    function checkAddress()
    {
        if (checkAddress.checked == true)
        {
            alert("a");
        }
    }

HTML

<input type="checkbox" name="checkAddress" onchange="checkAddress()" />

Body:
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:

<td>
    <input type="radio" name="bob" />
</td>

You can easily get/set checked state as such:

$("td").each(function()
{
    $(this).click(function()
    {
        var thisInput  = $(this).find("input[type=radio]");
        var checked = thisInput.is(":checked");
        thisInput[0].checked = (checked) ?  false : true;
    }
});

The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!


问:
Background image does not render on server (nextjs)
I am using NextJs. I want to apply a background image on the body and it should be rendered on the server-side.

Here is my code

Below is my App.js

```<code>import BodyStyle from '@components/Bodystyle';
return (
    <>
      <BodyStyle bgColor={`url("picture-url")`} />
<>);
</code>```

Here is my BodyStyle.js

```<code>const BodyStyle = (props) => {
  const { bgColor } =
    props;
  return (
    <Head>
      <style>{`body { background: ${bgColor} no-repeat center center fixed; background-size: cover;`}</style>
    </Head>
  );
</code>```

The background is applied to the body but not from SSR

But there is a twist if I just copy the code from BodyStyles.js  and paste in app.js the  background image renders fine on the server

Here is the example code of the App.js

```<code>import Head from 'next/head';

return (
  <Head>
        <style>{`body { background: url(${url}) no-repeat center center fixed; background-size: cover;`}</style>
      </Head>
);
</code>```

Attached screenshots
Without background on SSR

With the background on SSR

What could be an issue? Any help

答:
i think its because you use to set bgcolor when there isn't any props yet try using it inside an useEffect or like this code:</p>
```<code>const BodyStyle = ({bgColor}) => {

  return (
    <Head>
      <style>{`body { background: ${bgColor} no-repeat center center fixed; background-size: cover;`}</style>
    </Head>
  );
</code>```

Body:
I am using NextJs. I want to apply a background image on the body and it should be rendered on the server-side.

Here is my code

Below is my App.js

import BodyStyle from '@components/Bodystyle';
return (
    <>
      <BodyStyle bgColor={`url("picture-url")`} />
<>);

Here is my BodyStyle.js

const BodyStyle = (props) => {
  const { bgColor } =
    props;
  return (

  );

The background is applied to the body but not from SSR

But there is a twist if I just copy the code from BodyStyles.js  and paste in app.js the  background image renders fine on the server

Here is the example code of the App.js

import Head from 'next/head';

return (

);

Attached screenshots
Without background on SSR

With the background on SSR

What could be an issue? Any help

Body:
i think its because you use to set bgcolor when there isn't any props yet try using it inside an useEffect or like this code:

const BodyStyle = ({bgColor}) => {

  return (
    <Head>
      <style>{`body { background: ${bgColor} no-repeat center center fixed; background-size: cover;`}</style>
    </Head>
  );