问:
How to debug if app closes without error message?
Im facing an issue that i am unable to debug.

If i open the app, it opens normally and works. But if i launch the app and close the app within 1 second and then launch the app again, it crashes without error message.

How do i debug this as Xcode loses debug connection if i close the app?

I tried putting exception break point but since xcode loses debug connection, it wont trigger.

This ONLY happens when a user does the above mentioned steps (open, close within 2 seconds and open again).

Is there anyway to find out why the app is closing and why there is no error / crash message?

Clarification : The crash happens when user opens the app, within 1 sec terminates the app by manually by swiping up from recents menu and tries to open the app again within 1 or 2 seconds. (Open -> terminate -> open)

答:
Let us imagine that you run the app and quickly force-quit. Then, if you start your second run of the app from the Xcode debugger, hopefully, you should see your crash in Xcode at that point.

If that does not work, you might consider a crash reporting tool (e.g., Crashlytics, etc.). That will help you monitor and track crash reports that happen (for both you and your users) in the wild. If you do this, make sure you test the crash reporting system with some forced crash/report because an absence of a report could just be a result of a misconfiguration, which is easy to do because the setup of these tools takes a little work the first time you do it. Just make sure you have the crash report system working with a positive crash report before you draw any conclusions from an absence of a crash report generated by this particular bug.

That having been said, the way these crash reporting systems often work is they capture the crash and send it the next time you start up the app. It seems like there might be a chance that your particular crash (firing it up after having quickly force-quit it the first time) is happening so fast that the crash reporting system may not have a chance to send off its report of the past crash. (That having been said, these are still invaluable for capturing information about user crashes that happen during the normal use of the app, so I would consider them even if it does not help in this particular scenario.)

So, let’s imagine that you are still unsuccessful in catching your crash for some reason. The last resort is to consider sprinkling your code with Logger/OSLog statements. The nice thing about these logging statements is that you can watch these logging statements on your macOS Console app. See WWDC 2020 Explore logging in Swift.


来源: stackexchange

问:
Reshaping tensor 2d to 1d
```<code>tensor([[17,  0],
        [93,  0],
        [0,  0],
        [21,  0],
        [19,  0])
</code>```

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

```<code>tensor([[17],
        [93],
        [0],
        [21],
        [19])
</code>```

When using the code below, there is a problem that the existing zero disappears.
How should I fix this?

```<code>x = x.flatten()
x = x[x!=0]
x = np.reshape(x, ( -1, x.shape[0] ))
</code>```

array([[17, 93, 21, 19]])

答:
You can use slicing to index the 0 column

```<code>import torch

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(t[:,0])
</code>```

Output

```<code>tensor([17, 93,  0, 21, 19])
</code>```

And if you want to keep it a 2D array then you can use numpy.reshape

```<code>import torch
import numpy as np

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(np.reshape(t[:,0], (-1, 1)))
</code>```

Output

```<code>array([[17],
       [93],
       [ 0],
       [21],
       [19]], dtype=int32)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Reshaping tensor 2d to 1d

Body:
tensor([[17,  0],
        [93,  0],
        [0,  0],
        [21,  0],
        [19,  0])

I want to remove 0 from this tensor, which is a two-dimensional array, and make it a one-dimensional array.

How can I make this tensor with the tensor below?

tensor([[17],
        [93],
        [0],
        [21],
        [19])

When using the code below, there is a problem that the existing zero disappears.
How should I fix this?

x = x.flatten()
x = x[x!=0]
x = np.reshape(x, ( -1, x.shape[0] ))

array([[17, 93, 21, 19]])

Body:
You can use slicing to index the 0 column

import torch

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(t[:,0])

Output

tensor([17, 93,  0, 21, 19])

And if you want to keep it a 2D array then you can use numpy.reshape

import torch
import numpy as np

t = torch.tensor(
      [[17,  0],
       [93,  0],
       [0,  0],
       [21,  0],
       [19,  0]]
    )

print(np.reshape(t[:,0], (-1, 1)))

Output

array([[17],
       [93],
       [ 0],
       [21],
       [19]], dtype=int32)


问:
What purpose does this index serve after Get-ChildItem?
This PowerShell command line:

```<code>code (Get-ChildItem $Home\.vscode\extensions\ms-vscode.PowerShell-*\examples)[-1]
</code>```

is from the page here: https://code.visualstudio.com/docs/languages/powershell

It opens up the folder in question in VS Code.

What is the purpose of the index [-1] after the GCI?  I tried running the command without any index at all, and VS Code opened up in exact identical layout.

答:
As requested, my comment as answer:

Using array index [-1] returns the last item of that array.

Because of the asteriks in the path (where the version number of the PowerShell extension is), an array of directories is expected.

Perhaps even better would be to use

```<code>@(Get-ChildItem $Home\.vscode\extensions\ms-vscode.PowerShell-*\examples)[-1]
</code>```

where the @() forces the result to be an array, even if only one directory is found.

For more array indexing possibilities, please follow the link in zett42's comment

Body:
This PowerShell command line:

code (Get-ChildItem $Home\.vscode\extensions\ms-vscode.PowerShell-*\examples)[-1]

is from the page here: https://code.visualstudio.com/docs/languages/powershell

It opens up the folder in question in VS Code.

What is the purpose of the index [-1] after the GCI?  I tried running the command without any index at all, and VS Code opened up in exact identical layout.

Body:
As requested, my comment as answer:

Using array index [-1] returns the last item of that array.

Because of the asteriks in the path (where the version number of the PowerShell extension is), an array of directories is expected.

Perhaps even better would be to use

@(Get-ChildItem $Home\.vscode\extensions\ms-vscode.PowerShell-*\examples)[-1]

where the @() forces the result to be an array, even if only one directory is found.

For more array indexing possibilities, please follow the link in zett42's comment


问:
Turbolinks to Turbo upgrade has broken form redirection
I'm attempting to upgrade to Turbo from Turbolinks and I've found that the client is not rendering redirects for form submissions.

Versions:

rails 6.1.4

hotwire-rails 0.1.2

@hotwired/turbo-rails 7.0.0-beta.8

I've ignored the incompatibility between Turbo and Devise for now - just trying to get regular forms working without having to disable Turbo on them.

Here's an example action:

def update
  authorize @label
  @label.update(label_params)
  if @label.save
    redirect_to document_labels_path(document_id: @document.id)
  else
    render :new, status: :unprocessable_entity
  end
end
```
<p>Here's a rendered form:</p>
<pre class="lang-html prettyprint-override"><code><form class="simple_form new_label" id="label_form" novalidate="novalidate" action="/documents/72/labels" accept-charset="UTF-8" method="post">
...
</form>
</code>```

When submitting a valid form, the server will say Processing by LabelsController#create as TURBO_STREAM and correctly serve a 302. It will then serve the 200 for the redirect location. The browser however is left just looking at the submitted form. Changing the redirect status to 303 doesn't change anything.

I added a console.log for every Turbo event:

document.addEventListener("turbo:load", function () {
  console.log('TURBO:LOAD')
})
document.addEventListener("turbo:click", function () {
  console.log('TURBO:CLICK')
})
document.addEventListener("turbo:before-visit", function () {
  console.log('TURBO:BEFORE-VISIT')
})
document.addEventListener("turbo:visit", function () {
  console.log('TURBO:VISIT')
})
document.addEventListener("turbo:submit-start", function () {
  console.log('TURBO:SUBMIT-START')
})
document.addEventListener("turbo:before-fetch-request", function () {
  console.log('TURBO:BEFORE-FETCH-REQUEST')
})
document.addEventListener("turbo:before-fetch-response", function () {
  console.log('TURBO:BEFORE-FETCH-RESPONSE')
})
document.addEventListener("turbo:submit-end", function (event) {
  console.log('TURBO:SUBMIT-END')
  // event.detail
})
document.addEventListener("turbo:before-cache", function () {
  console.log('TURBO:BEFORE-CACHE')
})
document.addEventListener("turbo:before-stream-render", function () {
  console.log('TURBO:BEFORE-STREAM-RENDER')
})
document.addEventListener("turbo:render", function () {
  console.log('TURBO:RENDER')
})
```
<p>This is what the output is for a successful form submission:</p>
```TURBO:BEFORE-FETCH-REQUEST
TURBO:SUBMIT-START
TURBO:BEFORE-FETCH-RESPONSE
TURBO:SUBMIT-END
```
<p>There is no render event. Investigating <code>event.detail.fetchResponse.response</code> for <code>turbo:submit-end</code> it seems to be perfectly aware that the client should redirect, it just didn't.</p>
```Response {type: "basic", url: "http://lvh.me:3000/documents/72/labels", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: "OK"
type: "basic"
url: "http://lvh.me:3000/documents/72/labels"
__proto__: Response
```

Update: It is actually performing the redirect and the server is generating the response. The issue is that the client is not rendering the redirect response.

答:
Adding to the excellent answer of Jeff Seifert.

If you don't need turbo streams, you may also unregister the turbo-stream content type altogether by putting this into an initializer e.g. config/initializers/turbo.rb:

```<code>Rails.application.config.after_initialize do
  Mime::Type.unregister(:turbo_stream)
end
</code>```

Body:
I'm attempting to upgrade to Turbo from Turbolinks and I've found that the client is not rendering redirects for form submissions.

Versions:

rails 6.1.4

hotwire-rails 0.1.2

@hotwired/turbo-rails 7.0.0-beta.8

I've ignored the incompatibility between Turbo and Devise for now - just trying to get regular forms working without having to disable Turbo on them.

Here's an example action:

def update
  authorize @label
  @label.update(label_params)
  if @label.save
    redirect_to document_labels_path(document_id: @document.id)
  else
    render :new, status: :unprocessable_entity
  end
end

