问:
Pytest: load and run test from notebook
In the official Databricks example a notebook is created which runs tests with unittest:

The notebook imports another notebook (containing the test_* methods) with %run

The test is launched in the notebook with unittest.main(...

I would like to do the same thing with pytest:

I imported the notebook containing th test_* methods using  %run

I tried to launch the tests with retcode = pytest.main([]) but I always get no tests ran

Notebook containing the tests (notebook_my_test)

```<code>def test_trivial2():
    myvar=True
    assert myvar == True
</code>```

Main notebook:

```<code>%run ./notebook_my_test

import pytest
retcode = pytest.main([])
</code>```

Title: Pytest: load and run test from notebook

Body:
In the official Databricks example a notebook is created which runs tests with unittest:

The notebook imports another notebook (containing the test_* methods) with %run

The test is launched in the notebook with unittest.main(...

I would like to do the same thing with pytest:

I imported the notebook containing th test_* methods using  %run

I tried to launch the tests with retcode = pytest.main([]) but I always get no tests ran

Notebook containing the tests (notebook_my_test)

def test_trivial2():
    myvar=True
    assert myvar == True

Main notebook:

%run ./notebook_my_test

import pytest
retcode = pytest.main([])


来源: stackexchange

问:
Bootstrap input-group-prepend: mismatched sizes and rounded corner
i am experiencing issues with the bootstrap class 'input-group-prepend'.

The prepended #-icon container has a wrong height and the right corners are rounded, although the left corners of the following input field get squared (as expected.

screenshot

```<code><div class="input-group">
  <label for="linkdev_id" class="sr-only">ID</label>
  <div class="input-group-prepend">
    <span class="input-group-text"><img src="./sym/hash.svg" width="20" height="20"></span>
  </div>
  <input type="text" minlength="6" maxlength="6" name="linkdev_id" id="linkdev_id" class="form-control" placeholder="ABCDEF" style="text-transform:uppercase;">
</div>
</code>```

Thanks in advance!

tried to remove the label and replacing the svg in it, but no effect

ContentLicense: CC BY-SA 4.0

Body:
i am experiencing issues with the bootstrap class 'input-group-prepend'.

The prepended #-icon container has a wrong height and the right corners are rounded, although the left corners of the following input field get squared (as expected.

screenshot

  ID

  <input type="text" minlength="6" maxlength="6" name="linkdev_id" id="linkdev_id" class="form-control" placeholder="ABCDEF" style="text-transform:uppercase;">

Thanks in advance!

tried to remove the label and replacing the svg in it, but no effect


问:
Select only the first part of file name
Using Linux bash I have an exercise in which I have a directory full of files, but their names have all kinds of special characters (some of them start with a number, other with $, other have spaces in the start or in the middle of the names etc.) and they end with .ps

Now I want to select only the first part of their name (until .ps) with all the special characters or numbers they contain.

```<code>
for file in *.ps; do
    # Use parameter expansion to remove the .ps extension from the file name
    name=${file%.ps}
    # Use the basename command to print the file name without the path
    echo $(basename "$name")
done
</code>```

or

```<code>for file in *.ps; do
    # The for loop will iterate through all the files in the current directory that have a .ps extension.
    # The variable "file" will hold the name of each file in turn.

    # Use awk to print the first field (delimited by .ps) of the file name
    echo $(awk -F.ps '{print $1}' <<< "$file")
done

</code>```

But with this command some file names are being excluded (for instance those you have spaces in the middle, or starts with $or '

What can I do to contain the whole name file with all the special characters ?
Thank you in advance

Title: Select only the first part of file name

Body:
Using Linux bash I have an exercise in which I have a directory full of files, but their names have all kinds of special characters (some of them start with a number, other with $, other have spaces in the start or in the middle of the names etc.) and they end with .ps

Now I want to select only the first part of their name (until .ps) with all the special characters or numbers they contain.

for file in *.ps; do
    # Use parameter expansion to remove the .ps extension from the file name
    name=${file%.ps}
    # Use the basename command to print the file name without the path
    echo $(basename "$name")
done

or

for file in *.ps; do
    # The for loop will iterate through all the files in the current directory that have a .ps extension.
    # The variable "file" will hold the name of each file in turn.

    # Use awk to print the first field (delimited by .ps) of the file name
    echo $(awk -F.ps '{print $1}' <<< "$file")
done

But with this command some file names are being excluded (for instance those you have spaces in the middle, or starts with $or '

What can I do to contain the whole name file with all the special characters ?
Thank you in advance


问:
React Native Build Failed Using Eas
SDK-47This is the error
Please Help

I just did as per EAS DOCS and still got the error
errrrrr why it sucks and slows development.

Title: React Native Build Failed Using Eas


问:
Saving a excel file with POI was increased size of file
Does anyone know this error? When I save an xlsx file with POI, but its size is increased a lot even with a bit more data. Each auto-save is to increase the size, and so on continuously. Then if you open the file with another application, such as Microsoft Excel and Save again, it will be greatly reduced

```<code>for (i in 0..sheet.lastRowNum) {
                    sheet.getRow(i).createCell(14)
                    tm = sheet.getRow(i).getCell(14).stringCellValue + arrBpd[i].toString()
                    if (tm.length<151)   {
                        sheet.getRow(i).getCell(14).setCellValue(tm)
                    }
                      sheet.getRow(i).getCell(13).setCellValue(sheet.getRow(i).getCell(13).numericCellValue+1)
}

val exFile2 = File("$path/$tenFile.xlsx")
      wb.write(FileOutputStream(exFile2))
wb.close()
</code>```

Before setValue, All of cells were format number or text

Body:
Does anyone know this error? When I save an xlsx file with POI, but its size is increased a lot even with a bit more data. Each auto-save is to increase the size, and so on continuously. Then if you open the file with another application, such as Microsoft Excel and Save again, it will be greatly reduced

for (i in 0..sheet.lastRowNum) {
                    sheet.getRow(i).createCell(14)
                    tm = sheet.getRow(i).getCell(14).stringCellValue + arrBpd[i].toString()
                    if (tm.length<151)   {
                        sheet.getRow(i).getCell(14).setCellValue(tm)
                    }
                      sheet.getRow(i).getCell(13).setCellValue(sheet.getRow(i).getCell(13).numericCellValue+1)
}

val exFile2 = File("$path/$tenFile.xlsx")
      wb.write(FileOutputStream(exFile2))
wb.close()

Before setValue, All of cells were format number or text


问:
Need to return null as response in weblogic 12c that uses jackson json provider
In my weblogic 11g to 12c migrated java application, my API endpoint is

```<code>\`@GET
@Path("/scheme/id/{Id}")
@Produces(MediaType.APPLICATION_JSON)
public List\<Scheme\> getSchemesById(@PathParam("Id") String id){
List\<Scheme\> list =  new List\<Scheme\>;

    return list;

}
\`
</code>```

This returns {} if the list is empty. This list has some child objects that returns null, these nulls and empty object where removed from json response through ObjectMapper mapper properties(Look at the below properties).

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

So that the response

```<code>\`{
"abc" : null, //null object
"xyz" : {}    // empty object

    .
    .

}\`
</code>```

becomes {}. But instead of getting this {}, I need null to be the response for this parent object list. Guide me in getting the required response. This application supports both jersey 1 & jersey 2. Thank you.

I tried with Resource Context ObjectMapper properties like

```<code>mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
</code>```

also included
@JsonInclude(JsonInclude.Include.ALWAYS) for list object getter methods.

Also I tried with a customized null serializer to check for null and to write null through jsongenerator as like below

if (isFullOfNulls(value)) {     generator.writeStartObject();     generator.writeString("null");     generator.writeEndObject(); }
isFullOfNulls() - checks for null at all the properties and child properties.

Body:
In my weblogic 11g to 12c migrated java application, my API endpoint is

\`@GET
@Path("/scheme/id/{Id}")
@Produces(MediaType.APPLICATION_JSON)
public List\<Scheme\> getSchemesById(@PathParam("Id") String id){
List\<Scheme\> list =  new List\<Scheme\>;

    return list;

}
\`

This returns {} if the list is empty. This list has some child objects that returns null, these nulls and empty object where removed from json response through ObjectMapper mapper properties(Look at the below properties).

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

So that the response

\`{
"abc" : null, //null object
"xyz" : {}    // empty object

    .
    .

}\`

becomes {}. But instead of getting this {}, I need null to be the response for this parent object list. Guide me in getting the required response. This application supports both jersey 1 & jersey 2. Thank you.

I tried with Resource Context ObjectMapper properties like

mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

also included
@JsonInclude(JsonInclude.Include.ALWAYS) for list object getter methods.

Also I tried with a customized null serializer to check for null and to write null through jsongenerator as like below

if (isFullOfNulls(value)) {     generator.writeStartObject();     generator.writeString("null");     generator.writeEndObject(); }
isFullOfNulls() - checks for null at all the properties and child properties.


问:
make: *** [Makefile:43: user_proj_example] Error 1
```<code>When I call the `make user_proj_example` command to the caravel user project in the openlane folder, I encounter such an error.
</code>```

I have applied the solutions from all the sources I can find on the internet, but the problem still persists.

Body:
When I call the `make user_proj_example` command to the caravel user project in the openlane folder, I encounter such an error.

I have applied the solutions from all the sources I can find on the internet, but the problem still persists.


问:
Is there a way I can specify conditional defines when using a package?
I have a package Fluxor.Web.Blazor.ReduxDevTools which allows the user to specify whether they use System.Text.Json or Newtonsoft.Json for serialization.

But this means I must have a dependency on both, which is a problem because this is a Blazor library and it increases the payload size.

Is there a way I can compile my package so the consumer can define either Fluxor_NewtonsoftJson or Fluxor_SystemTextJson and when they compile they will somehow have a different build that has different dependencies?


问:
Python object property type conversion without creating new instance of an object
I'm looking for a way to convert Python object property type or cast it without creating new instance of an object. Consider the following code:

```<code>import enum
import requests

class HttpHeaders(str, enum.Enum):
    forwarded_for = 'X-Forwarded-For'
    content_type = 'Content-Type'

myheaders = {
    HttpHeaders.forwarded_for: "192.168.0.1",
    HttpHeaders.content_type: "text/porn",
}

# The line below is needed for requests >= 2.28.0
myheaders= {xkey.value: xval for xkey, xval in myheaders.items() }
requests.post('http://127.0.0.1:8000', "zima", headers=myheaders)
</code>```

Python requests library starting from version 2.28.0 introduced strict type checking of http headers which is  vaguely mentioned in the release notes, so the code above without the line:

```<code>myheaders= {xkey.value: xval for xkey, xval in myheaders.items() }
</code>```

is going to throw exception:

```<code>requests.exceptions.InvalidHeader: Header part (<HttpHeaders.content_encoding: 'X-Content-Encoding'>) from {<HttpHeaders.content_encoding: 'X-Content-Encoding'>: 'gzip'} must be of type str or bytes, not <enum 'HttpHeaders'>
</code>```

Unfortunately this fix creates new instance of an object which incurs performance penalty (in case of a small array it's meaningless but still doesn't look like a great fix).

What would be the recommended fix for that?

Body:
I'm looking for a way to convert Python object property type or cast it without creating new instance of an object. Consider the following code:

import enum
import requests

class HttpHeaders(str, enum.Enum):
    forwarded_for = 'X-Forwarded-For'
    content_type = 'Content-Type'

myheaders = {
    HttpHeaders.forwarded_for: "192.168.0.1",
    HttpHeaders.content_type: "text/porn",
}

# The line below is needed for requests >= 2.28.0
myheaders= {xkey.value: xval for xkey, xval in myheaders.items() }
requests.post('http://127.0.0.1:8000', "zima", headers=myheaders)

Python requests library starting from version 2.28.0 introduced strict type checking of http headers which is  vaguely mentioned in the release notes, so the code above without the line:

myheaders= {xkey.value: xval for xkey, xval in myheaders.items() }

is going to throw exception:

requests.exceptions.InvalidHeader: Header part (<HttpHeaders.content_encoding: 'X-Content-Encoding'>) from {<HttpHeaders.content_encoding: 'X-Content-Encoding'>: 'gzip'} must be of type str or bytes, not <enum 'HttpHeaders'>

Unfortunately this fix creates new instance of an object which incurs performance penalty (in case of a small array it's meaningless but still doesn't look like a great fix).

What would be the recommended fix for that?


问:
A Collapsible JavaScript Code Isn't Accepted on Google Blogger
The following JavaScript code is used to make a collapsible element but it isn't accepted on google blogger and I recieve this message:
"org.xml.sax.SAXParseException; lineNumber: 847; columnNumber: 22; The content of elements must consist of well-formed character data or markup."
Can anyone help me?</p>
```<code>var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    var content = this.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  });
}
</code>```

Body:
The following JavaScript code is used to make a collapsible element but it isn't accepted on google blogger and I recieve this message:
"org.xml.sax.SAXParseException; lineNumber: 847; columnNumber: 22; The content of elements must consist of well-formed character data or markup."
Can anyone help me?

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    var content = this.nextElementSibling;
    if (content.style.maxHeight){
      content.style.maxHeight = null;
    } else {
      content.style.maxHeight = content.scrollHeight + "px";
    }
  });
}


问:
Regex of Visual Source Safe History
i'm stuck to write a regex pattern to the below lines, my problem is to match it in multilines

```<code>* History of Modifications:
 * $Log: /System/Utilities.cpp $
 *
 * 5     7/12/22 4:49p Peter
 *
 * 4     5/12/22 5:57p Mina
 *
 * 3     20/11/22 6:15p Simon
 *
 * 2     18/10/22 1:48p Micheal
 *
 * 1     5/10/21 4:13p Peter
 *
 */
</code>```

these lines always start with

$log: filename $

until the comment ends with */

i tried these two regex

```<code>^ \* \d+ .*
</code>```
```<code>/\d{1,2}\/\d{1,2}\/\d{2} \d{1,2}:\d{2}[ap] [A-Z][a-z]+/
</code>```

Title: Regex of Visual Source Safe History

Body:
i'm stuck to write a regex pattern to the below lines, my problem is to match it in multilines

* History of Modifications:
 * $Log: /System/Utilities.cpp $
 *
 * 5     7/12/22 4:49p Peter
 *
 * 4     5/12/22 5:57p Mina
 *
 * 3     20/11/22 6:15p Simon
 *
 * 2     18/10/22 1:48p Micheal
 *
 * 1     5/10/21 4:13p Peter
 *
 */

these lines always start with

$log: filename $

until the comment ends with */

i tried these two regex

^ \* \d+ .*

/\d{1,2}\/\d{1,2}\/\d{2} \d{1,2}:\d{2}[ap] [A-Z][a-z]+/


问:
Traitlets error when trying to generate plotly graph
When I try to run my dash app, I keep getting this error:

```<code>FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.
</code>```

I keep changing the port but it still gives me the same error, I am not sure where I am going wrong.

This is my code for the app:

```<code>dff = final_api.query("info_title=='Onfido API'").sort_values(by='commitDate')
import plotly.graph_objects as go
fig = go.Figure()

fig = px.scatter(dff, x='commitDate', y='API_paths', color='server_version', text='API_paths', color_discrete_sequence=px.colors.qualitative.Pastel1)

fig.add_trace(go.Scatter(mode='lines',
                         x=dff["commitDate"],
                         y=dff["API_paths"],
                         line_color='black',
                         line_width=0.6,
                         line_shape='hv',
                         showlegend=False
                       )
             )

for _,row in dff.iterrows():
    fig.add_annotation(
        go.layout.Annotation(
            x=row["commitDate"],
            y=row["API_paths"],
            text=row['server_version'],
            showarrow=False,
            align='center',
            yanchor='bottom',
            yshift=10,
            textangle=-1)
    )

fig.update_layout(template='ggplot2', title_text='Server Versions in Onfido API',title_x=0.5,width=1000,height=600,yaxis_range=[0, 40],
                  xaxis_title='Date of Commit', yaxis_title='Number of Paths',hoverlabel=dict(font_size=16, font_family="PT Sans"),font=dict(size=20, family='PT Sans'), paper_bgcolor='rgba(233,233,233,100)')
fig.update_traces(marker_size=10, marker_line_width=2, marker_line_color='black', showlegend=False, textposition="bottom right")
fig.show()

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=True, port=8000)