Here's a rendered form:

<form class="simple_form new_label" id="label_form" novalidate="novalidate" action="/documents/72/labels" accept-charset="UTF-8" method="post">
...
</form>

When submitting a valid form, the server will say Processing by LabelsController#create as TURBO_STREAM and correctly serve a 302. It will then serve the 200 for the redirect location. The browser however is left just looking at the submitted form. Changing the redirect status to 303 doesn't change anything.

I added a console.log for every Turbo event:

document.addEventListener("turbo:load", function () {
  console.log('TURBO:LOAD')
})
document.addEventListener("turbo:click", function () {
  console.log('TURBO:CLICK')
})
document.addEventListener("turbo:before-visit", function () {
  console.log('TURBO:BEFORE-VISIT')
})
document.addEventListener("turbo:visit", function () {
  console.log('TURBO:VISIT')
})
document.addEventListener("turbo:submit-start", function () {
  console.log('TURBO:SUBMIT-START')
})
document.addEventListener("turbo:before-fetch-request", function () {
  console.log('TURBO:BEFORE-FETCH-REQUEST')
})
document.addEventListener("turbo:before-fetch-response", function () {
  console.log('TURBO:BEFORE-FETCH-RESPONSE')
})
document.addEventListener("turbo:submit-end", function (event) {
  console.log('TURBO:SUBMIT-END')
  // event.detail
})
document.addEventListener("turbo:before-cache", function () {
  console.log('TURBO:BEFORE-CACHE')
})
document.addEventListener("turbo:before-stream-render", function () {
  console.log('TURBO:BEFORE-STREAM-RENDER')
})
document.addEventListener("turbo:render", function () {
  console.log('TURBO:RENDER')
})

This is what the output is for a successful form submission:

TURBO:BEFORE-FETCH-REQUEST
TURBO:SUBMIT-START
TURBO:BEFORE-FETCH-RESPONSE
TURBO:SUBMIT-END

There is no render event. Investigating event.detail.fetchResponse.response for turbo:submit-end it seems to be perfectly aware that the client should redirect, it just didn't.

Response {type: "basic", url: "http://lvh.me:3000/documents/72/labels", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: "OK"
type: "basic"
url: "http://lvh.me:3000/documents/72/labels"
__proto__: Response

Update: It is actually performing the redirect and the server is generating the response. The issue is that the client is not rendering the redirect response.

Body:
Adding to the excellent answer of Jeff Seifert.

If you don't need turbo streams, you may also unregister the turbo-stream content type altogether by putting this into an initializer e.g. config/initializers/turbo.rb:

Rails.application.config.after_initialize do
  Mime::Type.unregister(:turbo_stream)
end


问:
Are these 2 Java exam questions incorrect?
I recently did an exam related to Java that had 2 questions that in my opinion were wrong. I was hoping some of you could help me out.

The questions are:

1)

```<code>public class Cell {
    public Cell(){
    }
    public char content; //The character in this cell.
    public Cell next;  // Pointer to the cell to the right of this one.
    public Cell prev;  // Pointer to the cell to the left of this one.
}

// The following method is supposed to move one node to the right in a
// doubly linked list of Cells but it contains a flaw.
// The global variable 'currentCell' is a pointer to a Cell in the list.

public void moveRight(){
    if (currentCell.next == null){
        Cell newCell = new Cell();
        newCell.content = '';
        newCell.next = null;
        newCell.prev = currentCell;
        currentCell.next = newCell;
        currentCell = currentCell.next;
     }
 }
</code>```

True or False: If 'currentCell' is at the head of the list this moveRight()
method will perform its duties correctly.

For me, this question is False, as the moveRight method will not do anything because currentCell.next is NOT null when the pointer is at the head of the list. Its duties (move to the right) will not be successful.
I would like to know what the community thinks, because according to the exam this should be True?

2.

True or False: An interface contains method declarations as well as implementations.

I believe this should be True. As stated by Oracle (2021), “An interface declaration can contain method signatures, default methods, static methods, and constant definitions. The only methods that have implementations are default and static methods.”

Yet, the exam stated that the correct answer is False.

I hope someone could clarify this further for me.

Thank you!

答:
Can conclude that the questions are not clear and shouldn't be the standard for an exam.
Question 1 is vague and its unclear what is meant exactly.
For question 2 it is safe to state that since 2014 the correct answer should be True.

I thank you for your help.

Body:
I recently did an exam related to Java that had 2 questions that in my opinion were wrong. I was hoping some of you could help me out.

The questions are:

1)

public class Cell {
    public Cell(){
    }
    public char content; //The character in this cell.
    public Cell next;  // Pointer to the cell to the right of this one.
    public Cell prev;  // Pointer to the cell to the left of this one.
}

// The following method is supposed to move one node to the right in a
// doubly linked list of Cells but it contains a flaw.
// The global variable 'currentCell' is a pointer to a Cell in the list.

public void moveRight(){
    if (currentCell.next == null){
        Cell newCell = new Cell();
        newCell.content = '';
        newCell.next = null;
        newCell.prev = currentCell;
        currentCell.next = newCell;
        currentCell = currentCell.next;
     }
 }

True or False: If 'currentCell' is at the head of the list this moveRight()
method will perform its duties correctly.

For me, this question is False, as the moveRight method will not do anything because currentCell.next is NOT null when the pointer is at the head of the list. Its duties (move to the right) will not be successful.
I would like to know what the community thinks, because according to the exam this should be True?

2.

True or False: An interface contains method declarations as well as implementations.

I believe this should be True. As stated by Oracle (2021), “An interface declaration can contain method signatures, default methods, static methods, and constant definitions. The only methods that have implementations are default and static methods.”

Yet, the exam stated that the correct answer is False.

I hope someone could clarify this further for me.

Thank you!


问:
React: check the pressed key on form submit
I am using React (and Material UI), and I am trying to submit a form. As default by pressing enter when focused on the text field, the form submits. I want it to only happen when I press the Submit button.

The form

```<code><Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
    <TextField
        margin="normal"
        required
        fullWidth
        id="title"
        label="Title"
        name="title"
        autoComplete="title"
        autoFocus
        defaultValue={title}
    />
    <TextArea setData={setData} data={JSON.parse(description)} />
    <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
    >
        Finish
    </Button>
    <Link href="/">
        Back
    </Link>
</Box>
</code>```

The submit function

```<code> const handleSubmit = async (e) =>
    {
        e.preventDefault();
        console.log(e)
        //
    }

</code>```

答:
I just added onKeyPress to the TextField and checked if the pressed key is equal to Enter

```<code><TextField
    margin="normal"
    required
    fullWidth
    id="title"
    label="Title"
    name="title"
    autoComplete="title"
    onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }} //<----
    autoFocus
/>
</code>```

Body:
I am using React (and Material UI), and I am trying to submit a form. As default by pressing enter when focused on the text field, the form submits. I want it to only happen when I press the Submit button.

The form

<Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}>
    <TextField
        margin="normal"
        required
        fullWidth
        id="title"
        label="Title"
        name="title"
        autoComplete="title"
        autoFocus
        defaultValue={title}
    />
    <TextArea setData={setData} data={JSON.parse(description)} />
    <Button
        type="submit"
        fullWidth
        variant="contained"
        sx={{ mt: 3, mb: 2 }}
    >
        Finish
    </Button>
    <Link href="/">
        Back
    </Link>
</Box>

The submit function

 const handleSubmit = async (e) =>
    {
        e.preventDefault();
        console.log(e)
        //
    }

Body:
I just added onKeyPress to the TextField and checked if the pressed key is equal to Enter

<TextField
    margin="normal"
    required
    fullWidth
    id="title"
    label="Title"
    name="title"
    autoComplete="title"
    onKeyPress={(e) => { e.key === 'Enter' && e.preventDefault(); }} //<----
    autoFocus
/>


问:
Data types and data type affinity in SQLite?
The SQLite3 documentation on data types makes it clear that SQLite does not enforce column data types. Rather a data type "affinity" is defined which is the recommended data type for the column. The recommendation is not a requirement as in other database systems, and the column can store data in any type.

Am looking for a programmatic way to access the affinity for a column (i.e. what SQLite interpreted as the data type hint from the CREATE TABLE statement).

Sample C# code using the wrapper System.Data.SQLite.dll in Visual Studio 2019 on this table:

```<code>-- SQL CREATE TABLE
CREATE TABLE "MyTable" (
    "txt_Text"  TEXT,
    "txt_Text20"    TEXT(20),
    "txt_Memo"  MEMO,
    "num_Int"   INTEGER,
    "num_Bit"   BIT,
    "num_Bool"  BOOLEAN,
    "num_Byte"  BYTE,
    "float_Single"  FLOAT,
    "float_Double"  DOUBLE,
    "float_Decimal" DECIMAL,
    "float_Currency"    CURRENCY,
    "date_Date" DATE,
    "date_DateTime" DATETIME,
    "random"    fronk
)

// C# sample code
string[] columnRestrictions = new string[4];
columnRestrictions[2] = "MyTable";
DataTable schemaColumns =
    ((DbConnection)connection).GetSchema("Columns", columnRestrictions);
if (schemaColumns.Rows.Count > 0)
{
    string typeNameSQLite;
    string typeNameEntity;
    foreach (DataRow row in schemaColumns.Rows)
    {
        typeNameSQLite = (string)row["DATA_TYPE"];
        typeNameEntity = (string)row["EDM_TYPE"];
        // These would be saved in a List<string>...
    }
}

// Results
COLUMN NAME         CREATE      ASSUMED AFFINITY(1)     DATA_TYPE(2)    EDM_TYPE(2)
txt_Text            TEXT        TEXT                    text            nvarchar
txt_Text20          TEXT(20)    TEXT                    text            nvarchar
txt_Memo            MEMO        NUMERIC                 memo            nvarchar
num_Int             INTEGER     INTEGER                 integer         integer
num_Bit             BIT         NUMERIC                 bit             bit
num_Bool            BOOLEAN     NUMERIC                 boolean         bit
num_Byte            BYTE        NUMERIC                 byte            (blank)
float_Single        FLOAT       REAL                    float           real
float_Double        DOUBLE      REAL                    double          real
float_Decimal       DECIMAL     NUMERIC                 decimal         decimal
float_Currency      CURRENCY    NUMERIC                 currency        decimal
date_Date           DATE        NUMERIC                 date            datetime
date_DateTime       DATETIME    NUMERIC                 datetime        datetime
random              fronk       NUMERIC                 fronk           (blank)

Notes:
(1) Assumed affinity derived from [the SQLite3 documentation][2]
(2) "DATA_TYPE" and "EDM_TYPE" values taken directly from the "Columns" schema
</code>```

The examples given in the SQLite documentation do not mention the "MEMO" or "BIT" types, though they appear to have been processed. Also, why is the type fronk understood at all?

How do you reliably access data types and the internal storage class affinity in SQLite using code?

UPDATE

@DinoCoderSaurus provided a useful comment: Run the query SELECT typeof(field_name) FROM table_name; and process the rows. This shows the storage class SQLite used to actually save the data. For example:

```<code>+-----------------+
| typeof(num_Int) |
+-----------------+
| null            |
| integer         |
+-----------------+
</code>```

This is helpful, but is the answer to a different question. I'm trying to confirm what internal data type affinity SQLite determined for the column from the TABLE CREATE statement (e.g. before any data is put into the table).

答:
By following the rules described in Determination Of Column Affinity, I created a query that returns the affinities of all columns in a table:

```<code>SELECT cid, name, type,
       CASE
         WHEN type LIKE '%INT%' THEN 'INTEGER'
         WHEN (type LIKE '%CHAR%') OR (type LIKE '%CLOB%') OR (type LIKE '%TEXT%') THEN 'TEXT'
         WHEN (type LIKE '%BLOB%') OR (type = '') THEN 'BLOB'
         WHEN (type LIKE '%REAL%') OR (type LIKE '%FLOA%') OR (type LIKE '%DOUB%') THEN 'REAL'
         ELSE 'NUMERIC'
       END affinity
FROM pragma_table_info('MyTable');
</code>```

See the demo.

You can use it as it is, or apply its logic with the use of a programming language of your choice.

Body:
The SQLite3 documentation on data types makes it clear that SQLite does not enforce column data types. Rather a data type "affinity" is defined which is the recommended data type for the column. The recommendation is not a requirement as in other database systems, and the column can store data in any type.

Am looking for a programmatic way to access the affinity for a column (i.e. what SQLite interpreted as the data type hint from the CREATE TABLE statement).

Sample C# code using the wrapper System.Data.SQLite.dll in Visual Studio 2019 on this table:

-- SQL CREATE TABLE
CREATE TABLE "MyTable" (
    "txt_Text"  TEXT,
    "txt_Text20"    TEXT(20),
    "txt_Memo"  MEMO,
    "num_Int"   INTEGER,
    "num_Bit"   BIT,
    "num_Bool"  BOOLEAN,
    "num_Byte"  BYTE,
    "float_Single"  FLOAT,
    "float_Double"  DOUBLE,
    "float_Decimal" DECIMAL,
    "float_Currency"    CURRENCY,
    "date_Date" DATE,
    "date_DateTime" DATETIME,
    "random"    fronk
)

// C# sample code
string[] columnRestrictions = new string[4];
columnRestrictions[2] = "MyTable";
DataTable schemaColumns =
    ((DbConnection)connection).GetSchema("Columns", columnRestrictions);
if (schemaColumns.Rows.Count > 0)
{
    string typeNameSQLite;
    string typeNameEntity;
    foreach (DataRow row in schemaColumns.Rows)
    {
        typeNameSQLite = (string)row["DATA_TYPE"];
        typeNameEntity = (string)row["EDM_TYPE"];
        // These would be saved in a List<string>...
    }
}

// Results
COLUMN NAME         CREATE      ASSUMED AFFINITY(1)     DATA_TYPE(2)    EDM_TYPE(2)
txt_Text            TEXT        TEXT                    text            nvarchar
txt_Text20          TEXT(20)    TEXT                    text            nvarchar
txt_Memo            MEMO        NUMERIC                 memo            nvarchar
num_Int             INTEGER     INTEGER                 integer         integer
num_Bit             BIT         NUMERIC                 bit             bit
num_Bool            BOOLEAN     NUMERIC                 boolean         bit
num_Byte            BYTE        NUMERIC                 byte            (blank)
float_Single        FLOAT       REAL                    float           real
float_Double        DOUBLE      REAL                    double          real
float_Decimal       DECIMAL     NUMERIC                 decimal         decimal
float_Currency      CURRENCY    NUMERIC                 currency        decimal
date_Date           DATE        NUMERIC                 date            datetime
date_DateTime       DATETIME    NUMERIC                 datetime        datetime
random              fronk       NUMERIC                 fronk           (blank)

Notes:
(1) Assumed affinity derived from [the SQLite3 documentation][2]
(2) "DATA_TYPE" and "EDM_TYPE" values taken directly from the "Columns" schema

The examples given in the SQLite documentation do not mention the "MEMO" or "BIT" types, though they appear to have been processed. Also, why is the type fronk understood at all?

How do you reliably access data types and the internal storage class affinity in SQLite using code?

UPDATE

@DinoCoderSaurus provided a useful comment: Run the query SELECT typeof(field_name) FROM table_name; and process the rows. This shows the storage class SQLite used to actually save the data. For example:

+-----------------+
| typeof(num_Int) |
+-----------------+
| null            |
| integer         |
+-----------------+

This is helpful, but is the answer to a different question. I'm trying to confirm what internal data type affinity SQLite determined for the column from the TABLE CREATE statement (e.g. before any data is put into the table).

Body:
By following the rules described in Determination Of Column Affinity, I created a query that returns the affinities of all columns in a table:

SELECT cid, name, type,
       CASE
         WHEN type LIKE '%INT%' THEN 'INTEGER'
         WHEN (type LIKE '%CHAR%') OR (type LIKE '%CLOB%') OR (type LIKE '%TEXT%') THEN 'TEXT'
         WHEN (type LIKE '%BLOB%') OR (type = '') THEN 'BLOB'
         WHEN (type LIKE '%REAL%') OR (type LIKE '%FLOA%') OR (type LIKE '%DOUB%') THEN 'REAL'
         ELSE 'NUMERIC'
       END affinity
FROM pragma_table_info('MyTable');

See the demo.

You can use it as it is, or apply its logic with the use of a programming language of your choice.


问:
how concurrency works in flask and is handled by whom?
I have a time-consuming task in route /fibo and a route /home that return hello.

```<code>from flask import Flask, request
from fibo import fib_t
from datetime import datetime

app = Flask(__name__)

@app.route('/home')
def hello():
    return 'hello '

@app.route('/fibo')
def cal_fibo():
    request_rec_t = datetime.now().strftime("%M:%S")
    v, duretion = fib_t(37)
    return f'''
    <div><h1>request recieved by server:</h1>
    <p>{request_rec_t}</p>
    <p>
    <ul>
    <li><b>calculated value</b>:{v}</li>
    <li><b>that takes</b>: {duretion} seconds</li>
    <ul>
    </p>
    </div>
    <div>
    <h1>resonse send by server:</h1>
    <p>{datetime.now().strftime("%M:%S")}</p>
    </div>'''

if __name__ == '__main__':
    app.run(debug=True)
</code>```

the fibo module

```<code>import time

def fib(a):
    if a == 1 or a==2:
        return 1
    else:
        return fib(a-1) + fib(a-2)

def fib_t(a):
    t = time.time()
    v = fib(a)
    return v, f'{time.time()-t:.2f}'
</code>```

if I made two requests to /fibo the second one will start running after the first one finishes his work.
but if I send a request to the time-consuming task and another one to /home I will receive the /home route response immediately while still first request isn't resolved.
if this is matters, I make the requests from different tabs of the browser.

for example, if I request /fibo in two different tabs. the page starts to load. the captured time for the first request is 10:10 and 10:20(the execution of Fibonacci number is tasked 10 seconds) during this request to be finished, the second tab still is loading. after that the second request is finished i see that the process started at the 10:20(the time that first request finishes process) and finished in 10:29(the execution of  Fibonacci number is tasked 9 seconds).
but if I request /home while the /fibo in the first tab isn't returned, I will get the response.

why this is happening?
my general question is how and by whom the multiple requests are being handled?
how can I log the time requests reached the server?

EDIT:
if I add another route fibo2 with the same logic as cal_fibo view function, now I can run them concurrently(like /fibo and /home that I showed that are running concurrently, /fibo and /fibo2 are also running concurrently.)