</code>```

Any help would be kindly appreciated.

Body:
When I try to run my dash app, I keep getting this error:

FutureWarning: Supporting extra quotes around strings is deprecated in traitlets 5.0. You can use 'hmac-sha256' instead of '"hmac-sha256"' if you require traitlets >=5.

I keep changing the port but it still gives me the same error, I am not sure where I am going wrong.

This is my code for the app:

dff = final_api.query("info_title=='Onfido API'").sort_values(by='commitDate')
import plotly.graph_objects as go
fig = go.Figure()

fig = px.scatter(dff, x='commitDate', y='API_paths', color='server_version', text='API_paths', color_discrete_sequence=px.colors.qualitative.Pastel1)

fig.add_trace(go.Scatter(mode='lines',
                         x=dff["commitDate"],
                         y=dff["API_paths"],
                         line_color='black',
                         line_width=0.6,
                         line_shape='hv',
                         showlegend=False
                       )
             )

for _,row in dff.iterrows():
    fig.add_annotation(
        go.layout.Annotation(
            x=row["commitDate"],
            y=row["API_paths"],
            text=row['server_version'],
            showarrow=False,
            align='center',
            yanchor='bottom',
            yshift=10,
            textangle=-1)
    )

fig.update_layout(template='ggplot2', title_text='Server Versions in Onfido API',title_x=0.5,width=1000,height=600,yaxis_range=[0, 40],
                  xaxis_title='Date of Commit', yaxis_title='Number of Paths',hoverlabel=dict(font_size=16, font_family="PT Sans"),font=dict(size=20, family='PT Sans'), paper_bgcolor='rgba(233,233,233,100)')
fig.update_traces(marker_size=10, marker_line_width=2, marker_line_color='black', showlegend=False, textposition="bottom right")
fig.show()

import dash
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=True, port=8000)

Any help would be kindly appreciated.


问:
Must use import to load ES Module - lowlight with Quasar app
I'm using tiptap in my Quasar app with the node CodeBlockLowlight enabled.

Running the dev server works just fine with quasar dev --mode ssr --port 9000. THe project builds and I'm able to work on my project without any issues.

Now, whenever I try to start the node server with the following command ENV_FILE=test quasar build --mode ssr --port 3000 && node dist/ssr/index.js  it gives the following errors:

```<code>internal/modules/cjs/loader.js:1102
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/whatever/devotto/devotto.com/node_modules/lowlight/lib/core.js
require() of ES modules is not supported.
require() of /home/whatever/devotto/devotto.com/node_modules/lowlight/lib/core.js from /home/whatever/devotto/devotto.com/dist/ssr/server/server-entry.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename core.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/whatever/devotto/devotto.com/node_modules/lowlight/package.json.
</code>```

Here is my package.json

{
  ...
  "dependencies": {
    "@quasar/extras": "^1.0.0",
    "@tiptap/extension-code-block-lowlight": "^2.0.0-beta.209",
    "lowlight": "^2.8.0",
    "@tiptap/vue-3": "2.0.0-beta.204",
  }
}
```