EDIT 2:
as shown in the image, the second request was sent after the first request's response was received. why and how did this has happened?
(the related TCP handshake of each request has happened close to each other but how and who managed that the related HTTP get request is sent after the first request's response received?)

答:
actually you have only one process running with only one thread all the time to enable threading and running more than one process this depends on the context (development or production) .

for development purposes

to enable threading you need to run

```<code>app.run(host="your.host", port=4321, threaded=True)
</code>```

also to enable running more  than one process e.g. 3 according to documentation
you need to run the following line

```<code>app.run(host="your.host", port=4321, processes=3)
</code>```

for production purposes

when you run the app in production environment it is the responsability of the WSGI gateway (eg. gunicorn) that you configure on the cloud provider like heroku or aws to support the handling of multiple requests.

we use this method in production as it is more robust to crashes and also more efficent.

this was just a summary of the answers in this question

Body:
I have a time-consuming task in route /fibo and a route /home that return hello.

from flask import Flask, request
from fibo import fib_t
from datetime import datetime

app = Flask(__name__)

@app.route('/home')
def hello():
    return 'hello '

@app.route('/fibo')
def cal_fibo():
    request_rec_t = datetime.now().strftime("%M:%S")
    v, duretion = fib_t(37)
    return f'''

request recieved by server:

{request_rec_t}

calculated value:{v}

that takes: {duretion} seconds

resonse send by server:

{datetime.now().strftime("%M:%S")}

'''

if __name__ == '__main__':
    app.run(debug=True)

the fibo module

import time

def fib(a):
    if a == 1 or a==2:
        return 1
    else:
        return fib(a-1) + fib(a-2)

def fib_t(a):
    t = time.time()
    v = fib(a)
    return v, f'{time.time()-t:.2f}'

if I made two requests to /fibo the second one will start running after the first one finishes his work.
but if I send a request to the time-consuming task and another one to /home I will receive the /home route response immediately while still first request isn't resolved.
if this is matters, I make the requests from different tabs of the browser.

for example, if I request /fibo in two different tabs. the page starts to load. the captured time for the first request is 10:10 and 10:20(the execution of Fibonacci number is tasked 10 seconds) during this request to be finished, the second tab still is loading. after that the second request is finished i see that the process started at the 10:20(the time that first request finishes process) and finished in 10:29(the execution of  Fibonacci number is tasked 9 seconds).
but if I request /home while the /fibo in the first tab isn't returned, I will get the response.

why this is happening?
my general question is how and by whom the multiple requests are being handled?
how can I log the time requests reached the server?

EDIT:
if I add another route fibo2 with the same logic as cal_fibo view function, now I can run them concurrently(like /fibo and /home that I showed that are running concurrently, /fibo and /fibo2 are also running concurrently.)

EDIT 2:
as shown in the image, the second request was sent after the first request's response was received. why and how did this has happened?
(the related TCP handshake of each request has happened close to each other but how and who managed that the related HTTP get request is sent after the first request's response received?)

Body:
actually you have only one process running with only one thread all the time to enable threading and running more than one process this depends on the context (development or production) .

for development purposes

to enable threading you need to run

app.run(host="your.host", port=4321, threaded=True)

also to enable running more  than one process e.g. 3 according to documentation
you need to run the following line

app.run(host="your.host", port=4321, processes=3)

for production purposes

when you run the app in production environment it is the responsability of the WSGI gateway (eg. gunicorn) that you configure on the cloud provider like heroku or aws to support the handling of multiple requests.

we use this method in production as it is more robust to crashes and also more efficent.

this was just a summary of the answers in this question


问:
Generate Random numbers in array, add them together and store the answers in array
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

```<code>randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]
</code>```

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

```<code>public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}
</code>```

答:
Sounds simple enough </p>

```<code>int b = 0;
while ( b < 20 ) {
    answers[b/2] = num[b] + num[b+1];
    b = b + 2;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am new to Java and trying to solve the problem below

So this is my story:
Program generates 20 numbers up to 100 and stores every number in array. Once generated the program has to add two numbers and stores the answer in array.. Example

randomNumber[0]+randomNumber[1]=answer[0]
randomNumber[2]+randomNumber[3]=answer[1]
randomNumber[4]+randomNumber[5]=answer[2]

etc..

Once done I check user input with answers and count the correct answers.

The problem is: I can't figure out how to add two numbers together and store it in Array. It seems easy but I am not experienced enough :)

Currently I am stuck here, I would really appreciate if someone could explain or help me how to solve this problem.

public class gNumber {
    private final int[] num = new int[20]; // array of randomly generated numbers
    private int[] answers; // array of correct answers and UserAnswers
    private final int[] userAnswers = new int[10];
    private int numOfCorrect = 0;

    // Accessor to get the randomly generated number
    int getNumbers(final int n) {
        return num[n];
    }

    int numOfCorrectAnswers() {
        return numOfCorrect;
    }

    // Mutator to store store user input
    void setUsrAnswers(final int _index, final int answer) {
        userAnswers[_index] = answer;
    }

    // Method to generate random 20 numbers
    public void RandomN() {

        for (int i = 0; i < num.length; i++) {
            final int randomNum = (int) (Math.random() * 100);
            num[i] = randomNum;
            final int a = num[i];
            // int b =num[i];
            answers[i] = a + a;
            System.out.println(i + ")" + num[i] + answers[i]);
        }

    }

    // method to add two numbers and store in in answers array
    public void add(int arg1, int arg2) {
        int b = 0;
        while (b < 10) {
            arg1 = num[b];
            arg2 = num[b + 1];
            answers[b] = arg1 + arg2;

            System.out.println(answers[b]);
            b = b + 1;
        }
    }

    // method to check user answers
    public void usrInput(final int usrAnwer) {
        for (final int num : answers) {
            if (num == usrAnwer) {
                numOfCorrect++;
            }
        }

    }
}

Body:
Sounds simple enough

int b = 0;
while ( b < 20 ) {
    answers[b/2] = num[b] + num[b+1];
    b = b + 2;
}


问:
what is the difference between *.extension and .extension?
I am using git and in the .gitignore I found *.local and .DS_Store(mac). what are the differences and (if you know) what are all the possible format for .gitignore?</p>

答:
.name is not a pattern, not an extension, it's a filename. It just happens that the filename starts with a dot.

There is a tradition in Unix to name hidden files with the leading dot. It's only a tradition, it isn't built into OS kernels, but most file managers follow it and hide files with the leading dot from lists by default.

Because of this hidden configuration files are called "dot files".


问:
React Filtering based on user input -State, setState, useState, Hooks
I have a fun project that is filter data using .filter .map etc etc - At the moment I have a select -> option that changes the state of the data presented to the user but I also want to filter based an onChange event but have issues with the whole filter part

https://j121b.csb.app/ is the code sandbox and this is the issue:

Type Error - data.instName.contains is not a function

Could someone look over code and point me in the right direction please? Thank you and happy Friday :)

答: Actually I sorted it - https://j121b.csb.app/ Look at the different states!</p>


问:
I can't add cookies on python selenium webdriver
I'm trying to enter a page and then add cookies on it, but it returns an error and I don't know why. I did it exactly like is written on the selenium docs, and here is the code i used:

```<code>local_path = rf'{os.path.dirname(os.path.realpath(__file__))}\\chromedriver.exe'
driver = webdriver.Chrome(executable_path=local_path)
driver.get('https://example.com/')
driver.add_cookie({'session': 'session token'})
driver.close()
</code>```

And it returns selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: missing 'name'.

I already thought that it could be the code trying to add cookies before the page is totally loaded, but it isn't. I put a time.sleep(30) between get and add_cookie and it returned the same exception.

答:
Actually it was just a wrong usage of add_cookie(). The right way to send cookies is like this:

```<code>driver.addcookie({

    'name': 'session',
    'value': 'token'

})
</code>```

My error was using directly the cookie name + the value, and not with the dict template.

Body:
I'm trying to enter a page and then add cookies on it, but it returns an error and I don't know why. I did it exactly like is written on the selenium docs, and here is the code i used:

local_path = rf'{os.path.dirname(os.path.realpath(__file__))}\\chromedriver.exe'
driver = webdriver.Chrome(executable_path=local_path)
driver.get('https://example.com/')
driver.add_cookie({'session': 'session token'})
driver.close()

And it returns selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: missing 'name'.

I already thought that it could be the code trying to add cookies before the page is totally loaded, but it isn't. I put a time.sleep(30) between get and add_cookie and it returned the same exception.

Body:
Actually it was just a wrong usage of add_cookie(). The right way to send cookies is like this:

driver.addcookie({

    'name': 'session',
    'value': 'token'

})

My error was using directly the cookie name + the value, and not with the dict template.


问:
Discord.js | How do I make my bot send a random image?
I have tried a bunch of things that I've seen and none of them seem to be working for me. I am using the thing where when you do a command it activates a file in the commands folder, and most of the other scripts dont use that.

答:
Without seeing any code, it is quite difficult to point you in the right direction. It would help more to define the issue you are having (actual errors and/or functionality) along with seeing the code you are using. The solution also depends on where the images are coming from.

Assuming your images are in a local folder, here is a basic example:

```<code>if (message.content === '!random') {
    // get a random index between 0 and length
    const idx = (len) => Math.floor(Math.random() * (len));

    // get all the files in the directory
    const files = fs.readdirSync('/images/');

    // get file from directory
    const myImage = files[idx(files.length)];

    // send image to channel
    message.channel.send({ files: [`/images/${myImage}`] });
}
</code>```

Assuming images are from https://picsum.photos/, here is an basic example:

```<code>if (message.content === '!random') {
    const seed = Math.floor(Math.random() * 1000);
    const h = Math.floor(Math.random() * 400) + 100;
    const w = Math.floor(Math.random() * 400) + 100;

    // create embed with random image
    const embed = new MessageEmbed().setImage(`https://picsum.photos/seed/${seed}/${h}/${w}`);

    // send embed
    message.channel.send({ embeds: [embed] });

    // delete command
    message.delete();
}
</code>```

Body:
Without seeing any code, it is quite difficult to point you in the right direction. It would help more to define the issue you are having (actual errors and/or functionality) along with seeing the code you are using. The solution also depends on where the images are coming from.

Assuming your images are in a local folder, here is a basic example:

if (message.content === '!random') {
    // get a random index between 0 and length
    const idx = (len) => Math.floor(Math.random() * (len));

    // get all the files in the directory
    const files = fs.readdirSync('/images/');

    // get file from directory
    const myImage = files[idx(files.length)];

    // send image to channel
    message.channel.send({ files: [`/images/${myImage}`] });
}

Assuming images are from https://picsum.photos/, here is an basic example:

if (message.content === '!random') {
    const seed = Math.floor(Math.random() * 1000);
    const h = Math.floor(Math.random() * 400) + 100;
    const w = Math.floor(Math.random() * 400) + 100;

    // create embed with random image
    const embed = new MessageEmbed().setImage(`https://picsum.photos/seed/${seed}/${h}/${w}`);

    // send embed
    message.channel.send({ embeds: [embed] });

    // delete command
    message.delete();
}


问:
i want to add next page (every page is 10) to my recyclerview but it delet my last page
my recyclerview fragment:
this is the fragment that I set my recycler view , I want when touch  the continue button (btn_continue) add the rest of the list, which is actually  the next page, to my list when I click the button
But it deletes the previous list and displays the new list
and i use the kotlin coruotine, viewmodel and recyclerview

```<code> class AllUnpublishedAdsFragment : Fragment() {

            lateinit var unpublishedAdsAdapter: UnpublishedAdsAdapter
               var items = ArrayList<M_Ads>()
               lateinit var loadMoreItems: ArrayList<M_Ads>
               lateinit var scrollListener: RecyclerViewLoadMoreScroll
               lateinit var mLayoutManager: RecyclerView.LayoutManager
               val page = "1"
               var newpage = page.toInt()

               var navController: NavController? = null
               lateinit var btn_continue: Button
               private lateinit var viewModel: MainViewmodels
               lateinit var token: String

               override fun onCreateView(
                   inflater: LayoutInflater, container: ViewGroup?,
                   savedInstanceState: Bundle?
               ): View? {
                   // Inflate the layout for this fragment
                   return inflater.inflate(R.layout.fragment_all_unpublished_ads, container,
   false)
               }

               override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                   super.onViewCreated(view, savedInstanceState)
                   btn_continue = view.findViewById<Button>(R.id.btn_continueAds)
                   token = arguments?.getString(TOKEN_KEY).toString()
                   Log.i("TOKEN", token)
                   setupViewModel(token, page)

                   continueAds()

                   unpublishedAdsAdapter.itemClickListener = { item, position ->
                       val id = item.id
                       val bundle_id = Bundle()
                       bundle_id.putString(ID_KEY, id.toString())
                       navController = Navigation.findNavController(view)
                       //view.findNavController().navigate(R.id.action_UnpublishedAds_to_Detail,
   bundle_id)
                       navController!!.navigate(
                           R.id.action_allUnpublishedAdsFragment_to_adsDetailFragment,
                           bundle_id
                       )
                   }
               }

               private fun setupViewModel(token: String, page: String) {
                   LoadingDialog.show(requireContext(), { ld ->
                       recy_unpublished_ads.layoutManager = LinearLayoutManager(activity)
                       val decoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL)
                       recy_unpublished_ads.addItemDecoration(decoration)
                       viewModel = ViewModelProvider(this).get(MainViewmodels::class.java)
                       unpublishedAdsAdapter = UnpublishedAdsAdapter()
                       recy_unpublished_ads.adapter = unpublishedAdsAdapter
                       viewModel.adsListObserve().observe({ lifecycle }, { model ->

                           items.clear()
                           items.addAll(model.adsList!!)
                           unpublishedAdsAdapter.setUpdateData(items)
                           ld.dismiss()
                           btn_continue.visibility = View.VISIBLE
                       })
                       viewModel.getAdsList(token, page)

                   })
               }

                   fun continueAds() {
                   var isTouched=false
                   btn_continue.setOnClickListener {
                       isTouched=true
                       newpage = newpage + 1
                       Log.i("CONTINUE", newpage.toString())
                       setupViewModel(token, newpage.toString())
                       unpublishedAdsAdapter.notifyDataSetChanged()
                       isTouched=false
                   }
               }
</code>```

RetrofitInstance class

```<code>class RetrofitInstance {

    companion object{

        fun getRetrofitInstance (): Retrofit{
//            val interceptor = HttpLoggingInterceptor()
//            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
//            val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
            val okHttpClient: OkHttpClient = OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build()

            return  Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
        }
    }
}
</code>```

my adapter:

```<code>class UnpublishedAdsAdapter : RecyclerView.Adapter<UnpublishedAdsAdapter.MyViewHolder>() {

    var items = ArrayList<M_Ads>()
    var itemClickListener: ((item: M_Ads, position: Int) -> Unit)? = null
    lateinit var mcontext: Context

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    fun setUpdateData(items: ArrayList<M_Ads>) {
        this.items = items
        notifyDataSetChanged()
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val img_ads = view.findViewById<ImageView>(R.id.img_recy_ads)
        val txt_title = view.findViewById<TextView>(R.id.txt_recy_ads_title)
        val txt_accountType = view.findViewById<TextView>(R.id.txt_recy_ads_acctype)
        fun bind(data: M_Ads) {
            txt_title.setText(data.title)
            txt_accountType.setText(data.accountType)
            if (!data.image1.equals("")) {
                Picasso.with(img_ads.context).load(data.image1).into(img_ads)
            } else {
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

        mcontext = parent.context
        return if (viewType == Constant.VIEW_TYPE_ITEM) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.row_recy_unpublished_ads, parent, false)
            MyViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(mcontext).inflate(R.layout.progress_loading, parent, false)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                view.progressbar.indeterminateDrawable.colorFilter =
                    BlendModeColorFilter(Color.WHITE, BlendMode.SRC_ATOP)
            } else {
                view.progressbar.indeterminateDrawable.setColorFilter(
                    Color.WHITE,
                    PorterDuff.Mode.MULTIPLY
                )
            }
            MyViewHolder(view)
        }

    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(items.get(position))
        handleClick(holder)

    }

    fun handleClick(holder: UnpublishedAdsAdapter.MyViewHolder) {
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            itemClickListener?.invoke(items.get(position), position)
        }
    }

    override fun getItemCount(): Int {
        return items.size
    }
</code>```

my Viewmodel:

```<code>class MainViewmodels:ViewModel() {
    lateinit var getAds:MutableLiveData<Main_ModelAds>
    init {
        getAds= MutableLiveData<Main_ModelAds>()
    }
    fun adsListObserve():MutableLiveData<Main_ModelAds>{
        return getAds
    }
    fun getAdsList(token:String,page:String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.i("ERRORRES",token + "")
                val retrofitInstance=RetrofitInstance.getRetrofitInstance().create(RetrofitService::class.java)
                val response=retrofitInstance.unPublishedAdsList(token,page)
                getAds.postValue(response)
            }catch (ex:Exception){
                Log.i("ERRORRES", ex.message.toString() + "")
            }
        }

    }
</code>```

答:
What you want here is to update the list that you are showing when the user clicks the button.
In this case you should use ListAdapter.

You can refer to this article for implementation:
https://developer.android.com/reference/androidx/recyclerview/widget/ListAdapter

Body:
my recyclerview fragment:
this is the fragment that I set my recycler view , I want when touch  the continue button (btn_continue) add the rest of the list, which is actually  the next page, to my list when I click the button
But it deletes the previous list and displays the new list
and i use the kotlin coruotine, viewmodel and recyclerview

 class AllUnpublishedAdsFragment : Fragment() {

            lateinit var unpublishedAdsAdapter: UnpublishedAdsAdapter
               var items = ArrayList<M_Ads>()
               lateinit var loadMoreItems: ArrayList<M_Ads>
               lateinit var scrollListener: RecyclerViewLoadMoreScroll
               lateinit var mLayoutManager: RecyclerView.LayoutManager
               val page = "1"
               var newpage = page.toInt()

               var navController: NavController? = null
               lateinit var btn_continue: Button
               private lateinit var viewModel: MainViewmodels
               lateinit var token: String

               override fun onCreateView(
                   inflater: LayoutInflater, container: ViewGroup?,
                   savedInstanceState: Bundle?
               ): View? {
                   // Inflate the layout for this fragment
                   return inflater.inflate(R.layout.fragment_all_unpublished_ads, container,
   false)
               }

               override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
                   super.onViewCreated(view, savedInstanceState)
                   btn_continue = view.findViewById<Button>(R.id.btn_continueAds)
                   token = arguments?.getString(TOKEN_KEY).toString()
                   Log.i("TOKEN", token)
                   setupViewModel(token, page)

                   continueAds()

                   unpublishedAdsAdapter.itemClickListener = { item, position ->
                       val id = item.id
                       val bundle_id = Bundle()
                       bundle_id.putString(ID_KEY, id.toString())
                       navController = Navigation.findNavController(view)
                       //view.findNavController().navigate(R.id.action_UnpublishedAds_to_Detail,
   bundle_id)
                       navController!!.navigate(
                           R.id.action_allUnpublishedAdsFragment_to_adsDetailFragment,
                           bundle_id
                       )
                   }
               }

               private fun setupViewModel(token: String, page: String) {
                   LoadingDialog.show(requireContext(), { ld ->
                       recy_unpublished_ads.layoutManager = LinearLayoutManager(activity)
                       val decoration = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL)
                       recy_unpublished_ads.addItemDecoration(decoration)
                       viewModel = ViewModelProvider(this).get(MainViewmodels::class.java)
                       unpublishedAdsAdapter = UnpublishedAdsAdapter()
                       recy_unpublished_ads.adapter = unpublishedAdsAdapter
                       viewModel.adsListObserve().observe({ lifecycle }, { model ->

                           items.clear()
                           items.addAll(model.adsList!!)
                           unpublishedAdsAdapter.setUpdateData(items)
                           ld.dismiss()
                           btn_continue.visibility = View.VISIBLE
                       })
                       viewModel.getAdsList(token, page)

                   })
               }

                   fun continueAds() {
                   var isTouched=false
                   btn_continue.setOnClickListener {
                       isTouched=true
                       newpage = newpage + 1
                       Log.i("CONTINUE", newpage.toString())
                       setupViewModel(token, newpage.toString())
                       unpublishedAdsAdapter.notifyDataSetChanged()
                       isTouched=false
                   }
               }

RetrofitInstance class

class RetrofitInstance {

    companion object{

        fun getRetrofitInstance (): Retrofit{
//            val interceptor = HttpLoggingInterceptor()
//            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
//            val client: OkHttpClient = OkHttpClient.Builder().addInterceptor(interceptor).build()
            val okHttpClient: OkHttpClient = OkHttpClient.Builder()
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .build()

            return  Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()
        }
    }
}

my adapter:

class UnpublishedAdsAdapter : RecyclerView.Adapter<UnpublishedAdsAdapter.MyViewHolder>() {

    var items = ArrayList<M_Ads>()
    var itemClickListener: ((item: M_Ads, position: Int) -> Unit)? = null
    lateinit var mcontext: Context

    class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    fun setUpdateData(items: ArrayList<M_Ads>) {
        this.items = items
        notifyDataSetChanged()
    }

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val img_ads = view.findViewById<ImageView>(R.id.img_recy_ads)
        val txt_title = view.findViewById<TextView>(R.id.txt_recy_ads_title)
        val txt_accountType = view.findViewById<TextView>(R.id.txt_recy_ads_acctype)
        fun bind(data: M_Ads) {
            txt_title.setText(data.title)
            txt_accountType.setText(data.accountType)
            if (!data.image1.equals("")) {
                Picasso.with(img_ads.context).load(data.image1).into(img_ads)
            } else {
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {

        mcontext = parent.context
        return if (viewType == Constant.VIEW_TYPE_ITEM) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.row_recy_unpublished_ads, parent, false)
            MyViewHolder(view)
        } else {
            val view =
                LayoutInflater.from(mcontext).inflate(R.layout.progress_loading, parent, false)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                view.progressbar.indeterminateDrawable.colorFilter =
                    BlendModeColorFilter(Color.WHITE, BlendMode.SRC_ATOP)
            } else {
                view.progressbar.indeterminateDrawable.setColorFilter(
                    Color.WHITE,
                    PorterDuff.Mode.MULTIPLY
                )
            }
            MyViewHolder(view)
        }

    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(items.get(position))
        handleClick(holder)

    }

    fun handleClick(holder: UnpublishedAdsAdapter.MyViewHolder) {
        holder.itemView.setOnClickListener {
            val position = holder.adapterPosition
            itemClickListener?.invoke(items.get(position), position)
        }
    }

    override fun getItemCount(): Int {
        return items.size
    }