What I have tried

After reading the following resources:

https://github.com/wooorm/lowlight/issues/37

https://bobbyhadz.com/blog/error-err-require-esm-must-use-import-to-load-es-module

Importing in Node.js: error "Must use import to load ES Module"

I have:

tried to lower the version of lowlight all the way to 1.20.0

tried to add "type": "module" to my package.json

So far I wasn't able to build my project and start a node server so I can run my E2E tests.

Why am I getting this error and how I can solve it?

Body:
I'm using tiptap in my Quasar app with the node CodeBlockLowlight enabled.

Running the dev server works just fine with quasar dev --mode ssr --port 9000. THe project builds and I'm able to work on my project without any issues.

Now, whenever I try to start the node server with the following command ENV_FILE=test quasar build --mode ssr --port 3000 && node dist/ssr/index.js  it gives the following errors:

internal/modules/cjs/loader.js:1102
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/whatever/devotto/devotto.com/node_modules/lowlight/lib/core.js
require() of ES modules is not supported.
require() of /home/whatever/devotto/devotto.com/node_modules/lowlight/lib/core.js from /home/whatever/devotto/devotto.com/dist/ssr/server/server-entry.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename core.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/whatever/devotto/devotto.com/node_modules/lowlight/package.json.

Here is my package.json

{
  ...
  "dependencies": {
    "@quasar/extras": "^1.0.0",
    "@tiptap/extension-code-block-lowlight": "^2.0.0-beta.209",
    "lowlight": "^2.8.0",
    "@tiptap/vue-3": "2.0.0-beta.204",
  }
}

What I have tried

After reading the following resources:

https://github.com/wooorm/lowlight/issues/37

https://bobbyhadz.com/blog/error-err-require-esm-must-use-import-to-load-es-module

Importing in Node.js: error "Must use import to load ES Module"

I have:

tried to lower the version of lowlight all the way to 1.20.0

tried to add "type": "module" to my package.json

So far I wasn't able to build my project and start a node server so I can run my E2E tests.

Why am I getting this error and how I can solve it?


问:
ValueError: Expected 2D array, got 1D array instead: array=[4. 4. 3. ... 3. 3. 3.]
I tried to find cosine_similarity that compare pivot table and object using .loc, and the result says
ValueError: Expected 2D array, got 1D array instead: array=[4. 4. 3. ... 3. 3. 3.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

So, i tried to followed the suggestion, but it doesn't work, it says "Cannot compare multidimensional index" , could you guys help me and explain to me what should i do?

this my code:

```<code>#delete related_test
for i in range(len(collab_rated_test_fix)):
          ratings_test_df = ratings_test_df.drop(ratings_test_df.loc[(ratings_test_df.user_id == user_id_test) &\
                                                                      (ratings_test_df.book_id == collab_rated_test_fix[i])]\
                                                                      .index)
#pivot table
user_book_rating = pd.pivot_table(ratings_test_df, values="rating", index="book_id",columns="user_id")
user_book_rating = user_book_rating.fillna(user_book_rating.mean())

user_id_test = 9923

#cosine similarity
rel_user = pd.DataFrame(columns=['userId_1', 'userId_2','similarity'])

for rows, mean in user_book_rating.iteritems():

      sim = cosine_similarity(user_book_rating.loc[ : , user_id_test], user_book_rating.loc[ : , rows]) #error

      rel_user = rel_user.append({'UserId_1': user_id_test, 'UserId_2': rows, 'similarity': sim}, ignore_index=True)

rel_user['userId_1'] = rel_user['userId_1'].apply(int)
rel_user['userId_2'] = rel_user['userId_2'].apply(int)
</code>```

Body:
I tried to find cosine_similarity that compare pivot table and object using .loc, and the result says
ValueError: Expected 2D array, got 1D array instead: array=[4. 4. 3. ... 3. 3. 3.]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

So, i tried to followed the suggestion, but it doesn't work, it says "Cannot compare multidimensional index" , could you guys help me and explain to me what should i do?

this my code:

#delete related_test
for i in range(len(collab_rated_test_fix)):
          ratings_test_df = ratings_test_df.drop(ratings_test_df.loc[(ratings_test_df.user_id == user_id_test) &\
                                                                      (ratings_test_df.book_id == collab_rated_test_fix[i])]\
                                                                      .index)
#pivot table
user_book_rating = pd.pivot_table(ratings_test_df, values="rating", index="book_id",columns="user_id")
user_book_rating = user_book_rating.fillna(user_book_rating.mean())

user_id_test = 9923

#cosine similarity
rel_user = pd.DataFrame(columns=['userId_1', 'userId_2','similarity'])

for rows, mean in user_book_rating.iteritems():

      sim = cosine_similarity(user_book_rating.loc[ : , user_id_test], user_book_rating.loc[ : , rows]) #error

      rel_user = rel_user.append({'UserId_1': user_id_test, 'UserId_2': rows, 'similarity': sim}, ignore_index=True)

rel_user['userId_1'] = rel_user['userId_1'].apply(int)
rel_user['userId_2'] = rel_user['userId_2'].apply(int)


问:
C# Lock Cursor inside of Window like Blender does it
So im making a 3d fps game.

You know how Blender makes your Cursor repeat across the Window?

Yea i want that but in WinForms C#, im using SharpDX if that does anything.

I want like a Cursor that goes from one side from the window to the other, I bet with some code its possible, Does SharpDX have anything included to help me here?

Any Help appreciated!


问:
Multiple Modals not closing when I click on the X button
The modals that I have set up for my website are opening on clicking the respective div elements and they're closing as well when clicking outside the modals but they're not closing on clicking the 'X' buttons, except for the very first modal.

```<code>{% for i in range(anime_name|length)%}

    <!-- The Modal -->

        <div id = "more-details1" class = "modal">

        <!-- More details content -->

            <div class = "more-details-content">
                <div class = "modal-header">
                        <span class = "close" id = "close_{{i}}">×</span>
                            <p> {{ anime_name[0] }} </p>
                    </div>
                    <div class = "modal-body">
                            <p>Some text in the Modal Body</p>
                            <p>Some other text...</p>
                    </div>
            </div>

        </div>

{% endfor %}

{% for i in range(anime_name|length)%}

    <!-- The Modal -->

        <div id = "more-details2" class = "modal">

            <!-- More details content -->

            <div class = "more-details-content">
                    <div class = "modal-header">
                            <span class = "close" id = "close_{{i}}">×</span>
                                <p> {{ anime_name[1] }} </p>
                        </div>
                        <div class = "modal-body">
                                <p>Some text in the Modal Body</p>
                                <p>Some other text...</p>
                        </div>
                </div>

    </div>

{% endfor %}
</code>```
```<code>/* The Modal (background) */

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  }

.more-details-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
  }

  /* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
  }

  @keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
  }

  /* The Close Button */
.close {
    color: #f6e8d6;
    float: right;
    font-size: 28px;
    font-weight: bold;
  }

.close:hover, .close:focus {
  color: #222222;
  text-decoration: none;
  cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #b83333;
    color: #f6e8d6;
  }

.modal-body {padding: 2px 16px;}

</code>```
```<code>var modal1 = document.getElementById("more-details1")
var btn1 = document.querySelector(".anime-holder_0")
var span = document.getElementsByClassName("close")[0];
// var span1 = document.getElementById("close_0");

var modal2 = document.getElementById("more-details2")
var btn2 = document.querySelector(".anime-holder_1")
// var span2 = document.getElementById("close_1");

window.onclick = function(event) {
    if(btn1.contains(event.target)){
        modal1.style.display = "block";
        } else {
        if (!modal1.contains(event.target) && modal1.style.display === "block" ||  span.contains(event.target)) {
                    modal1.style.display = "none";
                }
    }
        if (event.target == modal1) {
        modal1.style.display = "none";
        }

    if(btn2.contains(event.target)){
        modal2.style.display = "block";
        } else {
                if (!modal2.contains(event.target) && modal2.style.display === "block" ||  span.contains(event.target)) {
                    modal2.style.display = "none";
        }
    }
        if (event.target == modal2) {
                modal2.style.display = "none";
        }

}
</code>```

I'm using the jinja template to access the values from my dataframe in the modal section but also because I tried giving individual IDs to each 'close' aka 'X' button through "close_{{i}}" (as that seems to be working when I'm accessing the 'anime-holder_0' and 'anime-holder_1' in btn1 and btn2 through 'anime-holder_{{i}}') so I tried doing that here too with different 'span' for each modal but that didn't work as the multiple modals didn't close on clicking 'X' except for the first one.

It could be because of the many conditions being given in the windows.onclick = function(event) {} but having a seperate function for each modal doesn't work either because it overrides the previous one.

I'm not sure what's the reason for this problem but I'm just looking for a way to close multiple modals by clicking on their 'X' buttons AND clicking outside the modals themselves (Hopefully without having to use Bootstrap).

Body:
The modals that I have set up for my website are opening on clicking the respective div elements and they're closing as well when clicking outside the modals but they're not closing on clicking the 'X' buttons, except for the very first modal.

{% for i in range(anime_name|length)%}

                        ×

 {{ anime_name[0] }}

Some text in the Modal Body

Some other text...

{% endfor %}

{% for i in range(anime_name|length)%}

                            ×

 {{ anime_name[1] }}

Some text in the Modal Body

Some other text...

{% endfor %}

/* The Modal (background) */

.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
  }

.more-details-content {
    position: relative;
    background-color: #fefefe;
    margin: auto;
    padding: 0;
    border: 1px solid #888;
    width: 80%;
    box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
    -webkit-animation-name: animatetop;
    -webkit-animation-duration: 0.4s;
    animation-name: animatetop;
    animation-duration: 0.4s
  }

  /* Add Animation */
@-webkit-keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
  }

  @keyframes animatetop {
    from {top:-300px; opacity:0}
    to {top:0; opacity:1}
  }

  /* The Close Button */
.close {
    color: #f6e8d6;
    float: right;
    font-size: 28px;
    font-weight: bold;
  }

.close:hover, .close:focus {
  color: #222222;
  text-decoration: none;
  cursor: pointer;
}

.modal-header {
    padding: 2px 16px;
    background-color: #b83333;
    color: #f6e8d6;
  }

.modal-body {padding: 2px 16px;}

var modal1 = document.getElementById("more-details1")
var btn1 = document.querySelector(".anime-holder_0")
var span = document.getElementsByClassName("close")[0];
// var span1 = document.getElementById("close_0");

var modal2 = document.getElementById("more-details2")
var btn2 = document.querySelector(".anime-holder_1")
// var span2 = document.getElementById("close_1");

window.onclick = function(event) {
    if(btn1.contains(event.target)){
        modal1.style.display = "block";
        } else {
        if (!modal1.contains(event.target) && modal1.style.display === "block" ||  span.contains(event.target)) {
                    modal1.style.display = "none";
                }
    }
        if (event.target == modal1) {
        modal1.style.display = "none";
        }

    if(btn2.contains(event.target)){
        modal2.style.display = "block";
        } else {
                if (!modal2.contains(event.target) && modal2.style.display === "block" ||  span.contains(event.target)) {
                    modal2.style.display = "none";
        }
    }
        if (event.target == modal2) {
                modal2.style.display = "none";
        }

}

I'm using the jinja template to access the values from my dataframe in the modal section but also because I tried giving individual IDs to each 'close' aka 'X' button through "close_{{i}}" (as that seems to be working when I'm accessing the 'anime-holder_0' and 'anime-holder_1' in btn1 and btn2 through 'anime-holder_{{i}}') so I tried doing that here too with different 'span' for each modal but that didn't work as the multiple modals didn't close on clicking 'X' except for the first one.

It could be because of the many conditions being given in the windows.onclick = function(event) {} but having a seperate function for each modal doesn't work either because it overrides the previous one.

I'm not sure what's the reason for this problem but I'm just looking for a way to close multiple modals by clicking on their 'X' buttons AND clicking outside the modals themselves (Hopefully without having to use Bootstrap).


问:
loading data into singly linked list from file in c
I would like to load the data back into the linked list after i terminate the program and run it the second time. But the previous list of data doesn't store back into the linked list the second time i run

insert with singly linked list:

```<code>    tick *addinfo(tick *previous,char* serial,char* ticketno,char* name,char* id)
  {

     tick *info = malloc(sizeof(tick));
    info->nextPtr = NULL;
    info->visitor.SrNo =strdup(serial);
    info->visitor.ticketNo = strdup(ticketno);
    info->visitor.Name = strdup(name);
    info->visitor.ID= strdup(id);

    if (previous != NULL)
    {
        previous->nextPtr = info;
    }

    printf("visitor info has been added: %s %s %s %s",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
    ptroutfile=fopen("output.txt","a");
    fprintf(ptroutfile,"visitor info has been added: %s %s %s %s\n\n",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
    fclose(ptroutfile);

    return info;
}
</code>```

readfile function:

```<code>    void readfile(tick* startPtr)
    {
       FILE* cfptr=NULL;
       char srno[20],ticketNo[20],name[30],id[20];
       cfptr=fopen("ticket.txt","r");

       while(fscanf(cfptr,"%s %s %s %s",srno,ticketNo,name,id) == 4)
       {
          tick *info = malloc(sizeof(tick));
          info->nextPtr = NULL;
          info->visitor.SrNo =strdup(srno);
          info->visitor.ticketNo = strdup(ticketNo);
          info->visitor.Name = strdup(name);
          info->visitor.ID= strdup(id);

          if (startPtr != NULL)
          {
              startPtr->nextPtr = info;
          }

     }

     fclose(cfptr);
}
</code>```

Calling the function in main:

```<code>int main ()
{

   tick *visitorinfo = NULL;
   tick *new = NULL;

    readfile(visitorinfo);

}
</code>```

Body:
I would like to load the data back into the linked list after i terminate the program and run it the second time. But the previous list of data doesn't store back into the linked list the second time i run