my Viewmodel:

class MainViewmodels:ViewModel() {
    lateinit var getAds:MutableLiveData<Main_ModelAds>
    init {
        getAds= MutableLiveData<Main_ModelAds>()
    }
    fun adsListObserve():MutableLiveData<Main_ModelAds>{
        return getAds
    }
    fun getAdsList(token:String,page:String){
        viewModelScope.launch(Dispatchers.IO) {
            try {
                Log.i("ERRORRES",token + "")
                val retrofitInstance=RetrofitInstance.getRetrofitInstance().create(RetrofitService::class.java)
                val response=retrofitInstance.unPublishedAdsList(token,page)
                getAds.postValue(response)
            }catch (ex:Exception){
                Log.i("ERRORRES", ex.message.toString() + "")
            }
        }

    }


问:
Hide command prompt in Selenium ChromeDriver
```<code>var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;

var driver = new ChromeDriver(driverService, new ChromeOptions());
</code>```

Is it possible to achieve this in Python? I've tried all the possible fixes posted here on StackoverFlow and outside, but nothing when I run my .exe, the cmd appears too.

Python 3.6, latest Selenium version (3.9).

答:
This feature has been added in python library since selenium4 release! See this answer

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows

# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
chrome_service.creationflags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)
</code>```

Body:
var driverService = ChromeDriverService.CreateDefaultService();
driverService.HideCommandPromptWindow = true;

var driver = new ChromeDriver(driverService, new ChromeOptions());

Is it possible to achieve this in Python? I've tried all the possible fixes posted here on StackoverFlow and outside, but nothing when I run my .exe, the cmd appears too.

Python 3.6, latest Selenium version (3.9).

Body:
This feature has been added in python library since selenium4 release! See this answer

from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService # Similar thing for firefox also!
from subprocess import CREATE_NO_WINDOW # This flag will only be available in windows

# Define your own service object with the `CREATE_NO_WINDOW ` flag
# If chromedriver.exe is not in PATH, then use:
# ChromeService('/path/to/chromedriver')
chrome_service = ChromeService('chromedriver')
chrome_service.creationflags = CREATE_NO_WINDOW

driver = webdriver.Chrome(service=chrome_service)


问:
How do I paste multi-line bash codes into terminal and run it all at once?
I need to paste a multi-line bash code into terminal, but whenever I do, each line gets run as a separate command as soon as it gets pasted.</p>

答:
So I think for very long command (namely compiling a file with llvm!) this has given me the most ease of us over the others Ive tried in the past. I use it all the time to thrash out a command in an editor over multiple lines:

```<code>cat | paste -sd " "  - | xargs echo
</code>```

This will open up cat standard input in the terminal, paste in the code and follow up with ctrl-d (mentioned before this adds a EOF char and ends CAT process). Paste takes in the cat input and scoops up all multi lines into a space char. This will ONLY echo out the command.

To execute the command just add sh to the end:

```<code>cat | paste -sd " "  - | xargs echo | sh
</code>```

Or alternatively I like to make the output an alias command, place in .zshrc

```<code>alias mcmd='cat | paste -sd " "  - | xargs echo'
</code>```

then to execute

```<code>> mcmd | sh
</code>```

this will open cat, paste in your multi line command, ctrl d and will execute the multi lines as a one line command  :)

Example command

```<code>>    mcmd;
# now paste in your long command
> llvm-g++
    main.mm
    -o
    buildApp
    -w
    -g
    -std=c++14
    -L/System/Library/Frameworks/
    -framework
    CoreServices
     # now key press ctrl + d
</code>```

whoop! outputs single line

```<code> llvm-g++ main.mm -o buildApp -w -g -std=c++14 -L/System/Library/Frameworks/ -framework CoreServices
</code>```

Body:
So I think for very long command (namely compiling a file with llvm!) this has given me the most ease of us over the others Ive tried in the past. I use it all the time to thrash out a command in an editor over multiple lines:

cat | paste -sd " "  - | xargs echo

This will open up cat standard input in the terminal, paste in the code and follow up with ctrl-d (mentioned before this adds a EOF char and ends CAT process). Paste takes in the cat input and scoops up all multi lines into a space char. This will ONLY echo out the command.

To execute the command just add sh to the end:

cat | paste -sd " "  - | xargs echo | sh

Or alternatively I like to make the output an alias command, place in .zshrc

alias mcmd='cat | paste -sd " "  - | xargs echo'

then to execute

> mcmd | sh

this will open cat, paste in your multi line command, ctrl d and will execute the multi lines as a one line command  :)

Example command

>    mcmd;
# now paste in your long command
> llvm-g++
    main.mm
    -o
    buildApp
    -w
    -g
    -std=c++14
    -L/System/Library/Frameworks/
    -framework
    CoreServices
     # now key press ctrl + d

whoop! outputs single line

 llvm-g++ main.mm -o buildApp -w -g -std=c++14 -L/System/Library/Frameworks/ -framework CoreServices


问:
How to clear Nx cache
I have an Nx monorepo (https://nx.dev).
It has a folder with Nx cache (./node_modules/.cache/nx/).
Its size for now is over 3GB.

Is there a command for clear this cache?

答:
This works in the latest version as of today (February 12, 2022). I am uncertain why this is no longer in the CLI documentation despite evidence of it being there in the past: https://nx.dev/cli/clear-cache

nx clear-cache

Title: How to clear Nx cache


问:
convert mp4 to webp without quality loss (ffmpeg)
How can I do that?

```<code>ffmpeg -y -i input.mp4 -vcodec libwebp -lossless 0 -compression_level 0 -loop 0 output_lossless0_comp0.webp
</code>```

and

```<code>ffmpeg -i input.mp4 -vcodec libwebp -filter:v fps=fps=20 -lossless 0  -compression_level 3 -q:v 70 -loop 1 -preset picture -an -vsync 0 -s 800:600 output.webp
</code>```

lead to substantial quality loss.

All other command lines i found elsewhere lead to infinite encoding times and absurd file sizes (500+ MB when the source is 3 MB).

All i need is to convert mp4 to webp without compression or quality loss.

答:
Only -c:v copy option can guarantee similar size of the output with no loss in quality, but webp does not support mp4 codecs so you need to use "some" encoder and any encoder will lead you to a loss in quality or much bigger size of the output file (it's a tradeoff).

If you use libwebp (documentation) then you will need to experiment with the different values of its parameters to get the result that will be good for you in terms of size, quality and time.

I would start any tests with -lossless 0 or -lossless 1 together with a different values for -compression_level parameter:

For lossy, this is a quality/speed tradeoff. Higher values give better
quality for a given size at the cost of increased encoding time. For
lossless, this is a size/speed tradeoff. Higher values give smaller
size at the cost of increased encoding time. More specifically, it
controls the number of extra algorithms and compression tools used,
and varies the combination of these tools. This maps to the method
option in libwebp. The valid range is 0 to 6. Default is 4.

Body:
How can I do that?

ffmpeg -y -i input.mp4 -vcodec libwebp -lossless 0 -compression_level 0 -loop 0 output_lossless0_comp0.webp

and

ffmpeg -i input.mp4 -vcodec libwebp -filter:v fps=fps=20 -lossless 0  -compression_level 3 -q:v 70 -loop 1 -preset picture -an -vsync 0 -s 800:600 output.webp

lead to substantial quality loss.

All other command lines i found elsewhere lead to infinite encoding times and absurd file sizes (500+ MB when the source is 3 MB).

All i need is to convert mp4 to webp without compression or quality loss.


问:
Docker cannot start on Windows
Executing docker version command on Windows returns the following results:

```<code>C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
</code>```

Running the diagnostics produces the following:

```<code>C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at <ScriptBlock>, <No file>: line 27
 [+] Service is running 127ms
 [+] Docker.exe is in path 2.14s