insert with singly linked list:

    tick *addinfo(tick *previous,char* serial,char* ticketno,char* name,char* id)
  {

     tick *info = malloc(sizeof(tick));
    info->nextPtr = NULL;
    info->visitor.SrNo =strdup(serial);
    info->visitor.ticketNo = strdup(ticketno);
    info->visitor.Name = strdup(name);
    info->visitor.ID= strdup(id);

    if (previous != NULL)
    {
        previous->nextPtr = info;
    }

    printf("visitor info has been added: %s %s %s %s",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
    ptroutfile=fopen("output.txt","a");
    fprintf(ptroutfile,"visitor info has been added: %s %s %s %s\n\n",info->visitor.SrNo,info->visitor.ticketNo,info->visitor.Name,info->visitor.ID);
    fclose(ptroutfile);

    return info;
}

readfile function:

    void readfile(tick* startPtr)
    {
       FILE* cfptr=NULL;
       char srno[20],ticketNo[20],name[30],id[20];
       cfptr=fopen("ticket.txt","r");

       while(fscanf(cfptr,"%s %s %s %s",srno,ticketNo,name,id) == 4)
       {
          tick *info = malloc(sizeof(tick));
          info->nextPtr = NULL;
          info->visitor.SrNo =strdup(srno);
          info->visitor.ticketNo = strdup(ticketNo);
          info->visitor.Name = strdup(name);
          info->visitor.ID= strdup(id);

          if (startPtr != NULL)
          {
              startPtr->nextPtr = info;
          }

     }

     fclose(cfptr);
}

Calling the function in main:

int main ()
{

   tick *visitorinfo = NULL;
   tick *new = NULL;

    readfile(visitorinfo);

}


问:
When loading Keras checkpoint the validation loss increases on first evaluation
I'm having an issue with model saving and loading (fine-tuning).

After I load the model that was saved at val_loss 0.8, on first epoch it will be evaluated to 0.85 or so, even if the model never climbed more than 0.82 for example on previous training (just went flat).
The ModelCheckpoint then will save it at that point (seems like it starts from inf?) overwriting any previous progress.

I'm saving checkpoints like this:

```<code>checkpoint = ModelCheckpoint(
    "count_fingers.h5",
    #filepath="weights.{epoch:02d}-{val_loss:.2f}.h5",
    monitor= "val_loss",
    verbose= 1,
    save_best_only= True,
    #save_weights_only= True,
    save_freq="epoch"
)
</code>```

and loading like this:

```<code>model = tf.keras.models.load_model("count_fingers.h5")
</code>```

I've tried also model.load_weights.

After some search I think it might be related to the optimizer decay? That will have a big learning rate on first epoch? Not sure.

If you can let me know what I'm doing wrong or why this is happening and what's the right approach to continue exactly from where I've left?

Thank you,

Adrian

Body:
I'm having an issue with model saving and loading (fine-tuning).

After I load the model that was saved at val_loss 0.8, on first epoch it will be evaluated to 0.85 or so, even if the model never climbed more than 0.82 for example on previous training (just went flat).
The ModelCheckpoint then will save it at that point (seems like it starts from inf?) overwriting any previous progress.

I'm saving checkpoints like this:

checkpoint = ModelCheckpoint(
    "count_fingers.h5",
    #filepath="weights.{epoch:02d}-{val_loss:.2f}.h5",
    monitor= "val_loss",
    verbose= 1,
    save_best_only= True,
    #save_weights_only= True,
    save_freq="epoch"
)

and loading like this:

model = tf.keras.models.load_model("count_fingers.h5")

I've tried also model.load_weights.

After some search I think it might be related to the optimizer decay? That will have a big learning rate on first epoch? Not sure.

If you can let me know what I'm doing wrong or why this is happening and what's the right approach to continue exactly from where I've left?

Thank you,

Adrian


问:
Puppeteer script works some times but doesn't work some times without any change in the code
I have a piece of code which uses Puppeteer to scrape for some data off google. The problem is that sometimes the code works without any problem but sometimes stops working even when there is virtually no change in the code of the puppeteer script.

Sometimes the code works after restarting VS Code but it seems completely non intuitive for me why a piece of code stops working for some time and again stars working.

The problem is that sometimes I get an error where the the function page.click() raises an error which is as follows:

Node is either not clickable or not an HTML Element although in the headless=false setting I can see the link getting clicked and I can even the see it doing what it should do but for some reason puppeteer thinks there has been some exception and stops the execution of the code.


问:
Catia V5 VB.net code, how to remove popup "some contextual links will be broken"
I have a Catia V5 assembly where I'd like to delete a part that is inside a product. I made the following code.
`

```<code> Public Shared Function Delete_Part(Name_Of_The_Product_Instance_Containing_The_Part As String, Name_Of_The_Part_Instance_To_Delete As String)

        Dim CATIA = GetObject(, "CATIA.Application")
        Dim productDocument1 = CATIA.ActiveDocument
        Dim selection1 = productDocument1.Selection
        selection1.Clear
        Dim product1 = productDocument1.Product
        Dim products1 = product1.Products
        Dim product2 = products1.Item(Name_Of_The_Product_Instance_Containing_The_Part)
        Dim products2 = product2.Products
        Dim product3 = products2.Item(Name_Of_The_Part_Instance_To_Delete)
        selection1.Add(product3)
        selection1.Clear
    End Function
</code>```

The code works, the part is about to be delete but a warning/popup message appears saying :

"some contextual links will be broken [...] some of the components you are trying to delete are contextual. Use change context on a new instance before synchronizing the external references "

I can manually click on ok and the part gets deleted with no problem, but how can I automate this ?

Writing :

```<code>
SendKeys.SendWait("{ENTER}")
</code>```

Would not really be an option as it's not robust.

Body:
I have a Catia V5 assembly where I'd like to delete a part that is inside a product. I made the following code.
`

 Public Shared Function Delete_Part(Name_Of_The_Product_Instance_Containing_The_Part As String, Name_Of_The_Part_Instance_To_Delete As String)

        Dim CATIA = GetObject(, "CATIA.Application")
        Dim productDocument1 = CATIA.ActiveDocument
        Dim selection1 = productDocument1.Selection
        selection1.Clear
        Dim product1 = productDocument1.Product
        Dim products1 = product1.Products
        Dim product2 = products1.Item(Name_Of_The_Product_Instance_Containing_The_Part)
        Dim products2 = product2.Products
        Dim product3 = products2.Item(Name_Of_The_Part_Instance_To_Delete)
        selection1.Add(product3)
        selection1.Clear
    End Function

The code works, the part is about to be delete but a warning/popup message appears saying :

"some contextual links will be broken [...] some of the components you are trying to delete are contextual. Use change context on a new instance before synchronizing the external references "

I can manually click on ok and the part gets deleted with no problem, but how can I automate this ?

Writing :

SendKeys.SendWait("{ENTER}")

Would not really be an option as it's not robust.


问:
Optional prefix for imask
using react version of this library https://imask.js.org/guide.html

I made hh:mm field using this library

```<code>export const maskC = 'SH:M';

export const maskObj = {
  S: {
    mask: MaskedEnum,
    enum: ['+', '-'],
  },
  H: {
    mask: MaskedRange,
    from: 0,
    to: 23,
    maxLength: 2,
  },

  M: {
    mask: MaskedRange,
    from: 0,
    to: 59,
    maxLength: 2,
  },
};
</code>```

problem is user have to enter + or - at start
if user want to enter 23:59 they have to type + explicitly at start
what i need is prefix should be optional, what can only be + or -, no other values or special characters

if someone knows the answer, that would be very helpful!

i got to know that we can use this for optional inputs "[]", but this is allowing every character or nuber, what i need is it should only allow + or -, ---> [+-] this won't work

Title: Optional prefix for imask

Body:
using react version of this library https://imask.js.org/guide.html

I made hh:mm field using this library

export const maskC = 'SH:M';

export const maskObj = {
  S: {
    mask: MaskedEnum,
    enum: ['+', '-'],
  },
  H: {
    mask: MaskedRange,
    from: 0,
    to: 23,
    maxLength: 2,
  },

  M: {
    mask: MaskedRange,
    from: 0,
    to: 59,
    maxLength: 2,
  },
};

problem is user have to enter + or - at start
if user want to enter 23:59 they have to type + explicitly at start
what i need is prefix should be optional, what can only be + or -, no other values or special characters

if someone knows the answer, that would be very helpful!

i got to know that we can use this for optional inputs "[]", but this is allowing every character or nuber, what i need is it should only allow + or -, ---> [+-] this won't work


问:
NP Array Comparison elementwise and specific conditions
I would like to ask a question for a numpy array below.

I have a dataset, which has 50 rows and 15 columns and I created a numpy array as such:

I want to compare rows with each other (except than itself), then found the number of rows which satisfies following condition:

there is no other row that

-values are both smaller

-if one is equal, the other one should be smaller

```<code>Money Weight
10 80
20 70
30 90
25 50
35 10
40 60
50 10
</code>```

for instance for row 1: there is no other row which are both smaller on two columns, if one is smaller on the other column row 1 is smaller on the other. Satisfies the condition

for row 3: there is no other row which are both smaller on two columns, it is equal on column weight with row 6 but on money dimension it is smaller. Satisfies the condition

for row 6: there is no other row which are both smaller on two columns. it is equal on weight dimension with row 3 but the value in money is greater. Does not satisfy the condition

Following code works perfect for me to find the rows in the given table:

```<code>mask = (arr <= arr[:, None]).all(2).sum(1) < 2
res = df[mask]
print(res)
</code>```

But I need also compare the table with another row outside the table and should find True or False

For instance:

```<code>compare([40,10],table) =False
compare([10,70],table) =True
</code>```

I have tried bunch of ways to find a proper solution, but could not find a proper way.

I appreciate any suggestions!

Body:
I would like to ask a question for a numpy array below.

I have a dataset, which has 50 rows and 15 columns and I created a numpy array as such:

I want to compare rows with each other (except than itself), then found the number of rows which satisfies following condition:

there is no other row that

-values are both smaller

-if one is equal, the other one should be smaller

Money Weight
10 80
20 70
30 90
25 50
35 10
40 60
50 10

for instance for row 1: there is no other row which are both smaller on two columns, if one is smaller on the other column row 1 is smaller on the other. Satisfies the condition

for row 3: there is no other row which are both smaller on two columns, it is equal on column weight with row 6 but on money dimension it is smaller. Satisfies the condition

for row 6: there is no other row which are both smaller on two columns. it is equal on weight dimension with row 3 but the value in money is greater. Does not satisfy the condition

Following code works perfect for me to find the rows in the given table:

mask = (arr <= arr[:, None]).all(2).sum(1) < 2
res = df[mask]
print(res)

But I need also compare the table with another row outside the table and should find True or False

For instance:

compare([40,10],table) =False
compare([10,70],table) =True

I have tried bunch of ways to find a proper solution, but could not find a proper way.

I appreciate any suggestions!


问:
Zeppelin HDP 2.6.5 : I want to display some data stored on my spark-wharehouse and i have problems
I'm trying to display some data stored on my database in the spark-wharehous on zeppelin but i have an some errors :

```<code>%spark2.sql

select * from testdb3.test2
</code>```

the errors :

```<code>Table or view not found: `testdb3`.`test2`; line 1 pos 14;
'Project [*]
+- 'UnresolvedRelation `testdb3`.`test2`
set zeppelin.spark.sql.stacktrace = true to see full stacktrace
</code>```

When i go to my filezilla i can see the database on my spark-warehouse(root account) but i can get the data.

my database in filezilla

how can i get my database on the sparkwarehouse ?

Thank you for the help and have a nice day.

I try to restart my hdp.

Body:
I'm trying to display some data stored on my database in the spark-wharehous on zeppelin but i have an some errors :

%spark2.sql

select * from testdb3.test2

the errors :

Table or view not found: `testdb3`.`test2`; line 1 pos 14;
'Project [*]
+- 'UnresolvedRelation `testdb3`.`test2`
set zeppelin.spark.sql.stacktrace = true to see full stacktrace

When i go to my filezilla i can see the database on my spark-warehouse(root account) but i can get the data.

my database in filezilla

how can i get my database on the sparkwarehouse ?

Thank you for the help and have a nice day.

I try to restart my hdp.


问:
.NET 7 MAUI not receiving http response
I am playing around with .NET MAUI, and I got a problem. I call a rest API endpoint, and it is called, no errors (works 100% because I got response in Postman and on the SwaggerUI). But my mobile app client never receives a response. I probably miss something. Any idea is welcome.

```<code>    namespace Mobile.UI.Clients;

    public abstract class BaseClient
    {
        private readonly HttpClient httpClient;
        private readonly MobileAppSettings settings;

        private string BaseURL
        {
            get
            {
                return DeviceInfo.Platform == DevicePlatform.Android ?
                                              this.settings.AndroidBaseURL :
                                              this.settings.IosBaseURL;
            }
        }

        protected BaseClient(HttpClient httpClient, MobileAppSettings settings)
        {
            this.settings = settings;

            this.httpClient = BuildHttpClient(httpClient);
        }

        /// <summary>
        /// Creates a simple get request
        /// </summary>
        /// <typeparam name="T">The return type</typeparam>
        /// <param name="route">The route part without the base url</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected async Task<T> SendGetRequestAsync<T>(string route)
        {
            try
            {
                var uri = BuildUri(route);

                var response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("Faild to fetch data.");
                }

                var content = await SerializeResponse<T>(response.Content);
                return content;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        /// <summary>
        /// Creates a simple get request
        /// </summary>
        /// <typeparam name="T">The return type</typeparam>
        /// <param name="route">The route part without the base url</param>
        /// <param name="routParam">Rout parameter</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected async Task<T> SendGetRequestAsync<T>(string route, object routParam)
        {
            try
            {
                var uri = BuildUri(route, routParam);

                var response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("Faild to fetch data.");
                }

                var content = await SerializeResponse<T>(response.Content);
                return content;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private HttpClient BuildHttpClient(HttpClient httpClient)
        {
    #if DEBUG
            var handler = new HttpsClientHandlerService();
            httpClient = new HttpClient(handler.GetPlatformMessageHandler());
    #endif

            httpClient.BaseAddress = new Uri(BaseURL);

            httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");

            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new("application/json"));

            return httpClient;
        }

        private Uri BuildUri(string route)
        {
            return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route));
        }

        private Uri BuildUri(string route, object routParam)
        {
            return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route, $"{routParam}"));
        }

        private async Task<T> SerializeResponse<T>(HttpContent content)
        {
            var stream = await content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<T>(stream);
        }
    }

    public class PlayerClient : BaseClient, IPlayerClient
    {
        public PlayerClient(HttpClient httpClient, MobileAppSettings settings) : base(httpClient, settings)
        {}

        public async Task<List<PlayerModel>> GetAllAsync()
        {
            var path = @"players/get-all";
            return await SendGetRequestAsync<List<PlayerModel>>(path);
        }

}

    public class HttpsClientHandlerService : IHttpsClientHandlerService
    {
        public HttpMessageHandler GetPlatformMessageHandler()
        {
    #if ANDROID
                var handler = new Xamarin.Android.Net.AndroidMessageHandler();
                handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                {
                    if (cert != null && cert.Issuer.Equals("CN=localhost"))
                        return true;
                    return errors == System.Net.Security.SslPolicyErrors.None;
                };
                return handler;

    #elif IOS
                var handler = new NSUrlSessionHandler
                {
                    TrustOverrideForUrl = IsHttpsLocalhost
                };
                return handler;

    #elif WINDOWS || MACCATALYST
                return null;
    #else
            throw new PlatformNotSupportedException("Only Android, iOS, MacCatalyst, and Windows supported.");
    #endif
        }

    #if IOS
        public bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
        {
            if (url.StartsWith("https://localhost"))
                return true;
            return false;
        }
    #endif
    }
</code>```

In the android message handler I captured an error (if it is an error):

System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors | System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch

Title: .NET 7 MAUI not receiving http response

Body:
I am playing around with .NET MAUI, and I got a problem. I call a rest API endpoint, and it is called, no errors (works 100% because I got response in Postman and on the SwaggerUI). But my mobile app client never receives a response. I probably miss something. Any idea is welcome.

    namespace Mobile.UI.Clients;

    public abstract class BaseClient
    {
        private readonly HttpClient httpClient;
        private readonly MobileAppSettings settings;

        private string BaseURL
        {
            get
            {
                return DeviceInfo.Platform == DevicePlatform.Android ?
                                              this.settings.AndroidBaseURL :
                                              this.settings.IosBaseURL;
            }
        }

        protected BaseClient(HttpClient httpClient, MobileAppSettings settings)
        {
            this.settings = settings;

            this.httpClient = BuildHttpClient(httpClient);
        }

        ///
        /// Creates a simple get request
        ///
        /// <typeparam name="T">The return type</typeparam>
        /// <param name="route">The route part without the base url</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected async Task<T> SendGetRequestAsync<T>(string route)
        {
            try
            {
                var uri = BuildUri(route);

                var response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("Faild to fetch data.");
                }

                var content = await SerializeResponse<T>(response.Content);
                return content;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        ///
        /// Creates a simple get request
        ///
        /// <typeparam name="T">The return type</typeparam>
        /// <param name="route">The route part without the base url</param>
        /// <param name="routParam">Rout parameter</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected async Task<T> SendGetRequestAsync<T>(string route, object routParam)
        {
            try
            {
                var uri = BuildUri(route, routParam);

                var response = await httpClient.GetAsync(uri);

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception("Faild to fetch data.");
                }

                var content = await SerializeResponse<T>(response.Content);
                return content;

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        private HttpClient BuildHttpClient(HttpClient httpClient)
        {
    #if DEBUG
            var handler = new HttpsClientHandlerService();
            httpClient = new HttpClient(handler.GetPlatformMessageHandler());
    #endif

            httpClient.BaseAddress = new Uri(BaseURL);

            httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
            httpClient.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");

            httpClient.DefaultRequestHeaders.Accept.Clear();
            httpClient.DefaultRequestHeaders.Accept.Add(new("application/json"));

            return httpClient;
        }

        private Uri BuildUri(string route)
        {
            return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route));
        }

        private Uri BuildUri(string route, object routParam)
        {
            return new Uri(Path.Combine(BaseURL, settings.ApiVersion, route, $"{routParam}"));
        }

        private async Task<T> SerializeResponse<T>(HttpContent content)
        {
            var stream = await content.ReadAsStreamAsync();
            return await JsonSerializer.DeserializeAsync<T>(stream);
        }
    }

    public class PlayerClient : BaseClient, IPlayerClient
    {
        public PlayerClient(HttpClient httpClient, MobileAppSettings settings) : base(httpClient, settings)
        {}

        public async Task<List<PlayerModel>> GetAllAsync()
        {
            var path = @"players/get-all";
            return await SendGetRequestAsync<List<PlayerModel>>(path);
        }

}

    public class HttpsClientHandlerService : IHttpsClientHandlerService
    {
        public HttpMessageHandler GetPlatformMessageHandler()
        {
    #if ANDROID
                var handler = new Xamarin.Android.Net.AndroidMessageHandler();
                handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) =>
                {
                    if (cert != null && cert.Issuer.Equals("CN=localhost"))
                        return true;
                    return errors == System.Net.Security.SslPolicyErrors.None;
                };
                return handler;

    #elif IOS
                var handler = new NSUrlSessionHandler
                {
                    TrustOverrideForUrl = IsHttpsLocalhost
                };
                return handler;

    #elif WINDOWS || MACCATALYST
                return null;
    #else
            throw new PlatformNotSupportedException("Only Android, iOS, MacCatalyst, and Windows supported.");
    #endif
        }

    #if IOS
        public bool IsHttpsLocalhost(NSUrlSessionHandler sender, string url, Security.SecTrust trust)
        {
            if (url.StartsWith("https://localhost"))
                return true;
            return false;
        }
    #endif
    }