Describing User has permissions to use Docker daemon
 [+] docker.exe should not return access denied 42ms
Describing Windows container settings are correct
 [-] Do not have DisableVSmbOplock set to 1 53ms
   Expected: {0}
   But was:  {1}
   66:              $regvalue.VSmbDisableOplocks | Should Be 0
   at <ScriptBlock>, <No file>: line 66
 [+] Do not have zz values set 42ms
Describing The right container base images are installed
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/images/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.
 [-] At least one of 'microsoft/windowsservercore' or 'microsoft/nanoserver' should be installed 129ms
   ValidationMetadataException: The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   ParameterBindingValidationException: Cannot validate argument on parameter 'Property'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
   at <ScriptBlock>, <No file>: line 90
Describing Container network is created
 [-] Error occurred in Describe block 1.08s
   RuntimeException: Cannot index into a null array.
   at <ScriptBlock>, <No file>: line 119
Showing output from: docker info

Showing output from: docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64

Showing output from: docker network ls

Warnings & errors from the last 24 hours
Logs saved to C:\Projects\logs_20161107-084122.csv
C:\Projects>
</code>```

答:
First, I downloaded docker for windows 10, OS Built 19042 and version 20H2, as shown in this video,
but my docker was at the beginning stage. I run the docker with the command provided, but I got such an
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.24/version: open //./pipe/docker_engine: The system cannot find the file

Then, these solutions worked for me to start the docker:

Open Powershell as administrator &
run this command: 'C:\Program Files\Docker\Docker\DockerCli.exe' -SwitchDaemon

OR

Open cmd as administrator &
run this command: "C:\Program Files\Docker\Docker\DockerCli.exe" -SwitchDaemon

I found this from here. Hope this helps you too!

Title: Docker cannot start on Windows

Body:
Executing docker version command on Windows returns the following results:

C:\Projects> docker version
Client:
 Version:      1.13.0-dev
 API version:  1.25
 Go version:   go1.7.3
 Git commit:   d8d3314
 Built:        Tue Nov  1 03:05:34 2016
 OS/Arch:      windows/amd64
error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.25/version: open //./pipe/docker_engine: The system cannot find the file
specified. In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also indicate that the docker daemon is not running.

Running the diagnostics produces the following:

C:\Projects> wget https://github.com/Microsoft/Virtualization-
Documentation/raw/master/windows-server-container-tools/Debug-
ContainerHost/Debug-ContainerHost.ps1 -UseBasicParsin | iex

Checking for common problems
Describing Windows Version and Prerequisites
 [+] Is Windows 10 Anniversary Update or Windows Server 2016 608ms
 [+] Has KB3192366, KB3194496, or later installed if running Windows build 14393 141ms
 [+] Is not a build with blocking issues 29ms
Describing Docker is installed
 [-] A Docker service is installed - 'Docker' or 'com.Docker.Service'  134ms
   Expected: value to not be empty
   27:         $services | Should Not BeNullOrEmpty
   at


问:
division by zero warning in numpy despite there being no zeros to divide in a function for finding inverse matrix
I am making a function for a matrix class for finding the inverse matrix using gaussian elimination, The function works fine most of the time it would have random warnings that come in pairs that look like this

```<code>RuntimeWarning: invalid value encountered in double_scalars
RuntimeWarning: divide by zero encountered in double_scalars
</code>```

The problem comes for the lines where I divide everything in the same row by a constant. However, the first part of the function already makes sure the all the pivot elements in the matrix would not be zero. I have also ran a lot of tests and the problem isn't coming from the pivot elements being zero, the pivot elements are the only elements used for division, so I don't understand where the error is coming from

```<code>def inverse(self):
        if self.row != self.col:
            raise ValueError("Inverse Matrices only possible with square matrices")
        det = self.determinant()
        if det == 0:
            raise ValueError("The provided matrix does not have an Inverse")

        # Makes sure that the pivot elements are not zero
        inverse = Matrix.identity(self.row)
        placeHolder = [[self.matrix[i, j] for j in range(self.col)] for i in range(self.row)]
        for i in range(self.col):
            if self.matrix[i, i] == 0:
                for j in range(self.row):
                    if self.matrix[j, i] != 0:
                        for k in range(self.col):
                            self.matrix[i, k] += self.matrix[j, k]
                            inverse.matrix[i, k] += inverse.matrix[j, k]
                        break

        # Row operations
        for i in range(self.row):
            constant = self.matrix[i, i]
            for j in range(self.col):
                self.matrix[i, j] /= constant
                inverse.matrix[i, j] /= constant

            row = i
            while row != 0:
                constant = self.matrix[row-1, i]
                for j in range(self.col):
                    self.matrix[row-1, j] -= self.matrix[i, j] * constant
                    inverse.matrix[row-1, j] -= inverse.matrix[i, j] * constant
                row -= 1

            row = i
            while row != self.row - 1:
                constant = self.matrix[row+1, i]
                for j in range(self.col):
                    self.matrix[row+1, j] -= self.matrix[i, j] * constant
                    inverse.matrix[row+1, j] -= inverse.matrix[i, j] * constant
                row += 1

        self.set(placeHolder)
        return inverse
</code>```

答:
While initially you check that the diagonal elements of a matrix are non-zero, these elements are modified as you perform row operations, and they may become zeros. A usual step in the row reduction of a matrix is to check that an element in a pivot position is non-zero before using it do modify other rows, since this cannot be determined beforehand.

As a side note, I don’t know how the function computing the determinant is implemented, but because floating point arithmetic is not exact, typically computations of a determinant can give a non-zero value even if matrix is singular. The same problem applies to row reduction of matrices: due to rounding errors these computations may give wrong results, with singular matrices appearing to be non-singular and vice versa. In numerical analysis there are a lot of considerations and methods that deal with such issues.

Body:
I am making a function for a matrix class for finding the inverse matrix using gaussian elimination, The function works fine most of the time it would have random warnings that come in pairs that look like this

RuntimeWarning: invalid value encountered in double_scalars
RuntimeWarning: divide by zero encountered in double_scalars

The problem comes for the lines where I divide everything in the same row by a constant. However, the first part of the function already makes sure the all the pivot elements in the matrix would not be zero. I have also ran a lot of tests and the problem isn't coming from the pivot elements being zero, the pivot elements are the only elements used for division, so I don't understand where the error is coming from

def inverse(self):
        if self.row != self.col:
            raise ValueError("Inverse Matrices only possible with square matrices")
        det = self.determinant()
        if det == 0:
            raise ValueError("The provided matrix does not have an Inverse")

        # Makes sure that the pivot elements are not zero
        inverse = Matrix.identity(self.row)
        placeHolder = [[self.matrix[i, j] for j in range(self.col)] for i in range(self.row)]
        for i in range(self.col):
            if self.matrix[i, i] == 0:
                for j in range(self.row):
                    if self.matrix[j, i] != 0:
                        for k in range(self.col):
                            self.matrix[i, k] += self.matrix[j, k]
                            inverse.matrix[i, k] += inverse.matrix[j, k]
                        break

        # Row operations
        for i in range(self.row):
            constant = self.matrix[i, i]
            for j in range(self.col):
                self.matrix[i, j] /= constant
                inverse.matrix[i, j] /= constant

            row = i
            while row != 0:
                constant = self.matrix[row-1, i]
                for j in range(self.col):
                    self.matrix[row-1, j] -= self.matrix[i, j] * constant
                    inverse.matrix[row-1, j] -= inverse.matrix[i, j] * constant
                row -= 1

            row = i
            while row != self.row - 1:
                constant = self.matrix[row+1, i]
                for j in range(self.col):
                    self.matrix[row+1, j] -= self.matrix[i, j] * constant
                    inverse.matrix[row+1, j] -= inverse.matrix[i, j] * constant
                row += 1

        self.set(placeHolder)
        return inverse


问:
Why is angular view not getting updated here?
I have a div tag like this:

```<code>  <div [hidden]="reviewable && !suggestionIsRejected" class="oppia-suggestion-review-message">
    <i [hidden]="reviewMessage === '' || reviewMessage === undefined || reviewMessage === null" class="fa fa-spinner fa-spin"></i>
    <strong>Review message: </strong>{{ reviewMessage }}
  </div>
</code>```

Now, as you can see, I am checking on a reviewMessage variable to show a loading indicator if it's empty, otherwise show it's contents. What I see instead is both of them on the screen, i.e. both the loading indicator as well as the message. Why is it happening this way?

答:
You don't need to do individual value checking, as both '', undefined and null result in falsy, just having to negate the variable's value.

Also, your logic is reversed. You will only want to hide when there is some value.

Try:

  Review message: {{ reviewMessage }}

```

I don't know how the rest of your logic is, but possibly you would also need to put the  outside the div.

Body:
I have a div tag like this:

    Review message: {{ reviewMessage }}

Now, as you can see, I am checking on a reviewMessage variable to show a loading indicator if it's empty, otherwise show it's contents. What I see instead is both of them on the screen, i.e. both the loading indicator as well as the message. Why is it happening this way?