In the android message handler I captured an error (if it is an error):

System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors | System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch


问:
How can I work around the AWS Terraform provider's limit for loadbalancer configurations per ECS Service?
I get the following error when I attempt to create an ECS service with over 5 loadbalancer configurations. Here is my terraform:

```<code>resource "aws_ecs_service" "elastic_integrations" {
  name            = "elastic_agent"
  cluster         = aws_ecs_cluster.elastic_integrations.id
  task_definition = aws_ecs_task_definition.elastic_agent.arn
  launch_type     = "FARGATE"
  desired_count   = 1

  dynamic "load_balancer" {
    for_each = local.xxxx_mappings
    content {
      target_group_arn = aws_lb_target_group.ecs_service[load_balancer.key].arn
      container_name   = "elastic_agent"
      container_port   = load_balancer.value
    }
  }
</code>```

Here is the error:

```<code>╷
│ Error: error creating ECS service (elastic_agent): InvalidParameterException: load balancers can have at most 5 items.
│
│   with aws_ecs_service.elastic_integrations,
│   on main.tf line 12, in resource "aws_ecs_service" "elastic_integrations":
│   12: resource "aws_ecs_service" "elastic_integrations" {
│
╵
</code>```

This issue has been mentioned before in 2020 (see here) but was responded to as a limitation of the terraform provider for AWS. My question is, how can I work around this limitation in Terraform as I need more than 5 loadbalancer configurations for this ECS service.

And just to note, it is perfectly OK to have more than 5 loadbalancer configurations per ECS service if it's done via the AWS UI.

Body:
I get the following error when I attempt to create an ECS service with over 5 loadbalancer configurations. Here is my terraform:

resource "aws_ecs_service" "elastic_integrations" {
  name            = "elastic_agent"
  cluster         = aws_ecs_cluster.elastic_integrations.id
  task_definition = aws_ecs_task_definition.elastic_agent.arn
  launch_type     = "FARGATE"
  desired_count   = 1

  dynamic "load_balancer" {
    for_each = local.xxxx_mappings
    content {
      target_group_arn = aws_lb_target_group.ecs_service[load_balancer.key].arn
      container_name   = "elastic_agent"
      container_port   = load_balancer.value
    }
  }

Here is the error:

╷
│ Error: error creating ECS service (elastic_agent): InvalidParameterException: load balancers can have at most 5 items.
│
│   with aws_ecs_service.elastic_integrations,
│   on main.tf line 12, in resource "aws_ecs_service" "elastic_integrations":
│   12: resource "aws_ecs_service" "elastic_integrations" {
│
╵

This issue has been mentioned before in 2020 (see here) but was responded to as a limitation of the terraform provider for AWS. My question is, how can I work around this limitation in Terraform as I need more than 5 loadbalancer configurations for this ECS service.

And just to note, it is perfectly OK to have more than 5 loadbalancer configurations per ECS service if it's done via the AWS UI.


问:
Why is Shared Preferences plugin throwing Gradle error
I am using shared preferences 2.0.15 plugin in my flutter app.
Building linux version of the app works fine but building apk version throws the following error:

Could not download httpclient-4.5.9.jar (org.apache.httpcomponents:httpsclient:4.5.9)

Here is my build.gradle file:

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
    localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk         in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
    if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
        //}
        //kotlinOptions {
          //  jvmTarget = "11"
        //}
        // sourceCompatibility JavaVersion.VERSION_1_8
        // targetCompatibility JavaVersion.VERSION_1_8
    }

kotlinOptions {
    jvmTarget = '11'
}

sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.shopapp"
    // You can update the following values to match your application needs.
    // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
    minSdkVersion flutter.minSdkVersion
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30"
//      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.21"
      //implementation "org.jetbrains.kotlin:kotlin-reflect:1.3.50"
//    implementation "com.github.User:Repo:Tag"
} `
</code>```

PLEASE IGNORE:
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.

Body:
I am using shared preferences 2.0.15 plugin in my flutter app.
Building linux version of the app works fine but building apk version throws the following error:

Could not download httpclient-4.5.9.jar (org.apache.httpcomponents:httpsclient:4.5.9)