Body:
You don't need to do individual value checking, as both '', undefined and null result in falsy, just having to negate the variable's value.

Also, your logic is reversed. You will only want to hide when there is some value.

Try:

<div [hidden]="reviewable && !suggestionIsRejected" class="oppia-suggestion-review-message">
  <i [hidden]="reviewMessage" class="fa fa-spinner fa-spin"></i>
  <strong [hidden]="!reviewMessage">Review message: </strong>{{ reviewMessage }}
</div>

I don't know how the rest of your logic is, but possibly you would also need to put the <i [hidden]="reviewMessage" class="fa fa-spinner fa-spin"></i> outside the div.


问:
Bash: match in a list of files, cases including and excluding pattern
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

```<code>  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done
</code>```

so here:

```<code>grep -Rl --include \*.txt "+${transaction}:" myDir/
</code>```

grep in myDir recursively all the files.txt matching the TXNA..B

Then

```<code>$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

```<code>grep -L "EXCLUDE_PATTERN1"
</code>```

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

答:
A bit in deep water as I don't have the time to set up testing before I need to get the family some dinner, but could this awk be closely what you are after?

awk -v m=TXNA -v p1=EXCLUDE_PATTERN1 -v p2=EXCLUDE_PATTERN2 '
    $0~m { o[FILENAME] }
    $0~p1 { e1[FILENAME] }
    $0~p2 { e2[FILENAME] }
    END {
        for(v in e1) delete o[v]
        for(v in e2) delete o[v]
        for(v in o) print v
    }
' file*
```
<hr />
<p>A parameterized version could look something like this:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash

unset {in,ex}cludes
[[ $# == 0 ]] && set -- -h

printf -v usage %s "\
$(basename "${0}"): find transactions in files that doesn't include certain patterns
    -i [PATTERN]  Overwrite/add default included matches.
    -e [PATTERN]  Overwrite/add default excluded matches.
    -h            Print this help section

Add list of files as parameters to define which files to look in.
Example: $0 file*
"

while getopts "i:e:h" o; do
    case "${o}" in
        i) includes+=("${OPTARG}") ;;
        e) excludes+=("${OPTARG}") ;;
        h|*) echo -n "${usage}"; exit   ;;
    esac
done
shift $((OPTIND-1))

# set default values if no includes or excludes have been set on command line
[[ -z ${includes[*]} ]] && includes=( 'TXNA' 'TXNB' 'TXNC' 'TXND' 'TXNE' )
[[ -z ${excludes[*]} ]] && excludes=( 'EXCLUDE_PATTERN1' 'EXCLUDE_PATTERN2' )

ex=$(IFS=\|; echo "${excludes[*]}")
inc=$(printf "%s\n" "${includes[@]}")

gawk -v m="$inc" -v p="$ex" '
    BEGIN {
        RS=""
        split(m,t,"\n")
        for(i in t) {
            m = (i==1) ? t[i] : m "|" t[i]
        }
        m="+(" m "):"
    }
    $0~m && $0!~p {
        for(i in t) {
            if($0~"+"t[i]":") o[t[i]][FILENAME]
        }
    }
    END {
            for(i in o) {
                print i, "matches found in:"
                for(f in o[i]) print "\t" f
            }
    }
' "${@}"
</code>```

Body:
I'd need to find the cleanest way in bash to extract from hundred of files, the files matching some patterns in their contents AND NOT matching some others.

for instance:

  for transaction in "TXNA" "TXNB" "TXNC" "TXND" "TXNE" ; do
      echo "--> ${transaction}"
      grep -L "EXCLUDE_PATTERN1" $(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/))   >> myReport.txt
    done

so here:

grep -Rl --include \*.txt "+${transaction}:" myDir/

grep in myDir recursively all the files.txt matching the TXNA..B

Then

$(grep -lL "EXCLUDE_PATTERN2" $(grep -Rl --include \*.txt "+${transaction}:" myDir/)

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN2

and finally:

grep -L "EXCLUDE_PATTERN1"

Exclude in the list found before the files containing the patterns EXCLUDE_PATTERN1

This is quite ugly as I have around 10 patterns to exclude it will become not readable at all.

Any idea for making this code more readable and easy to debug?

Thanks a lot.

Body:
A bit in deep water as I don't have the time to set up testing before I need to get the family some dinner, but could this awk be closely what you are after?

awk -v m=TXNA -v p1=EXCLUDE_PATTERN1 -v p2=EXCLUDE_PATTERN2 '
    $0~m { o[FILENAME] }
    $0~p1 { e1[FILENAME] }
    $0~p2 { e2[FILENAME] }
    END {
        for(v in e1) delete o[v]
        for(v in e2) delete o[v]
        for(v in o) print v
    }
' file*

A parameterized version could look something like this:

#!/bin/bash

unset {in,ex}cludes
[[ $# == 0 ]] && set -- -h

printf -v usage %s "\
$(basename "${0}"): find transactions in files that doesn't include certain patterns
    -i [PATTERN]  Overwrite/add default included matches.
    -e [PATTERN]  Overwrite/add default excluded matches.
    -h            Print this help section

Add list of files as parameters to define which files to look in.
Example: $0 file*
"

while getopts "i:e:h" o; do
    case "${o}" in
        i) includes+=("${OPTARG}") ;;
        e) excludes+=("${OPTARG}") ;;
        h|*) echo -n "${usage}"; exit   ;;
    esac
done
shift $((OPTIND-1))

# set default values if no includes or excludes have been set on command line
[[ -z ${includes[*]} ]] && includes=( 'TXNA' 'TXNB' 'TXNC' 'TXND' 'TXNE' )
[[ -z ${excludes[*]} ]] && excludes=( 'EXCLUDE_PATTERN1' 'EXCLUDE_PATTERN2' )

ex=$(IFS=\|; echo "${excludes[*]}")
inc=$(printf "%s\n" "${includes[@]}")

gawk -v m="$inc" -v p="$ex" '
    BEGIN {
        RS=""
        split(m,t,"\n")
        for(i in t) {
            m = (i==1) ? t[i] : m "|" t[i]
        }
        m="+(" m "):"
    }
    $0~m && $0!~p {
        for(i in t) {
            if($0~"+"t[i]":") o[t[i]][FILENAME]
        }
    }
    END {
            for(i in o) {
                print i, "matches found in:"
                for(f in o[i]) print "\t" f
            }
    }
' "${@}"


问:
What is the more common way to build up a robot control structure?
I’m a college student and I’m trying to build an underwater robot with my team.

We plan to use stm32 and RPi. We will put our controller on stm32 and high-level algorithm (like path planning, object detection…) on Rpi. The reason we design it this way is that the controller needs to be calculated fast and high-level algorithms need more overhead.

But later I found out there is tons of package on ROS that support IMU and other attitude sensors. Therefore, I assume many people might build their controller on a board that can run ROS such as RPi.

As far as I know, RPi is slower than stm32 and has less port to connect to sensor and motor which makes me think that Rpi is not a desired place to run a controller.

So I’m wondering if I design it all wrong?

答:
Robot application could vary so much, the suitable structure shall be very much according to use case, so it is difficult to have a standard answer, I just share my thoughts for your reference.

In general, I think Linux SBC(e.g. RPi) + MCU Controller(e.g. stm32/esp32) is a good solution for many use cases. I personally use RPi + ESP32 for a few robot designs, the reason is,

Linux is not a good realtime OS, MCU is good at handling time critical tasks, like motor control, IMU filtering;

Some protection mechnism need to be reliable even when central "brain" hang or whole system running into low voltage;

MCU is cheaper, smaller and flexible to distribute to any parts inside robot, it also helps our modularized design thinking;

Many new MCU is actually powerful enough to handle sophisticated tasks and could offload a lot from the central CPU;


问:
How to select a random key from an UnorderedMap in NEAR Rust SDK?
How can one get a random key from an UnorderedMap in NEAR Rust SDK?</p>

答:
If performance is not a concern for you, the simplest and most obvious way to do that is to use
the keys_as_vector() method on the map and then get a random element from it via the choose() method in the rand crate.

Example:

```<code>use rand::thread_rng;
use rand::seq::SliceRandom;

let keys = my_map.keys_as_vector();
let random_key = keys.choose(&mut thread_rng());
println!("{:?}", random_key);
</code>```

Clearly, the bigger your map, the slower this is gonna be.

Body:
If performance is not a concern for you, the simplest and most obvious way to do that is to use
the keys_as_vector() method on the map and then get a random element from it via the choose() method in the rand crate.

Example:

use rand::thread_rng;
use rand::seq::SliceRandom;

let keys = my_map.keys_as_vector();
let random_key = keys.choose(&mut thread_rng());
println!("{:?}", random_key);

Clearly, the bigger your map, the slower this is gonna be.


问:
What is the practical use of the identity function in R?
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

```<code>identity <- function (x){x}
</code>```

Why would such a trivial function ever be useful?  Why would it be included in base R?

答:
One use that appears on a simple code base search is as a convenience for the most basic type of error handling function in tryCatch.

```<code>tryCatch(...,error = identity)
</code>```

which is identical (ha!) to

```<code>tryCatch(...,error = function(e) e)
</code>```

So this handler would catch an error message and then simply return it.

Body:
Base R defines an identity function, a trivial identity function returning its argument (quoting from ?identity).

It is defined as :

identity <- function (x){x}

Why would such a trivial function ever be useful?  Why would it be included in base R?

Body:
One use that appears on a simple code base search is as a convenience for the most basic type of error handling function in tryCatch.

tryCatch(...,error = identity)

which is identical (ha!) to

tryCatch(...,error = function(e) e)

So this handler would catch an error message and then simply return it.