Here is my build.gradle file:

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
    localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk         in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
    if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
        //}
        //kotlinOptions {
          //  jvmTarget = "11"
        //}
        // sourceCompatibility JavaVersion.VERSION_1_8
        // targetCompatibility JavaVersion.VERSION_1_8
    }

kotlinOptions {
    jvmTarget = '11'
}

sourceSets {
    main.java.srcDirs += 'src/main/kotlin'
}

defaultConfig {
    // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
    applicationId "com.example.shopapp"
    // You can update the following values to match your application needs.
    // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
    minSdkVersion flutter.minSdkVersion
    targetSdkVersion flutter.targetSdkVersion
    versionCode flutterVersionCode.toInteger()
    versionName flutterVersionName
}

buildTypes {
    release {
        // TODO: Add your own signing config for the release build.
        // Signing with the debug keys for now, so `flutter run --release` works.
        signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.30"
//      implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.21"
      //implementation "org.jetbrains.kotlin:kotlin-reflect:1.3.50"
//    implementation "com.github.User:Repo:Tag"
} `

PLEASE IGNORE:
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.
It looks like your post is mostly code; please add some more details.


问:
Nextcloud log shows: "cURL error 61" - is my cURL broken?
While configuring and setting up NextCloud, I saw this show up in my logs (prettyfied with jq and exception trace snipped):

```<code>{
  "reqId": "BaJzicXwT0kJlMjnKVCb",
  "level": 2,
  "time": "2022-12-17T16:20:33+00:00",
  "remoteAddr": "",
  "user": "--",
  "app": "appstoreFetcher",
  "method": "",
  "url": "--",
  "message": "cURL error 61: Unrecognized content encoding type. libcurl understands identity content encodings. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://apps.nextcloud.com/api/v1/apps.json",
  "userAgent": "--",
  "version": "25.0.2.3",
  "exception": {
    "Exception": "GuzzleHttp\\Exception\\RequestException",
    "Message": "cURL error 61: Unrecognized content encoding type. libcurl understands identity content encodings. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://apps.nextcloud.com/api/v1/apps.json",
    "Code": 200,
    "Trace": [
</code>```

Taking a look at the headers of the address:

```<code>$ curl --head "https://apps.nextcloud.com/api/v1/apps.json"
HTTP/1.1 200 OK
Date: Sat, 17 Dec 2022 17:53:42 GMT
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Content-Length: 10534962
Vary: Accept-Encoding,Accept-Language,Cookie
Allow: GET, HEAD, OPTIONS
ETag: "2022-12-17 16:09:07.889082+00:00"
Content-Language: en
X-Frame-Options: DENY
Content-Security-Policy: form-action 'self' https://github.com; style-src 'self'; default-src 'none'; font-src 'self'; img-src *; script-src 'self'; connect-src 'self'
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: same-origin
X-Cache-Status: HIT
X-Cache-Date: Sat, 17 Dec 2022 16:14:11 GMT
</code>```

I run PHP on an OpenWrt device (FriendlyElec NanoPi R6s, 4+4 armv8 cores, 8gb ram) and I am well aware that this setup is a little funky as it is. NextCloud is executed as a www user (via php-fpm) under Caddy. The default INI settings have been off before, and I would bet they are once again.

I used phpinfo to find out the information about the installed cURL extension. Couldn't spot anything wrong though...

```<code>curl

cURL support => enabled
cURL Information => 7.86.0
Age => 9
Features
AsynchDNS => No
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => No
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => No
NTLM => No
NTLMWB => No
SPNEGO => No
SSL => Yes
SSPI => No
TLS-SRP => No
HTTP2 => Yes
GSSAPI => No
KERBEROS5 => No
UNIX_SOCKETS => No
PSL => No
HTTPS_PROXY => No
MULTI_SSL => No
BROTLI => No
Protocols => file, ftp, ftps, http, https, mqtt
Host => aarch64-openwrt-linux-gnu
SSL Version => mbedTLS/2.28.1
</code>```

Body:
While configuring and setting up NextCloud, I saw this show up in my logs (prettyfied with jq and exception trace snipped):

{
  "reqId": "BaJzicXwT0kJlMjnKVCb",
  "level": 2,
  "time": "2022-12-17T16:20:33+00:00",
  "remoteAddr": "",
  "user": "--",
  "app": "appstoreFetcher",
  "method": "",
  "url": "--",
  "message": "cURL error 61: Unrecognized content encoding type. libcurl understands identity content encodings. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://apps.nextcloud.com/api/v1/apps.json",
  "userAgent": "--",
  "version": "25.0.2.3",
  "exception": {
    "Exception": "GuzzleHttp\\Exception\\RequestException",
    "Message": "cURL error 61: Unrecognized content encoding type. libcurl understands identity content encodings. (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for https://apps.nextcloud.com/api/v1/apps.json",
    "Code": 200,
    "Trace": [

Taking a look at the headers of the address:

$ curl --head "https://apps.nextcloud.com/api/v1/apps.json"
HTTP/1.1 200 OK
Date: Sat, 17 Dec 2022 17:53:42 GMT
Server: nginx/1.18.0 (Ubuntu)
Content-Type: application/json
Content-Length: 10534962
Vary: Accept-Encoding,Accept-Language,Cookie
Allow: GET, HEAD, OPTIONS
ETag: "2022-12-17 16:09:07.889082+00:00"
Content-Language: en
X-Frame-Options: DENY
Content-Security-Policy: form-action 'self' https://github.com; style-src 'self'; default-src 'none'; font-src 'self'; img-src *; script-src 'self'; connect-src 'self'
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Referrer-Policy: same-origin
X-Cache-Status: HIT
X-Cache-Date: Sat, 17 Dec 2022 16:14:11 GMT

I run PHP on an OpenWrt device (FriendlyElec NanoPi R6s, 4+4 armv8 cores, 8gb ram) and I am well aware that this setup is a little funky as it is. NextCloud is executed as a www user (via php-fpm) under Caddy. The default INI settings have been off before, and I would bet they are once again.

I used phpinfo to find out the information about the installed cURL extension. Couldn't spot anything wrong though...

curl

cURL support => enabled
cURL Information => 7.86.0
Age => 9
Features
AsynchDNS => No
CharConv => No
Debug => No
GSS-Negotiate => No
IDN => No
IPv6 => Yes
krb4 => No
Largefile => Yes
libz => No
NTLM => No
NTLMWB => No
SPNEGO => No
SSL => Yes
SSPI => No
TLS-SRP => No
HTTP2 => Yes
GSSAPI => No
KERBEROS5 => No
UNIX_SOCKETS => No
PSL => No
HTTPS_PROXY => No
MULTI_SSL => No
BROTLI => No
Protocols => file, ftp, ftps, http, https, mqtt
Host => aarch64-openwrt-linux-gnu
SSL Version => mbedTLS/2.28.1


问:
Terminal: How to split line with a specified delimiter into multi lines
I have a line and want to split it with specified delimiter and each section has been written in one line. for example:

A,B,C,D,E

with , delimiter converted to

```<code>A
B
C
D
E
</code>```

I want do this in terminal.

Is there any extension to do it on splitting multi-lines input file?

Thanks

I use cut command but it is not suitable

Body:
I have a line and want to split it with specified delimiter and each section has been written in one line. for example:

A,B,C,D,E

with , delimiter converted to

A
B
C
D
E

I want do this in terminal.

Is there any extension to do it on splitting multi-lines input file?

Thanks

I use cut command but it is not suitable


问:
Getting a type error for API call and can't find the problem
I have a list of ingredients in a useState array. When I handleSetIngredients with the setState function I get a type error when passing to the API at getRecipes.

Fridge.jsx

```<code>import React, {useEffect, useState} from 'react'
import Recipes from '../Recipes'
import recipeApi from '../../Api/Api'

function Fridge({setFavorites, favorites}) {

  const [search, setSearch] = useState('');
  const [ingredientList, setIngredientList] = useState([])
  const [searchedIngredients, setSearchedIngredients] = useState([])
  const [recipes, setRecipes] = useState([])

  //When input changes we will update the ingredient search query
  const handleChange = (e) => {
    setSearch(e.target.value)
  }

  //this will add an ingredient to the list we have in our fridge
  const handleSetIngredients = (e) => {
    setIngredientList( (prev) => [...prev, e.target.innerText])
  }

  //this will remove an ingredient in our list
  const handleRemoveIngredients = (e) => {
    setIngredientList( (prev) => prev.filter(ele => ele !== e.target.id))
  }

  //Here we will fetch for ingredients and set the searched ingredients to an array of objs
  const handleSearch = async (search) => {
    const quer = await recipeApi
      .searchForIngredients(search);
    setSearchedIngredients(quer)
  }

  //then we fetch for recipes from our ingreidents when our list changes
  const getRecipes = async (ingredientList) => {
    const quer = await recipeApi.getByIngredients(ingredientList);
    setRecipes(quer)
  }

  //call handle search when search changes; this will update fetch ingredients
  useEffect( () => {
    if(search){
    handleSearch(search)
  }
  }, [search])

  //this will fetch recipes when ingredient list changes
  useEffect(() => {
    if(ingredientList.length > 0)
    {
      getRecipes(ingredientList);
    }
  }, [ingredientList]);

  return (
    <div className="bg-slate-900 w-screen flex flex-col lg:flex-row md:flex-row">
      <div className="flex flex-col w-full [&>*]:mt-10 [&>*]:ml-auto [&>*]:mr-auto mt-28">
        <p className="text-5xl font-semibold text-slate-200">
          What's in your fridge?
        </p>
        <form className="flex relative w-fit h-fit">
          <input
            onChange={handleChange}
            placeholder="Search ingredient"
            className="border-2 text-white bg-slate-800 w-[197px] h-[38px] p-1.5 rounded-3xl border-gray-900"
          />
          {
            <ul className="absolute top-[100%] w-full p-1 ">
              {searchedIngredients.length > 0 &&
                searchedIngredients.map((ele) => {
                  if (ele.name) {
                    return (
                      <button
                        key={ele.name}
                        onClick={handleSetIngredients}
                        className="bg-white border-b-2 m-auto first:rounded-t-lg last:rounded-b-lg w-full"
                      >
                        {ele.name}
                      </button>
                    );
                  } else {
                    return (
                      <div className="bg-white border-b-2 m-auto first:rounded-t-lg last:rounded-b-lg w-full">
                        No results...
                      </div>
                    );
                  }
                })}
            </ul>
          }
        </form>
        <div className="bg-slate-700 w-[40%] text-white p-5">
          <p className="ml-auto mr-auto w-fit pb-2">Ingredient List</p>
          <div>
            {ingredientList?.map((ing, i) => {
              return (
                <li
                  className="flex justify-between group border-t-[1px] border-slate-500 p-[3px]"
                  key={i}
                >
                  {ing}
                  <button
                    id={ing}
                    onClick={handleRemoveIngredients}
                    className="text-red-400 hidden group-hover:block"
                  >
                    X
                  </button>
                </li>
              );
            })}
          </div>
        </div>
      </div>

      {ingredientList.length > 0 && (
        <Recipes
          recipes={recipes}
          setFavorites={setFavorites}
          favorites={favorites}
          className="border-l-4 border-slate-600 w-full mt-28 flex flex-col [&>*]:ml-auto [&>*]:mr-auto"
        />
      )}
    </div>
  );
}

export default Fridge
</code>```

Api.js

```<code>const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": process.env.REACT_APP_API_KEY,
    "X-RapidAPI-Host": process.env.REACT_APP_HOST_URL
  },
};

const recipeApi = {
  getRandom: async () => {
    return await fetch(
      "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=1",
      options
    )
      .then((response) => response.json())
      .then((response) => response.recipes)
      .catch((err) => console.error(err));
  },

  getByIngredients: async (ingredientList) => {
    const querySearchIngredients = ingredientList.join().split(" ").join("");
     return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients?ingredients=${querySearchIngredients}&number=5&ranking=1`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },

  getById: async (ids) => {
    const queryIds = ids.join("%2C%20").split(" ").join("");
    return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/informationBulk?ids=${queryIds}`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },

  searchForIngredients: async (search) => {
    return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/food/ingredients/autocomplete?query=${search}&number=10`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },
};

export default recipeApi;

</code>```

I tried setting the initial value to something other than an empty array and it works. So somewhere in the process of changing the state of ingredientList is somehow changing the type.

Error

```<code>react_devtools_backend.js:4012 TypeError: Failed to fetch
    at Object.getByIngredients (:3000/static/js/bundle.js:31:18)
    at getRecipes (:3000/static/js/bundle.js:1571:73)
    at :3000/static/js/bundle.js:1585:7
    at commitHookEffectListMount (:3000/static/js/bundle.js:32214:30)
    at commitPassiveMountOnFiber (:3000/static/js/bundle.js:33707:17)
    at commitPassiveMountEffects_complete (:3000/static/js/bundle.js:33679:13)
    at commitPassiveMountEffects_begin (:3000/static/js/bundle.js:33669:11)
    at commitPassiveMountEffects (:3000/static/js/bundle.js:33659:7)
    at flushPassiveEffectsImpl (:3000/static/js/bundle.js:35544:7)
    at flushPassiveEffects (:3000/static/js/bundle.js:35496:18)
</code>```

Body:
I have a list of ingredients in a useState array. When I handleSetIngredients with the setState function I get a type error when passing to the API at getRecipes.

Fridge.jsx

import React, {useEffect, useState} from 'react'
import Recipes from '../Recipes'
import recipeApi from '../../Api/Api'

function Fridge({setFavorites, favorites}) {

  const [search, setSearch] = useState('');
  const [ingredientList, setIngredientList] = useState([])
  const [searchedIngredients, setSearchedIngredients] = useState([])
  const [recipes, setRecipes] = useState([])

  //When input changes we will update the ingredient search query
  const handleChange = (e) => {
    setSearch(e.target.value)
  }

  //this will add an ingredient to the list we have in our fridge
  const handleSetIngredients = (e) => {
    setIngredientList( (prev) => [...prev, e.target.innerText])
  }

  //this will remove an ingredient in our list
  const handleRemoveIngredients = (e) => {
    setIngredientList( (prev) => prev.filter(ele => ele !== e.target.id))
  }

  //Here we will fetch for ingredients and set the searched ingredients to an array of objs
  const handleSearch = async (search) => {
    const quer = await recipeApi
      .searchForIngredients(search);
    setSearchedIngredients(quer)
  }

  //then we fetch for recipes from our ingreidents when our list changes
  const getRecipes = async (ingredientList) => {
    const quer = await recipeApi.getByIngredients(ingredientList);
    setRecipes(quer)
  }

  //call handle search when search changes; this will update fetch ingredients
  useEffect( () => {
    if(search){
    handleSearch(search)
  }
  }, [search])

  //this will fetch recipes when ingredient list changes
  useEffect(() => {
    if(ingredientList.length > 0)
    {
      getRecipes(ingredientList);
    }
  }, [ingredientList]);

  return (

*]:mt-10 [&>*]:ml-auto [&>*]:mr-auto mt-28">

          What's in your fridge?

        <form className="flex relative w-fit h-fit">
          <input
            onChange={handleChange}
            placeholder="Search ingredient"
            className="border-2 text-white bg-slate-800 w-[197px] h-[38px] p-1.5 rounded-3xl border-gray-900"
          />
          {

              {searchedIngredients.length > 0 &&
                searchedIngredients.map((ele) => {
                  if (ele.name) {
                    return (
                      <button
                        key={ele.name}
                        onClick={handleSetIngredients}
                        className="bg-white border-b-2 m-auto first:rounded-t-lg last:rounded-b-lg w-full"
                      >
                        {ele.name}
                      </button>
                    );
                  } else {
                    return (

                        No results...

                    );
                  }
                })}

          }
        </form>

Ingredient List

            {ingredientList?.map((ing, i) => {
              return (

                  {ing}
                  <button
                    id={ing}
                    onClick={handleRemoveIngredients}
                    className="text-red-400 hidden group-hover:block"
                  >
                    X
                  </button>

              );
            })}

      {ingredientList.length > 0 && (
        <Recipes
          recipes={recipes}
          setFavorites={setFavorites}
          favorites={favorites}
          className="border-l-4 border-slate-600 w-full mt-28 flex flex-col [&>*]:ml-auto [&>*]:mr-auto"
        />
      )}

  );
}

export default Fridge

Api.js

const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": process.env.REACT_APP_API_KEY,
    "X-RapidAPI-Host": process.env.REACT_APP_HOST_URL
  },
};

const recipeApi = {
  getRandom: async () => {
    return await fetch(
      "https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/random?number=1",
      options
    )
      .then((response) => response.json())
      .then((response) => response.recipes)
      .catch((err) => console.error(err));
  },

  getByIngredients: async (ingredientList) => {
    const querySearchIngredients = ingredientList.join().split(" ").join("");
     return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/findByIngredients?ingredients=${querySearchIngredients}&number=5&ranking=1`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },

  getById: async (ids) => {
    const queryIds = ids.join("%2C%20").split(" ").join("");
    return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/informationBulk?ids=${queryIds}`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },

  searchForIngredients: async (search) => {
    return await fetch(
      `https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/food/ingredients/autocomplete?query=${search}&number=10`,
      options
    )
      .then((response) => response.json())
      .then((response) => response)
      .catch((err) => console.error(err));
  },
};

export default recipeApi;

I tried setting the initial value to something other than an empty array and it works. So somewhere in the process of changing the state of ingredientList is somehow changing the type.

Error

react_devtools_backend.js:4012 TypeError: Failed to fetch
    at Object.getByIngredients (:3000/static/js/bundle.js:31:18)
    at getRecipes (:3000/static/js/bundle.js:1571:73)
    at :3000/static/js/bundle.js:1585:7
    at commitHookEffectListMount (:3000/static/js/bundle.js:32214:30)
    at commitPassiveMountOnFiber (:3000/static/js/bundle.js:33707:17)
    at commitPassiveMountEffects_complete (:3000/static/js/bundle.js:33679:13)
    at commitPassiveMountEffects_begin (:3000/static/js/bundle.js:33669:11)
    at commitPassiveMountEffects (:3000/static/js/bundle.js:33659:7)
    at flushPassiveEffectsImpl (:3000/static/js/bundle.js:35544:7)
    at flushPassiveEffects (:3000/static/js/bundle.js:35496:18)


问:
How Scenario Use Name Space in Sass
How scenario we can use nesting name space in scss? What is the reasoning?

I was share nesting name space example

```<code>.nesting-namespace-properties {
border: {
top: 1px dashed $color7;
right: 1px dotted $color5;
bottom: 2px solid $color8;
left: 1px solid $color4;
}
}
</code>```

Title: How Scenario Use Name Space in Sass

Body:
How scenario we can use nesting name space in scss? What is the reasoning?

I was share nesting name space example

.nesting-namespace-properties {
border: {
top: 1px dashed $color7;
right: 1px dotted $color5;
bottom: 2px solid $color8;
left: 1px solid $color4;
}
}