问:
Access button class in javascript
I have a button class that is placed inside an iframe. Problem is that this button's class has such a long name and I do not understand how to reference it in my script.

```<code><button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button"></button>
</code>```

I am using my javascript to reference this class as:

```<code>document.querySelector("iframe").contentWindow.document.querySelector(".PDF-dmzpd5z6ckdkxkn8").click();
</code>```

The above code does not work. Do I have to provide the complete class name for reference?

I am on right track because I have another button that looks like this:

```<code><button class="PDF-tdsfethgr51stg Next-Button Next-Previous-Button" title="Next" aria-label="Next" type="button"></button>
</code>```

And I can easily call/reference it via:

```<code>document.querySelector("iframe").contentWindow.document.querySelector(".PDF-tdsfethgr51stg").click();
</code>```

答:
If selecting with class doesn't work, you can try to select with title attribute:</p>
```<code>document.querySelector('button[title="SignUp"]');
</code>```

Title: Access button class in javascript

Body:
I have a button class that is placed inside an iframe. Problem is that this button's class has such a long name and I do not understand how to reference it in my script.

<button class="PDF-dmzpd5z6ckdkxkn8 PDF-5rbqp8nfgh6e11 PDF-tma5quj Toolbar-Button Tool-Button" title="SignUp" aria-label="myButton001" type="button"></button>

I am using my javascript to reference this class as:

document.querySelector("iframe").contentWindow.document.querySelector(".PDF-dmzpd5z6ckdkxkn8").click();

The above code does not work. Do I have to provide the complete class name for reference?

I am on right track because I have another button that looks like this:

<button class="PDF-tdsfethgr51stg Next-Button Next-Previous-Button" title="Next" aria-label="Next" type="button"></button>

And I can easily call/reference it via:

document.querySelector("iframe").contentWindow.document.querySelector(".PDF-tdsfethgr51stg").click();

Body:
If selecting with class doesn't work, you can try to select with title attribute:

document.querySelector('button[title="SignUp"]');


来源: stackexchange

问:
How to create a column in Pandas with distance from coordinates using GeoPy
I have this df:

```<code>    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844
</code>```

And the following coordinates:

```<code>coords_2 = (-25.236632,  -56.835262)
</code>```

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

```<code>import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)
</code>```

Output:

```<code>4691.07078306837
</code>```

So I want to apply this same logic to a Dataframe.

Thanks

答:
You could simply apply a lambda function to the existing dataframe

```<code>df['distance'] = df.apply(lambda x: geopy.distance.distance(x.tolist(), coords_2).km,
                          axis=1)
</code>```

you should get:

```<code>   latitude_1  longitude_1    distance
0  -25.294871   -56.992654   17.116773
1  -24.946374   -57.384543   64.062048
2  -24.835273   -53.825342  306.992429
3  -24.153553   -54.363844  277.379381
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this df:

    latitude_1  longitude_1
0   -25.294871  -56.992654
1   -24.946374  -57.384543
2   -24.835273  -53.825342
3   -24.153553  -54.363844

And the following coordinates:

coords_2 = (-25.236632,  -56.835262)

So I want to create a 3rd column in the df that shows the distance between each row with coords_2.

If I try to do it without using Dataframes, it works (here I'm using random numbers):

import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (43.263845, -42.2637377)

print(geopy.distance.distance(coords_1, coords_2).km)

Output:

4691.07078306837

So I want to apply this same logic to a Dataframe.

Thanks

Body:
You could simply apply a lambda function to the existing dataframe

df['distance'] = df.apply(lambda x: geopy.distance.distance(x.tolist(), coords_2).km,
                          axis=1)

you should get:

   latitude_1  longitude_1    distance
0  -25.294871   -56.992654   17.116773
1  -24.946374   -57.384543   64.062048
2  -24.835273   -53.825342  306.992429
3  -24.153553   -54.363844  277.379381


问:
How to create one line plot per color series in Observable Plot?
Description:

I am playing around with Observable Plot an really like how easy it is to set up simple plots.

Now I have a little "more advanced" chart that I want to plot and need help.

In my data, I have multiple temp (temperature) readings recorded at a certain timestamp.
Each reading comes from a sensor, and each sensor is attached to a certain device (multiple sensors (e.g., 1-3) can be attached to a single device (e.g., 2)).
Thus, one data point might look like the following (see bottom script for a full minimal workabel example):

```<code>{
  timestamp: 1,
  device: 1,
  sensor: 1,
  temp: 20
}
</code>```

Currently, I dot plot this data, facet it based on the sensor, and give a color the each (device, sensor) pair series (just run below snippet to get a better feeling).

Problem:

I now would like to connect all dots of the same color with a black line.
I marked the problematic line with // HERE I NEED HELP in the snippet.
I assume that I somehow have to group data based on device and sensor to achieve a similar grouping to the color, but I sadly have no idea how to achieve this and hope that you can help!

const plotTestTemperatures = function(data) {
  const div = document.getElementById('temp-chart-test')
  div.appendChild(Plot.plot({
    color: {
      type: "ordinal",
      scheme: "category10",
      legend: true
    },
    facet: { data: data, x: "device", grid: true,},
    grid: true,
    marks: [
      Plot.frame(),
      Plot.dot(data, {x: "timestamp", y: "temp", r: 4, opacity: 0.8, fill: d => `Sensor ${d.sensor} of device ${d.device}` }),
      // HERE I NEED HELP
      // does not yet work, connects all dots independent of color
      // Plot.line(data, {x: "timestamp", y: "temp", opacity: 0.8, stroke: "black" })
    ],
  }));
}

// call with test data
plotTestTemperatures([
  {
    timestamp: 1,
    device: 1,
    sensor: 1,
    temp: 20
  },
  {
    timestamp: 2,
    device: 1,
    sensor: 1,
    temp: 21
  },
  {
    timestamp: 3,
    device: 1,
    sensor: 1,
    temp: 22
  },
  {
    timestamp: 1,
    device: 1,
    sensor: 2,
    temp: 20.1
  },
  {
    timestamp: 2,
    device: 1,
    sensor: 2,
    temp: 21.3
  },
  {
    timestamp: 3,
    device: 1,
    sensor: 2,
    temp: 22.5
  },
  {
    timestamp: 1,
    device: 2,
    sensor: 1,
    temp: 18
  },
  {
    timestamp: 2,
    device: 2,
    sensor: 1,
    temp: 19
  },
  {
    timestamp: 3,
    device: 2,
    sensor: 1,
    temp: 20
  },
  {
    timestamp: 1,
    device: 2,
    sensor: 2,
    temp: 17.8
  },
  {
    timestamp: 2,
    device: 2,
    sensor: 2,
    temp: 19.1
  },
  {
    timestamp: 3,
    device: 2,
    sensor: 2,
    temp: 20.1
  },
])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
    <meta name=”robots” content=”noindex”>
    <meta charset="UTF-8">
    <title>Home Automation</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@observablehq/plot@0.4"></script>
</head>

<body>
    <div id="app">
        <h1>Home Automation</h1>
        <div id="temp-chart-test"></div>
    </div>
</body>
</html></code>```

(cross-posted to the ObservableHQ forum)

答:
I think what you want is

z: (d) => `Sensor ${d.sensor} of device ${d.device}`,
```

Body:
Description:

I am playing around with Observable Plot an really like how easy it is to set up simple plots.

Now I have a little "more advanced" chart that I want to plot and need help.

In my data, I have multiple temp (temperature) readings recorded at a certain timestamp.
Each reading comes from a sensor, and each sensor is attached to a certain device (multiple sensors (e.g., 1-3) can be attached to a single device (e.g., 2)).
Thus, one data point might look like the following (see bottom script for a full minimal workabel example):

{
  timestamp: 1,
  device: 1,
  sensor: 1,
  temp: 20
}

Currently, I dot plot this data, facet it based on the sensor, and give a color the each (device, sensor) pair series (just run below snippet to get a better feeling).

Problem:

I now would like to connect all dots of the same color with a black line.
I marked the problematic line with // HERE I NEED HELP in the snippet.
I assume that I somehow have to group data based on device and sensor to achieve a similar grouping to the color, but I sadly have no idea how to achieve this and hope that you can help!

const plotTestTemperatures = function(data) {
  const div = document.getElementById('temp-chart-test')
  div.appendChild(Plot.plot({
    color: {
      type: "ordinal",
      scheme: "category10",
      legend: true
    },
    facet: { data: data, x: "device", grid: true,},
    grid: true,
    marks: [
      Plot.frame(),
      Plot.dot(data, {x: "timestamp", y: "temp", r: 4, opacity: 0.8, fill: d => `Sensor ${d.sensor} of device ${d.device}` }),
      // HERE I NEED HELP
      // does not yet work, connects all dots independent of color
      // Plot.line(data, {x: "timestamp", y: "temp", opacity: 0.8, stroke: "black" })
    ],
  }));
}

// call with test data
plotTestTemperatures([
  {
    timestamp: 1,
    device: 1,
    sensor: 1,
    temp: 20
  },
  {
    timestamp: 2,
    device: 1,
    sensor: 1,
    temp: 21
  },
  {
    timestamp: 3,
    device: 1,
    sensor: 1,
    temp: 22
  },
  {
    timestamp: 1,
    device: 1,
    sensor: 2,
    temp: 20.1
  },
  {
    timestamp: 2,
    device: 1,
    sensor: 2,
    temp: 21.3
  },
  {
    timestamp: 3,
    device: 1,
    sensor: 2,
    temp: 22.5
  },
  {
    timestamp: 1,
    device: 2,
    sensor: 1,
    temp: 18
  },
  {
    timestamp: 2,
    device: 2,
    sensor: 1,
    temp: 19
  },
  {
    timestamp: 3,
    device: 2,
    sensor: 1,
    temp: 20
  },
  {
    timestamp: 1,
    device: 2,
    sensor: 2,
    temp: 17.8
  },
  {
    timestamp: 2,
    device: 2,
    sensor: 2,
    temp: 19.1
  },
  {
    timestamp: 3,
    device: 2,
    sensor: 2,
    temp: 20.1
  },
])

    <meta name=”robots” content=”noindex”>
    <meta charset="UTF-8">
    <title>Home Automation</title>

Home Automation

(cross-posted to the ObservableHQ forum)


问:
Find one character in a string of any number of characters and return True or False
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.</p>
```<code>def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True
</code>```

答:
Maybe I'm missing something but Python's in operator does this out the box.

```<code>if single_character in any_length:
    return True
else:
    return False
</code>```

Body:
I'm having trouble returning the correct Boolean value back after checking for all occurrences of a single letter in a string of any length. If the single letter is in the string, I want it to return True. If the single letter is not in the string, I want it to return False. However, when I run it in python, it is just returning back only True or only False and is not accurately checking if the single letter is in the word.

def contains_char(any_length: str, single_character: str) -> bool:
    """A way to find one character in a word of any length."""
    assert len(single_character) == 1
    any_length = ""
    single_character = ""
    check_character: bool = False
    i: int = 0
    while i < len(any_length):
        if any_length[i] == single_character[0]:
            check_character is True
        else:
            i += 1
            alternative_char: int = 0
            while check_character is not True and i < len(any_length):
                if any_length[alternative_char] == single_character[0]:
                    check_character == True
                else:
                    alternative_char += 1
    if check_character is not False:
        return False
    else:
        return True

Body:
Maybe I'm missing something but Python's in operator does this out the box.

if single_character in any_length:
    return True
else:
    return False


问:
Django - button to remove row in sqlite3
I have a question.. I got a Django Application with a mailbox that shows a list with all the mails and their importance (priority to answer). clicking the button "Manage" goes to a view of a mail message.

Now I also want to add a "delete" button that will delete this email in the list aka the row from the sqlite3 database.

I have tried multiple things, because I saw this on multiple forums. My problem is that I'm quite new to Django and I don't know which answers I can combine with what I already have in my code.

This is what I have now (it doesn't work as I'm still trying to find working solutions)

mailindex.html:

```<code><form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
    <div class="form-group">
        <a href="{% url 'core:mail' mail.id %}" class="btn btn-secondary btn-sm">Manage</a>
        <button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button>
    </div>
</form>
</code>```

views.py

```<code>class MailboxView(generic.ListView):
    extra_context = {"mailbox_page": "active"}
    model = MailMessage
    context_object_name = 'mails'
    template_name = 'core/mailbox/mailindex.html'

    def post(self, request):
        # if 'deletemail' in self.request.POST:
        if request.POST.get('deletemail'):
            mail = MailMessage.objects.get(pk=13)
            mail.delete()
            return HttpResponseRedirect(self.request.path_info)
</code>```

EDIT:
I am a bit further: it now works that the button deletes email with ID 13... How can I send the mail.id to my function in views.py?

答:
Django will not trigger the delete_mail_listing, or any other method except the ones that are in the code flow of the ListView.

Probably the most elegant way to do this is working with a DeleteView:

```<code>from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import <strong>DeleteView</strong>

class MailMessageDeleteView(LoginRequired, <strong>DeleteView</strong>):
    model = MailMessage
    success_url = reverse_lazy('mailbox')</code>```

In the urls.py, you can then register this view:

```<code>urlpatterns = [
    path('', login_required(views.IndexView.as_view()), name='index'),
    path('mailbox', login_required(views.MailboxView.as_view()), name='mailbox'),
    path('mailbox/delete/<strong><int:pk></strong>/', views.MailMessageDeleteView.as_view(), name='delete')
]</code>```

and in the template you then submit to the MailMessageDeleteView:

```<code><form  method="POST" action="<strong>{% url 'delete' pk=mail.pk %}</strong>">
    {% csrf_token %}
    <button type="submit" class="btn btn-secondary btn-sm">Delete</button>
</form></code>```

Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].

Body:
I have a question.. I got a Django Application with a mailbox that shows a list with all the mails and their importance (priority to answer). clicking the button "Manage" goes to a view of a mail message.

Now I also want to add a "delete" button that will delete this email in the list aka the row from the sqlite3 database.

I have tried multiple things, because I saw this on multiple forums. My problem is that I'm quite new to Django and I don't know which answers I can combine with what I already have in my code.

This is what I have now (it doesn't work as I'm still trying to find working solutions)

mailindex.html:

<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}

        Manage
        <button type="submit" name="deletemail" value="deletemail" class="btn btn-secondary btn-sm">Delete</button>

</form>

views.py

class MailboxView(generic.ListView):
    extra_context = {"mailbox_page": "active"}
    model = MailMessage
    context_object_name = 'mails'
    template_name = 'core/mailbox/mailindex.html'

    def post(self, request):
        # if 'deletemail' in self.request.POST:
        if request.POST.get('deletemail'):
            mail = MailMessage.objects.get(pk=13)
            mail.delete()
            return HttpResponseRedirect(self.request.path_info)

EDIT:
I am a bit further: it now works that the button deletes email with ID 13... How can I send the mail.id to my function in views.py?

Body:
Django will not trigger the delete_mail_listing, or any other method except the ones that are in the code flow of the ListView.

Probably the most elegant way to do this is working with a DeleteView:

from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.views.generic import DeleteView

class MailMessageDeleteView(LoginRequired, DeleteView):
    model = MailMessage
    success_url = reverse_lazy('mailbox')

In the urls.py, you can then register this view:

urlpatterns = [
    path('', login_required(views.IndexView.as_view()), name='index'),
    path('mailbox', login_required(views.MailboxView.as_view()), name='mailbox'),
    path('mailbox/delete/<int:pk>/', views.MailMessageDeleteView.as_view(), name='delete')
]

and in the template you then submit to the MailMessageDeleteView:

<form  method="POST" action="{% url 'delete' pk=mail.pk %}">
    {% csrf_token %}
    <button type="submit" class="btn btn-secondary btn-sm">Delete</button>
</form>

Note: You can limit views to a class-based view to authenticated users with the
LoginRequiredMixin mixin [Django-doc].


问:
How to get specific values from a dictionary using list comprehension and modify them?
Can someone help and kindly advise how Can I get specific values from this dictionary (Using list comprehension) and

square the values only,

change every string value, so it starts with upper case?

```<code>items_list = {'a': 3, 'b':6, 'c': 'short', 'h': 'example', 'p': 77}
</code>```

So, the output needs to be:

```<code>9, 36, 5929
Short, Example
</code>```

答:
yes, you need to iterate through the dictionary and check if the value is an int then square it and if it is not capitalize it

```<code>result = []
for key, value in dictionary.items()
    if type(value) is int:
        result.append(value**2)
    else:
        result.append(value.capitalize())
print(result)
</code>```

this should print the desired output

Body:
Can someone help and kindly advise how Can I get specific values from this dictionary (Using list comprehension) and

square the values only,

change every string value, so it starts with upper case?

items_list = {'a': 3, 'b':6, 'c': 'short', 'h': 'example', 'p': 77}

So, the output needs to be:

9, 36, 5929
Short, Example

Body:
yes, you need to iterate through the dictionary and check if the value is an int then square it and if it is not capitalize it

result = []
for key, value in dictionary.items()
    if type(value) is int:
        result.append(value**2)
    else:
        result.append(value.capitalize())
print(result)

this should print the desired output


问:
Convert RGB to RGBA at 0.9 alpha in string
I need to take the color gradient and dynamically change rgb to rgba and add 0.9 alpha, or some other number. Of course div id="gradient" can have more than three rgb and rgba colors. I tried replace ((')', ', 0.9)'). Replace ('rgb', 'rgba'); but it does not work.  How do I do this?

The result should look like:

linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

function myFunction() {
  var gradient = document.getElementById("gradient").style.background;
  document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gradient" style="background: linear-gradient(
90deg
, rgba(215, 45, 45, 0.7) 11%, rgb(73, 45, 215) 45%, rgba(45, 215, 65, 0.5) 79%);"></div>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p></code>```

答:
To replace directly in the style, you could use the code below. However, if possible, you should instead have the different styles in a css file then just switch the whole element style (ex. gradient-idle to gradient-clicked or whatever your needs are) on click.

function myFunction() {
    var gradient = document.getElementById("gradient")
        .style
        .background
        .replace(/rgb\([0-9]{1,3},\s[0-9]{1,3},\s[0-9]{1,3}/, "$&, 0.75") // put another alpha here instead of 0.75
        .replace("rgb(", "rgba("); // then replace rgb( with rgba(

    document.getElementById("demo").innerHTML = gradient;
    document.getElementById("demo").style.background = gradient;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="gradient" style="
    background: linear-gradient(90deg,
    rgba(205, 55, 55, 0.7) 11%,
    rgb(80, 55, 205) 45%,
    rgba(55, 205, 73, 0.5) 79%);"></div>

<button onclick="myFunction()">Click me</button>
<p id="demo"></p></code>```

Body:
I need to take the color gradient and dynamically change rgb to rgba and add 0.9 alpha, or some other number. Of course div id="gradient" can have more than three rgb and rgba colors. I tried replace ((')', ', 0.9)'). Replace ('rgb', 'rgba'); but it does not work.  How do I do this?

The result should look like:

linear-gradient(90deg, rgba(205, 55, 55, 0.7) 11%, rgba(80, 55, 205, 0.9) 45%, rgba(55, 205, 73, 0.5) 79%)

function myFunction() {
  var gradient = document.getElementById("gradient").style.background;
  document.getElementById("demo").innerHTML = gradient.replace(')', ', 0.9)').replace('rgb', 'rgba');
}

<button onclick="myFunction()">Click me</button>

Body:
To replace directly in the style, you could use the code below. However, if possible, you should instead have the different styles in a css file then just switch the whole element style (ex. gradient-idle to gradient-clicked or whatever your needs are) on click.

function myFunction() {
    var gradient = document.getElementById("gradient")
        .style
        .background
        .replace(/rgb\([0-9]{1,3},\s[0-9]{1,3},\s[0-9]{1,3}/, "$&, 0.75") // put another alpha here instead of 0.75
        .replace("rgb(", "rgba("); // then replace rgb( with rgba(

    document.getElementById("demo").innerHTML = gradient;
    document.getElementById("demo").style.background = gradient;
}

<div id="gradient" style="
    background: linear-gradient(90deg,
    rgba(205, 55, 55, 0.7) 11%,
    rgb(80, 55, 205) 45%,
    rgba(55, 205, 73, 0.5) 79%);"></div>

<button onclick="myFunction()">Click me</button>
<p id="demo"></p>


问:
Android Compose not refresh with viewModel uiState
I am doing a simple app in compose in order to learn in, the app has two viewModels, ItemListViewModel that shows a list of items and ItemCreateViewModel that let you create the item, items are stored in Room.

My issue is that when I open the app the list is shown, but after I open the detail and create a new Item, going back the the first (ItemListViewModel) the list is not updated.

```<code>@HiltViewModel
class ItemListViewModel
@Inject
constructor(private val itemRepository: ItemRepository) : ViewModel() {

    var uiState by mutableStateOf(value = ItemListState(state = State.LOADING))
        private set

    init {
        viewModelScope.launch(Dispatchers.IO) {
            itemRepository.fetchItems()
                .distinctUntilChanged()
                .collect { items ->
                    uiState = uiState.copy(
                        state = State.IDLE,
                        items = if (items.isNullOrEmpty()) emptyList() else items
                    )
                }
        }
    }
</code>```

and here the Compose view

```<code>@Composable
fun ItemList(
    viewModel: ItemListViewModel,
    navController: NavController
) {

    val items = viewModel.uiState.items
    ShowItems(items)  // <--- this is not called

}

</code>```

this is the repository fun

```<code>fun fetchItems(): Flow<List<ItemEntity>>
</code>```

If I kill the app and restart it, I can see the new created item.

答:
Your list doesn't get refreshed because your coroutine gets canceled when navigating to your CreateMedicineScreen screen. When you go back to your MedicineList screen, the init doesn't get called (since it's the same ViewModel instance). You could expose the refresh as a public method from your ViewModel (as you started in your code) and call it from your composable using a side-effect.

```<code>@Composable
fun MedicineList(
    viewModel: MedicineListViewModel,
    navController: NavController
) {

    LaunchedEffect(Unit) {
        viewModel.fetchMedicines()
    }

    val medicines = viewModel.uiState.medicines
    ShowMedicines(medicines) {
        navController.navigate(NEW_MEDICINE_ROUTE)
    }
}
</code>```

When you'll pop back to your screen, MedicineList will recompose and execute once the fetch method.

As a bonus, I've noticed you had an issue with your navigation back when saving from the CreateMedicineScreen screen. It's because you're trying to navigate from a composable. It's also specified in the documentation

You should only call navigate() as part of a callback and not as part of your composable itself, to avoid calling navigate() on every recomposition.

You could use a side effect here as well:

```<code>LaunchedEffect(key1 = Unit) {
    navController.popBackStack()
}
</code>```

Body:
I am doing a simple app in compose in order to learn in, the app has two viewModels, ItemListViewModel that shows a list of items and ItemCreateViewModel that let you create the item, items are stored in Room.

My issue is that when I open the app the list is shown, but after I open the detail and create a new Item, going back the the first (ItemListViewModel) the list is not updated.

@HiltViewModel
class ItemListViewModel
@Inject
constructor(private val itemRepository: ItemRepository) : ViewModel() {

    var uiState by mutableStateOf(value = ItemListState(state = State.LOADING))
        private set

    init {
        viewModelScope.launch(Dispatchers.IO) {
            itemRepository.fetchItems()
                .distinctUntilChanged()
                .collect { items ->
                    uiState = uiState.copy(
                        state = State.IDLE,
                        items = if (items.isNullOrEmpty()) emptyList() else items
                    )
                }
        }
    }

and here the Compose view

@Composable
fun ItemList(
    viewModel: ItemListViewModel,
    navController: NavController
) {

    val items = viewModel.uiState.items
    ShowItems(items)  // <--- this is not called

}

this is the repository fun

fun fetchItems(): Flow<List<ItemEntity>>

If I kill the app and restart it, I can see the new created item.

Body:
Your list doesn't get refreshed because your coroutine gets canceled when navigating to your CreateMedicineScreen screen. When you go back to your MedicineList screen, the init doesn't get called (since it's the same ViewModel instance). You could expose the refresh as a public method from your ViewModel (as you started in your code) and call it from your composable using a side-effect.

@Composable
fun MedicineList(
    viewModel: MedicineListViewModel,
    navController: NavController
) {

    LaunchedEffect(Unit) {
        viewModel.fetchMedicines()
    }

    val medicines = viewModel.uiState.medicines
    ShowMedicines(medicines) {
        navController.navigate(NEW_MEDICINE_ROUTE)
    }
}

When you'll pop back to your screen, MedicineList will recompose and execute once the fetch method.

As a bonus, I've noticed you had an issue with your navigation back when saving from the CreateMedicineScreen screen. It's because you're trying to navigate from a composable. It's also specified in the documentation

You should only call navigate() as part of a callback and not as part of your composable itself, to avoid calling navigate() on every recomposition.

You could use a side effect here as well:

LaunchedEffect(key1 = Unit) {
    navController.popBackStack()
}


问:
UE4. Widget component doesn't show up when its outer is controller
As it's said, in UE 4.27 widget component doesn't show up when its outer is player controller. But in 4.18 version it worked.

Could you please explain why ?

And how ( if it's possible ) can I make it work in 4.27 ?

Widget is set in the widget component.

To reproduce:

.h:

```<code>UPROPERTY(EditDefaultsOnly)
TSubclassOf<UComicFXWidgetComponent> ComicWidgetClass;

UComicFXWidgetComponent* NewComponent;
</code>```

My .cpp code that does work:

"BeginPlay":

```<code>// If I change "this" with PlayerController ref then it will not work
NewComponent = NewObject<UComicFXWidgetComponent>(this, ComicWidgetClass);
NewComponent->RegisterComponent();
</code>```

"InteractButtonPressed":

```<code>NewComponent->AttachToComponent(equippedWeapon_->mesh_, FAttachmentTransformRules::SnapToTargetNotIncludingScale, TEXT("DamageSocket"));
</code>```

My .cpp code that does NOT work:

"BeginPlay":

```<code>APlayerController* PC = UGameplayStatics::GetPlayerController(this, 0);
NewComponent = NewObject<UComicFXWidgetComponent>(PC, ComicWidgetClass); // "this" replaced with "PC"
NewComponent->RegisterComponent();
</code>```

"InteractButtonPressed":

```<code>NewComponent->AttachToComponent(equippedWeapon_->mesh_, FAttachmentTransformRules::SnapToTargetNotIncludingScale, TEXT("DamageSocket"));
</code>```

答:
Okay. The answer is:

APlayerController derives from AController. And AController in it's constructor calls SetHidden(true); and it affects it's children ( or actors whose outer is the controller ).

To solve just add in your Controller constructor:

```<code>SetActorHiddenInGame(false);
</code>```

Body:
As it's said, in UE 4.27 widget component doesn't show up when its outer is player controller. But in 4.18 version it worked.

Could you please explain why ?

And how ( if it's possible ) can I make it work in 4.27 ?

Widget is set in the widget component.

To reproduce:

.h:

UPROPERTY(EditDefaultsOnly)
TSubclassOf<UComicFXWidgetComponent> ComicWidgetClass;

UComicFXWidgetComponent* NewComponent;

My .cpp code that does work:

"BeginPlay":

// If I change "this" with PlayerController ref then it will not work
NewComponent = NewObject<UComicFXWidgetComponent>(this, ComicWidgetClass);
NewComponent->RegisterComponent();

"InteractButtonPressed":

NewComponent->AttachToComponent(equippedWeapon_->mesh_, FAttachmentTransformRules::SnapToTargetNotIncludingScale, TEXT("DamageSocket"));

My .cpp code that does NOT work:

"BeginPlay":

APlayerController* PC = UGameplayStatics::GetPlayerController(this, 0);
NewComponent = NewObject<UComicFXWidgetComponent>(PC, ComicWidgetClass); // "this" replaced with "PC"
NewComponent->RegisterComponent();

"InteractButtonPressed":

NewComponent->AttachToComponent(equippedWeapon_->mesh_, FAttachmentTransformRules::SnapToTargetNotIncludingScale, TEXT("DamageSocket"));

Body:
Okay. The answer is:

APlayerController derives from AController. And AController in it's constructor calls SetHidden(true); and it affects it's children ( or actors whose outer is the controller ).

To solve just add in your Controller constructor:

SetActorHiddenInGame(false);


问:
Using paste and sum inside a for-loop
I need to compare a character string to multiple others and tried to do it the following way:

```<code>empty = character(0)
ps_2 = c("h2","h3")
ps_3 = c("h3", "h4")
visible = ("h2")

i = 2
ps_t = empty
ps_t <- append(ps_t, sum(visible %in% paste("ps_", i, sep="")))
</code>```

With the intention to write a loop instead of i = 2, in order to cycle trough ps_2,ps_3,...

However I think it's not working since the paste() command returns a string instead of the character string with the name: ps_2.
How can I fix this?

Thanks for the time and effort!

Kind regards,

A fellow datafanatic!

答:
You can use eval in R to convert the string to a variable name. You can find the solution here.

Here's what your code will look like:

```<code>ps_t <- c(0, (sum(visible %in% eval(parse(text = paste("ps_", i, sep=""))))))
</code>```

It will give you a numeric vector.

OR
You can use get.

```<code>ps_t <- append(0, sum(visible %in% get(paste("ps_", i, sep = ""))))
ps_t
</code>```

Title: Using paste and sum inside a for-loop

Body:
I need to compare a character string to multiple others and tried to do it the following way:

empty = character(0)
ps_2 = c("h2","h3")
ps_3 = c("h3", "h4")
visible = ("h2")

i = 2
ps_t = empty
ps_t <- append(ps_t, sum(visible %in% paste("ps_", i, sep="")))

With the intention to write a loop instead of i = 2, in order to cycle trough ps_2,ps_3,...

However I think it's not working since the paste() command returns a string instead of the character string with the name: ps_2.
How can I fix this?

Thanks for the time and effort!

Kind regards,

A fellow datafanatic!

Body:
You can use eval in R to convert the string to a variable name. You can find the solution here.

Here's what your code will look like:

ps_t <- c(0, (sum(visible %in% eval(parse(text = paste("ps_", i, sep=""))))))

It will give you a numeric vector.

OR
You can use get.

ps_t <- append(0, sum(visible %in% get(paste("ps_", i, sep = ""))))
ps_t


答:
in keyword uses linear search and returns boolean value O(n).

def contains_char(any_length: str, single_character: str) -> bool:
    return single_character in str
```
<p>Linear search follows</p>
<pre class="lang-py prettyprint-override"><code>def contains_char(any_length: str, single_character: str) -> bool:
    # For each loop iterates through each character in string
    for char in str:
        if char == str:
            return True
    return False
</code>```

Title: Find one character in a string of any number of characters and return True or False

Body:
in keyword uses linear search and returns boolean value O(n).

def contains_char(any_length: str, single_character: str) -> bool:
    return single_character in str

Linear search follows

def contains_char(any_length: str, single_character: str) -> bool:
    # For each loop iterates through each character in string
    for char in str:
        if char == str:
            return True
    return False


问:
Closest subsequent index for a specified value
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)
```
<p>I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.</p>
<p>For instance,</p>
<pre class="lang-r prettyprint-override"><code>f(int, 0)
# [1] 2 1 0 2 1 0 0 NA
</code>```

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA
```
<p>This should also work for character vectors:</p>
<pre class="lang-r prettyprint-override"><code>char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0
</code>```

答:
Here f is defined as a recursive function that calls itself over shorter tails of the lookup vector:

f <- function(lookup,val ) {
  ind <- which(lookup == val)[1] -1
  if (length(lookup) > 1) {
    c(ind, f(lookup[-1], val))
  } else {
    ind
  }
}
```

Body:
Consider a vector:

int = c(1, 1, 0, 5, 2, 0, 0, 2)

I'd like to get the closest subsequent index (not the difference) for a specified value. The first parameter of the function should be the vector, while the second should be the value one wants to see the closest subsequent elements.

For instance,

f(int, 0)
# [1] 2 1 0 2 1 0 0 NA

Here, the first element of the vector (1) is two positions away from the first subsequent 0, (3 - 1 = 2), so it should return 2. Then the second element is 1 position away from a 0 (2 - 1 = 1). When there is no subsequent values that match the specified value, return NA (here it's the case for the last element, because no subsequent value is 0).

Other examples:

f(int, 1)
# [1] 0 0 NA NA NA NA NA NA

f(int, 2)
# [1] 4 3 2 1 0 2 1 0

f(int, 3)
# [1] NA NA NA NA NA NA NA NA

This should also work for character vectors:

char = c("A", "B", "C", "A", "A")

f(char, "A")
# [1] 0 2 1 0 0


问:
Can I style an image's ALT text with CSS?
I have a dark blue page and when the image is loading (or missing) the ALT text is black and difficult to read (in FF).

Could I style it (with CSS) to be white?

答:
You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:

```

In the above example, the alt text will be black. However with the color:white the alt text is white.

ContentLicense: CC BY-SA 3.0

Body:
You cant style the alt attribute directly in css. However the alt will inherit the styles of the item the alt is on or what is inherited by its parent:

    <div style="background-color:black; height: 50px; width: 50px; color:white;">
    <img src="ouch" alt="here i am"/>
    <div>

In the above example, the alt text will be black. However with the color:white the alt text is white.


问:
module 'discord' has no attribute 'Intents' error
I am trying to code a discord bot but when I run the program it gives the error

Traceback (most recent call last):
File "c:/Users/phara/Documents/GitHub/RayzeBot/bot.py", line 41, in
intents = discord.Intents.default()
AttributeError: module 'discord' has no attribute 'Intents'

```<code>import discord, asyncio, os, platform, sys
from discord.ext.commands import Bot
from discord.ext import commands
import time
import random
if not os.path.isfile("config.py"):
    sys.exit("'config.py' not found! Please add it and try again.")
else:
    import config

"""
Setup bot intents (events restrictions)
For more information about intents, please go to the following websites:
https://discordpy.readthedocs.io/en/latest/intents.html
https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents

Default Intents:
intents.messages = True
intents.reactions = True
intents.guilds = True
intents.emojis = True
intents.bans = True
intents.guild_typing = False
intents.typing = False
intents.dm_messages = False
intents.dm_reactions = False
intents.dm_typing = False
intents.guild_messages = True
intents.guild_reactions = True
intents.integrations = True
intents.invites = True
intents.voice_states = False
intents.webhooks = False

Privileged Intents (Needs to be enabled on dev page):
intents.presences = True
intents.members = True
"""

intents = discord.Intents.default()
</code>```

I have the latest version of the discord API installed and am running python 3.8 What is causing the error and how do I fix it?

答:
There are two cases here.

The most obvious problem is that discord does not contain "intents" it contains "Intents". So all you need to do is change the i to a capital I.

The second possible problem could be an older version of Intent release.
To confirm your version do as the other answer mentioned in a new file and run that file.

Body:
I am trying to code a discord bot but when I run the program it gives the error

Traceback (most recent call last):
File "c:/Users/phara/Documents/GitHub/RayzeBot/bot.py", line 41, in
intents = discord.Intents.default()
AttributeError: module 'discord' has no attribute 'Intents'

import discord, asyncio, os, platform, sys
from discord.ext.commands import Bot
from discord.ext import commands
import time
import random
if not os.path.isfile("config.py"):
    sys.exit("'config.py' not found! Please add it and try again.")
else:
    import config

"""
Setup bot intents (events restrictions)
For more information about intents, please go to the following websites:
https://discordpy.readthedocs.io/en/latest/intents.html
https://discordpy.readthedocs.io/en/latest/intents.html#privileged-intents

Default Intents:
intents.messages = True
intents.reactions = True
intents.guilds = True
intents.emojis = True
intents.bans = True
intents.guild_typing = False
intents.typing = False
intents.dm_messages = False
intents.dm_reactions = False
intents.dm_typing = False
intents.guild_messages = True
intents.guild_reactions = True
intents.integrations = True
intents.invites = True
intents.voice_states = False
intents.webhooks = False

Privileged Intents (Needs to be enabled on dev page):
intents.presences = True
intents.members = True
"""

intents = discord.Intents.default()

I have the latest version of the discord API installed and am running python 3.8 What is causing the error and how do I fix it?


问:
Update PHP to 7.4 macOS Catalina with brew
I try to update my PHP version to 7.4 on macOS Catalina with brew.

I did brew install php@7.4

If I check my version php -v, I still see the old version PHP 7.3.11?

What do I have to do?

Update:

After brew doctor I get:

Warning: Homebrew's sbin was not found in your PATH but you have
installed formulae that put executables in /usr/local/sbin. Consider
setting the PATH for example like so:   echo 'export
PATH="/usr/local/sbin:$PATH"' >> ~/.profile

答:
If anyone want to downgrade php from latest 8.1.2 to 7.4 on systems demand, try the below commands with homebrew:
Installing PHP 7.4 :

```<code>brew install php@7.4
brew services restart php
brew unlink php@8.1
brew link php@7.4
</code>```
```<code>echo 'export PATH="/usr/local/opt/php@7.4/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/usr/local/opt/php@7.4/sbin:$PATH"' >> ~/.zshrc
</code>```

Or

```<code>export PATH="/usr/local/opt/php@7.4/bin:$PATH"
export PATH="/usr/local/opt/php@7.4/sbin:$PATH"
</code>```

Body:
If anyone want to downgrade php from latest 8.1.2 to 7.4 on systems demand, try the below commands with homebrew:
Installing PHP 7.4 :

brew install php@7.4
brew services restart php
brew unlink php@8.1
brew link php@7.4

echo 'export PATH="/usr/local/opt/php@7.4/bin:$PATH"' >> ~/.zshrc
echo 'export PATH="/usr/local/opt/php@7.4/sbin:$PATH"' >> ~/.zshrc

Or

export PATH="/usr/local/opt/php@7.4/bin:$PATH"
export PATH="/usr/local/opt/php@7.4/sbin:$PATH"


问:
What's the most efficient way to determine the minimum AWS permissions necessary for a Terraform configuration?
I have a Terraform configuration targeting deployment on AWS. It applies beautifully when using an IAM user that has permission to do anything (i.e. {actions: ["*"], resources: ["*"]}.

In pursuit of automating the application of this Terraform configuration, I want to determine the minimum set of permissions necessary to apply the configuration initially and effect subsequent changes. I specifically want to avoid giving overbroad permissions in policy, e.g. {actions: ["s3:*"], resources: ["*"]}.

So far, I'm simply running terraform apply until an error occurs. I look at the output or at the terraform log output to see what API call failed and then add it to the deployment user policy. EC2 and S3 are particularly frustrating because the name of the actions seems to not necessarily align with the API method name. I'm several hours into this with easy way to tell how far long I am.

Is there a more efficient way to do this?

It'd be really nice if Terraform advised me what permission/action I need but that's a product enhancement best left to Hashicorp.

答:
The tracking of minimum permissions is now provided by AWS itself. https://aws.amazon.com/blogs/security/iam-access-analyzer-makes-it-easier-to-implement-least-privilege-permissions-by-generating-iam-policies-based-on-access-activity/.

If you wanted to be picky about the minimum viable permission principle, you could use CloudFormation StackSets to deploy different roles with minimum permissions, so Terraform could assume them on each module call via different providers, i.e. if you have a module that deploys ASGs, LBs and EC2 instances, then:

include those actions in a role where the workload lives

add an terraform aws provider block that assumes that role

use that provider block within the module call.

The burden is to manage possibly quite a few terraform roles, but as I said, if you want to be picky or you have customer requirements to shrink down terraform user's permissions.

You could also download the CloudTrail event history for the last X days (up to 90) and run the following:

```<code>cat event_history.json <(echo "]}") | jq '[.Records[] | .eventName] | unique'
</code>```

The echo thing is due to the file being too big and shrunk (unknown reason) when downloaded from CloudTrail's page. You can see it below:

```<code>> jsonlint event_history.json
Error: Parse error on line 1:
...iam.amazonaws.com"}}
-----------------------^
Expecting ',', ']', got 'EOF'
    at Object.parseError (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/jsonlint.js:55:11)
    at Object.parse (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/jsonlint.js:132:22)
    at parse (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:82:14)
    at main (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:136:14)
    at Object.<anonymous> (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:178:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
</code>```

Body:
The tracking of minimum permissions is now provided by AWS itself. https://aws.amazon.com/blogs/security/iam-access-analyzer-makes-it-easier-to-implement-least-privilege-permissions-by-generating-iam-policies-based-on-access-activity/.

If you wanted to be picky about the minimum viable permission principle, you could use CloudFormation StackSets to deploy different roles with minimum permissions, so Terraform could assume them on each module call via different providers, i.e. if you have a module that deploys ASGs, LBs and EC2 instances, then:

include those actions in a role where the workload lives

add an terraform aws provider block that assumes that role

use that provider block within the module call.

The burden is to manage possibly quite a few terraform roles, but as I said, if you want to be picky or you have customer requirements to shrink down terraform user's permissions.

You could also download the CloudTrail event history for the last X days (up to 90) and run the following:

cat event_history.json <(echo "]}") | jq '[.Records[] | .eventName] | unique'

The echo thing is due to the file being too big and shrunk (unknown reason) when downloaded from CloudTrail's page. You can see it below:

> jsonlint event_history.json
Error: Parse error on line 1:
...iam.amazonaws.com"}}
-----------------------^
Expecting ',', ']', got 'EOF'
    at Object.parseError (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/jsonlint.js:55:11)
    at Object.parse (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/jsonlint.js:132:22)
    at parse (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:82:14)
    at main (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:136:14)
    at Object.<anonymous> (/usr/local/Cellar/jsonlint/1.6.0/libexec/lib/node_modules/jsonlint/lib/cli.js:178:1)
    at Module._compile (node:internal/modules/cjs/loader:1097:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)


答:
Sure you can!

http://jsfiddle.net/VfTGW/

I do this as a fallback for header logo images, I think some versions of IE will not abide. Edit: Or Chrome apparently - I don't even see alt text in the demo(?). Firefox works well however.

img {
  color: green;
  font: 40px Impact;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="404" alt="Alt Text"></code>```

Title: Can I style an image's ALT text with CSS?

Body:
I have a dark blue page and when the image is loading (or missing) the ALT text is black and difficult to read (in FF).

Could I style it (with CSS) to be white?

Body:
Sure you can!

http://jsfiddle.net/VfTGW/

I do this as a fallback for header logo images, I think some versions of IE will not abide. Edit: Or Chrome apparently - I don't even see alt text in the demo(?). Firefox works well however.

img {
  color: green;
  font: 40px Impact;
}

<img src="404" alt="Alt Text">


问:
Angular converting project to PWA, Dependencies error?
I am getting issues dynamically loading components using the following syntax:

```<code>this.dynamicContentPlacehold.clear();
const { AccountManagerComponent } = await import('./account-manager/account-manager.component')
const factory = this.componentFactoryResolver.resolveComponentFactory(AccountManagerComponent);
const componentRef = this.dynamicContentPlacehold.createComponent(factory);
componentRef.instance.user = this.user;
</code>```

I get the following console error.

```<code>ChunkLoadError: Loading chunk 592 failed.
</code>```

So I thought I would try what this link goes through, turning the app into a PWA

https://medium.com/fieldcircle/error-loading-chunk-xx-failed-with-angular-lazy-loaded-modules-6c5b1b6f8b8d

But when I run the command

```<code>ng add @angular/pwa --project user
</code>```

I get an error as shown

```<code>PS C:\Projects\user> ng add @angular/pwa --project user
ℹ Using package manager: npm
✔ Found compatible package version: @angular/pwa@latest.
✔ Package information loaded.

The package @angular/pwa will be installed and executed.
Would you like to proceed? Yes
✔ Package successfully installed.
CREATE ngsw-config.json (631 bytes)
CREATE ClientApp/src/manifest.webmanifest (1332 bytes)
CREATE ClientApp/src/assets/icons/icon-128x128.png (1253 bytes)
CREATE ClientApp/src/assets/icons/icon-144x144.png (1394 bytes)
CREATE ClientApp/src/assets/icons/icon-152x152.png (1427 bytes)
CREATE ClientApp/src/assets/icons/icon-192x192.png (1790 bytes)
CREATE ClientApp/src/assets/icons/icon-384x384.png (3557 bytes)
CREATE ClientApp/src/assets/icons/icon-512x512.png (5008 bytes)
CREATE ClientApp/src/assets/icons/icon-72x72.png (792 bytes)
CREATE ClientApp/src/assets/icons/icon-96x96.png (958 bytes)
UPDATE angular.json (4222 bytes)
UPDATE package.json (2082 bytes)
UPDATE ClientApp/src/app/app.module.ts (4421 bytes)
UPDATE ClientApp/src/index.html (303 bytes)
⠧ Installing packages (npm)...npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: user@0.0.0
npm ERR! Found: @angular/core@12.1.5
npm ERR! node_modules/@angular/core
npm ERR!   @angular/core@"^12.1.3" from the root project
npm ERR!   peer @angular/core@"^12.0.0 || ^13.0.0-0" from @angular/cdk@12.2.0
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^12.1.3" from the root project
npm ERR!   10 more (@angular/common, @angular/forms, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/core@12.2.16
npm ERR! node_modules/@angular/core
npm ERR!   peer @angular/core@"12.2.16" from @angular/service-worker@12.2.16
npm ERR!   node_modules/@angular/service-worker
npm ERR!     @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\me\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\me\AppData\Local\npm-cache\_logs\2022-02-07T10_57_36_373Z-debug.log
✖ Package install failed, see above.
The Schematic workflow failed. See above.
</code>```

These are my dependencies in the package.json file

```<code>"dependencies": {
    "@angular-devkit/build-angular": "~12.1.3",
    "@angular/animations": "^12.1.3",
    "@angular/cdk": "^12.1.3",
    "@angular/common": "^12.1.3",
    "@angular/compiler": "^12.1.3",
    "@angular/core": "^12.1.3",
    "@angular/forms": "^12.1.3",
    "@angular/platform-browser": "^12.1.3",
    "@angular/platform-browser-dynamic": "^12.1.3",
    "@angular/router": "^12.1.3",
    "@angular/service-worker": "^12.1.3",
    "@fortawesome/fontawesome-free": "^5.15.3",
    "@schematics/angular": "^12.1.3",
    "@sentry/browser": "^6.10.0",
    "del": "^6.0.0",
    "gulp": "^4.0.2",
    "ngx-cookie-service": "^12.0.0",
    "primeflex": "^2.0.0",
    "primeicons": "^4.1.0",
    "primeng": "^12.0.1",
    "raven-js": "^3.27.2",
    "rxjs": "^7.2.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
</code>```

How can I get this to work as I have no idea what the issue is, apart from confusing version conflicts for some reason?

I have also tried what Pankaj has said.

So I ran this with the version

```<code>ng add @angular/pwa@12.1.3
</code>```

but I still get this error

```<code>npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: user@0.0.0
npm ERR! Found: @angular/core@12.1.5
npm ERR! node_modules/@angular/core
npm ERR!   @angular/core@"^12.1.3" from the root project
npm ERR!   peer @angular/core@"^12.0.0 || ^13.0.0-0" from @angular/cdk@12.2.0
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^12.1.3" from the root project
npm ERR!   10 more (@angular/common, @angular/forms, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/core@12.2.16
npm ERR! node_modules/@angular/core
npm ERR!   peer @angular/core@"12.2.16" from @angular/service-worker@12.2.16
npm ERR!   node_modules/@angular/service-worker
npm ERR!     @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\me\AppData\Local\npm-cache\eresolve-report.txt for a full report.
</code>```

答:
You have a dependency conflict.

@angular/pwa internally adds @angular/service-worker package for
you.

The error message says that you are installing @angular/service-worker version '12.2.16' which internally depends on @angular/core version '12.2.16'.

Your package.json has @angular/core version '12.1.3'.

So, you need to install the @angular/pwa not with @latest but with the version that's compatible with your current setup.

Install it with ng add @angular/pwa@12.1.3

Body:
I am getting issues dynamically loading components using the following syntax:

this.dynamicContentPlacehold.clear();
const { AccountManagerComponent } = await import('./account-manager/account-manager.component')
const factory = this.componentFactoryResolver.resolveComponentFactory(AccountManagerComponent);
const componentRef = this.dynamicContentPlacehold.createComponent(factory);
componentRef.instance.user = this.user;

I get the following console error.

ChunkLoadError: Loading chunk 592 failed.

So I thought I would try what this link goes through, turning the app into a PWA

https://medium.com/fieldcircle/error-loading-chunk-xx-failed-with-angular-lazy-loaded-modules-6c5b1b6f8b8d

But when I run the command

ng add @angular/pwa --project user

I get an error as shown

PS C:\Projects\user> ng add @angular/pwa --project user
ℹ Using package manager: npm
✔ Found compatible package version: @angular/pwa@latest.
✔ Package information loaded.

The package @angular/pwa will be installed and executed.
Would you like to proceed? Yes
✔ Package successfully installed.
CREATE ngsw-config.json (631 bytes)
CREATE ClientApp/src/manifest.webmanifest (1332 bytes)
CREATE ClientApp/src/assets/icons/icon-128x128.png (1253 bytes)
CREATE ClientApp/src/assets/icons/icon-144x144.png (1394 bytes)
CREATE ClientApp/src/assets/icons/icon-152x152.png (1427 bytes)
CREATE ClientApp/src/assets/icons/icon-192x192.png (1790 bytes)
CREATE ClientApp/src/assets/icons/icon-384x384.png (3557 bytes)
CREATE ClientApp/src/assets/icons/icon-512x512.png (5008 bytes)
CREATE ClientApp/src/assets/icons/icon-72x72.png (792 bytes)
CREATE ClientApp/src/assets/icons/icon-96x96.png (958 bytes)
UPDATE angular.json (4222 bytes)
UPDATE package.json (2082 bytes)
UPDATE ClientApp/src/app/app.module.ts (4421 bytes)
UPDATE ClientApp/src/index.html (303 bytes)
⠧ Installing packages (npm)...npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: user@0.0.0
npm ERR! Found: @angular/core@12.1.5
npm ERR! node_modules/@angular/core
npm ERR!   @angular/core@"^12.1.3" from the root project
npm ERR!   peer @angular/core@"^12.0.0 || ^13.0.0-0" from @angular/cdk@12.2.0
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^12.1.3" from the root project
npm ERR!   10 more (@angular/common, @angular/forms, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/core@12.2.16
npm ERR! node_modules/@angular/core
npm ERR!   peer @angular/core@"12.2.16" from @angular/service-worker@12.2.16
npm ERR!   node_modules/@angular/service-worker
npm ERR!     @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\me\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\me\AppData\Local\npm-cache\_logs\2022-02-07T10_57_36_373Z-debug.log
✖ Package install failed, see above.
The Schematic workflow failed. See above.

These are my dependencies in the package.json file

"dependencies": {
    "@angular-devkit/build-angular": "~12.1.3",
    "@angular/animations": "^12.1.3",
    "@angular/cdk": "^12.1.3",
    "@angular/common": "^12.1.3",
    "@angular/compiler": "^12.1.3",
    "@angular/core": "^12.1.3",
    "@angular/forms": "^12.1.3",
    "@angular/platform-browser": "^12.1.3",
    "@angular/platform-browser-dynamic": "^12.1.3",
    "@angular/router": "^12.1.3",
    "@angular/service-worker": "^12.1.3",
    "@fortawesome/fontawesome-free": "^5.15.3",
    "@schematics/angular": "^12.1.3",
    "@sentry/browser": "^6.10.0",
    "del": "^6.0.0",
    "gulp": "^4.0.2",
    "ngx-cookie-service": "^12.0.0",
    "primeflex": "^2.0.0",
    "primeicons": "^4.1.0",
    "primeng": "^12.0.1",
    "raven-js": "^3.27.2",
    "rxjs": "^7.2.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },

How can I get this to work as I have no idea what the issue is, apart from confusing version conflicts for some reason?

I have also tried what Pankaj has said.

So I ran this with the version

ng add @angular/pwa@12.1.3

but I still get this error

npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: user@0.0.0
npm ERR! Found: @angular/core@12.1.5
npm ERR! node_modules/@angular/core
npm ERR!   @angular/core@"^12.1.3" from the root project
npm ERR!   peer @angular/core@"^12.0.0 || ^13.0.0-0" from @angular/cdk@12.2.0
npm ERR!   node_modules/@angular/cdk
npm ERR!     @angular/cdk@"^12.1.3" from the root project
npm ERR!   10 more (@angular/common, @angular/forms, ...)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: @angular/core@12.2.16
npm ERR! node_modules/@angular/core
npm ERR!   peer @angular/core@"12.2.16" from @angular/service-worker@12.2.16
npm ERR!   node_modules/@angular/service-worker
npm ERR!     @angular/service-worker@"^12.1.3" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\me\AppData\Local\npm-cache\eresolve-report.txt for a full report.


问:
Cannot find 'selectedIndexPaths' in scope
My Viewcontroller shows "Cannot find 'selectedIndexPaths' in scope" and other errors

My viewcontroller with errors:- import UIKit

```<code>  class ProductViewController: UIViewController, UITableViewDataSource,
                         UITableViewDelegate {
   let notificationButton = SSBadgeButton()
    let rightbarbuttonimage = UIImage(named:"ic_cart")
    fileprivate var cart = Cart()
   let scrollView = UIScrollView()
   let sections = ["Section A", "Section B","Section C", "Section D","Section   E","Section F","Section G","Section H", "Section I","Section J","Section K","Section L"]
   let rowspersection = [2,3,1,2,2,3,3,1,4,2,1,2]

    @IBOutlet weak var tableView: UITableView!

     override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    self.tableView.backgroundColor = UIColor.gray

    //Add and setup scroll view
    self.tableView.addSubview(self.scrollView)
    self.scrollView.translatesAutoresizingMaskIntoConstraints = false;

    //Constrain scroll view
    self.scrollView.leadingAnchor.constraint(equalTo: self.tableView.leadingAnchor, constant: 20).isActive = true;
    self.scrollView.topAnchor.constraint(equalTo: self.tableView.topAnchor, constant: 20).isActive = true;
    self.scrollView.trailingAnchor.constraint(equalTo: self.tableView.trailingAnchor, constant: -20).isActive = true;
    self.scrollView.bottomAnchor.constraint(equalTo: self.tableView.bottomAnchor, constant: -20).isActive = true;

    // customising rightBarButtonItems as notificationbutton
    notificationButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
    notificationButton.setImage(UIImage(named: "ic_cart")?.withRenderingMode(.alwaysTemplate), for: .normal)
    notificationButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 15)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)

    //following register is needed because I have rightbarbuttonitem customised as   uibutton i.e.  notificationbutton
    notificationButton.addTarget(self, action: #selector(self.registerTapped(_:)), for: .touchUpInside)
}
@objc func registerTapped(_ sender: UIButton) {
    self.performSegue(withIdentifier: "showCart", sender: nil)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    //Workaround to avoid the fadout the right bar button item
    self.navigationItem.rightBarButtonItem?.isEnabled = false
    self.navigationItem.rightBarButtonItem?.isEnabled = true

    //Update cart if some items quantity is equal to 0 and reload the product table and right button bar item
    cart.updateCart()

    //self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
    notificationButton.badge = String(cart.items.count)// making badge equal to no.ofitems in cart

    tableView.reloadData()
   }

   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

// this segue to transfer data
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showCart" {
        if let cartViewController = segue.destination as? CartViewController {
            cartViewController.cart = self.cart
        }
    }
}

   func numberOfSections(in tableView: UITableView) -> Int {
    return productMap.count
   }
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return productMap[section]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let product = productMap[indexPath.section]![indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCell") as! ProductTableViewCell
    cell.imageView?.image =  product.imagename
    cell.delegate = self as CartDelegate
    cell.setButton(state: self.cart.contains(product: product))
    return cell
}

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    switch(section) {
    case 0: return "Section A"
    case 1: return "Section B"
    case 2: return "Section C"
    case 3: return "Section D"
    case 4: return "Section E"
    case 5: return "Section F"
    case 6: return "Section G"
    case 7: return "Section H"
    case 8: return "Section I"
    case 9: return "Section J"
    case 10: return "Section K"
    case 11: return "Section L"
    default: return ""
       }
    }
  }

     extension ProductViewController: CartDelegate {

     // MARK: - CartDelegate
    func updateCart(cell: ProductTableViewCell) {
    guard let indexPath = tableView.indexPath(for: cell) else { return }
    let product = productMap[indexPath.section]![indexPath.row]

 /// `var selectedIndexPaths = [IndexPath]()` defined inside `ProductViewController`,   to keep track of the selected products// **error -Cannot find 'selectedIndexPaths' in scope**
    if selectedIndexPaths.contains(indexPath) {**//error -Cannot find 'selectedIndexPaths' in scope**
        if let index = selectedIndexPaths.firstIndex(of: indexPath) {
            selectedIndexPaths.remove(at: index)**//error -Cannot find 'selectedIndexPaths' in scope**
            removeProductFromCart(indexPath: indexPath)
        }
    } else {
        selectedIndexPaths.append(indexPath)
        addProductToCart(indexPath: indexPath)
    }

         //           addProductToCart(indexPath: indexPath)
    ///  **I commented this out because I don't have the code for `Cart`**
    //Update Cart with product
         //        cart.updateCart(with: product)
    // self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
        //        notificationButton.badge = String(cart.items.count) // making badge equal to noofitems in cart

      }
     }

    func addProductToCart(indexPath: IndexPath) {
     if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
    if let imageView = cell.imagename {

        let initialImageViewFrame = imageView.convert(imageView.frame, to: self.view)
        let targetImageViewFrame = self.notificationButton.frame

        let imgViewTemp = UIImageView(frame: initialImageViewFrame)
        imgViewTemp.clipsToBounds = true
        imgViewTemp.contentMode = .scaleAspectFill
        imgViewTemp.image = imageView.image

        self.view.addSubview(imgViewTemp)

        UIView.animate(withDuration: 1.0, animations: {
            imgViewTemp.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
        }) {  _ in
            UIView.animate(withDuration: 0.5, animations: {
                imgViewTemp.transform = CGAffineTransform(scaleX: 0.2, y: 0.2).rotated(by: CGFloat(Double.pi))
                imgViewTemp.frame = targetImageViewFrame
            }) { _ in
                imgViewTemp.removeFromSuperview()

                UIView.animate(withDuration: 1.0, animations: {
                    self.notificationButton.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
                }, completion: {_ in
                    self.notificationButton.transform = CGAffineTransform.identity
                })
            }
          }
        }
         }
        }

  func removeProductFromCart(indexPath: IndexPath) {
   if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
    if let imageView = cell.imagename {

        let initialImageViewFrame = self.notificationButton.frame
        let targetImageViewFrame = imageView.convert(imageView.frame, to: self.view)

        let imgViewTemp = UIImageView(frame: initialImageViewFrame)
        imgViewTemp.clipsToBounds = true
        imgViewTemp.contentMode = .scaleAspectFill
        imgViewTemp.image = imageView.image

        self.view.addSubview(imgViewTemp)

        var initialTransform = CGAffineTransform.identity
        initialTransform = initialTransform.scaledBy(x: 0.2, y: 0.2)
        initialTransform = initialTransform.rotated(by: CGFloat(Double.pi))

        UIView.animate(withDuration: 0.5, animations: {
            self.notificationButton.animationZoom(scaleX: 1.4, y: 1.4)
            imgViewTemp.transform = initialTransform
        }) {  _ in
            UIView.animate(withDuration: 1, animations: {
                self.notificationButton.animationZoom(scaleX: 1, y: 1)
                imgViewTemp.transform = CGAffineTransform.identity
                imgViewTemp.frame = targetImageViewFrame
            }) { _ in
                imgViewTemp.removeFromSuperview()
            }
           }
         }
      }
           }

</code>```

screenshot of the error-

I have tableview in my productviewcotroller as shown below. so, thats not an issusem still errors:-

There are other errors also which it is showing.

How to sort it out ?

答:
var selectedIndexPaths = IndexPath

Please define selectedIndexPaths inside the main class not in the extension then check it again .

Body:
My Viewcontroller shows "Cannot find 'selectedIndexPaths' in scope" and other errors

My viewcontroller with errors:- import UIKit

  class ProductViewController: UIViewController, UITableViewDataSource,
                         UITableViewDelegate {
   let notificationButton = SSBadgeButton()
    let rightbarbuttonimage = UIImage(named:"ic_cart")
    fileprivate var cart = Cart()
   let scrollView = UIScrollView()
   let sections = ["Section A", "Section B","Section C", "Section D","Section   E","Section F","Section G","Section H", "Section I","Section J","Section K","Section L"]
   let rowspersection = [2,3,1,2,2,3,3,1,4,2,1,2]

    @IBOutlet weak var tableView: UITableView!

     override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    self.tableView.backgroundColor = UIColor.gray

    //Add and setup scroll view
    self.tableView.addSubview(self.scrollView)
    self.scrollView.translatesAutoresizingMaskIntoConstraints = false;

    //Constrain scroll view
    self.scrollView.leadingAnchor.constraint(equalTo: self.tableView.leadingAnchor, constant: 20).isActive = true;
    self.scrollView.topAnchor.constraint(equalTo: self.tableView.topAnchor, constant: 20).isActive = true;
    self.scrollView.trailingAnchor.constraint(equalTo: self.tableView.trailingAnchor, constant: -20).isActive = true;
    self.scrollView.bottomAnchor.constraint(equalTo: self.tableView.bottomAnchor, constant: -20).isActive = true;

    // customising rightBarButtonItems as notificationbutton
    notificationButton.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
    notificationButton.setImage(UIImage(named: "ic_cart")?.withRenderingMode(.alwaysTemplate), for: .normal)
    notificationButton.badgeEdgeInsets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 15)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: notificationButton)

    //following register is needed because I have rightbarbuttonitem customised as   uibutton i.e.  notificationbutton
    notificationButton.addTarget(self, action: #selector(self.registerTapped(_:)), for: .touchUpInside)
}
@objc func registerTapped(_ sender: UIButton) {
    self.performSegue(withIdentifier: "showCart", sender: nil)
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    //Workaround to avoid the fadout the right bar button item
    self.navigationItem.rightBarButtonItem?.isEnabled = false
    self.navigationItem.rightBarButtonItem?.isEnabled = true

    //Update cart if some items quantity is equal to 0 and reload the product table and right button bar item
    cart.updateCart()

    //self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
    notificationButton.badge = String(cart.items.count)// making badge equal to no.ofitems in cart

    tableView.reloadData()
   }

   override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

// this segue to transfer data
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showCart" {
        if let cartViewController = segue.destination as? CartViewController {
            cartViewController.cart = self.cart
        }
    }
}

   func numberOfSections(in tableView: UITableView) -> Int {
    return productMap.count
   }
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return productMap[section]?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let product = productMap[indexPath.section]![indexPath.row]
    let cell = tableView.dequeueReusableCell(withIdentifier: "ProductTableViewCell") as! ProductTableViewCell
    cell.imageView?.image =  product.imagename
    cell.delegate = self as CartDelegate
    cell.setButton(state: self.cart.contains(product: product))
    return cell
}

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 44
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    switch(section) {
    case 0: return "Section A"
    case 1: return "Section B"
    case 2: return "Section C"
    case 3: return "Section D"
    case 4: return "Section E"
    case 5: return "Section F"
    case 6: return "Section G"
    case 7: return "Section H"
    case 8: return "Section I"
    case 9: return "Section J"
    case 10: return "Section K"
    case 11: return "Section L"
    default: return ""
       }
    }
  }

     extension ProductViewController: CartDelegate {

     // MARK: - CartDelegate
    func updateCart(cell: ProductTableViewCell) {
    guard let indexPath = tableView.indexPath(for: cell) else { return }
    let product = productMap[indexPath.section]![indexPath.row]

 /// `var selectedIndexPaths = [IndexPath]()` defined inside `ProductViewController`,   to keep track of the selected products// **error -Cannot find 'selectedIndexPaths' in scope**
    if selectedIndexPaths.contains(indexPath) {**//error -Cannot find 'selectedIndexPaths' in scope**
        if let index = selectedIndexPaths.firstIndex(of: indexPath) {
            selectedIndexPaths.remove(at: index)**//error -Cannot find 'selectedIndexPaths' in scope**
            removeProductFromCart(indexPath: indexPath)
        }
    } else {
        selectedIndexPaths.append(indexPath)
        addProductToCart(indexPath: indexPath)
    }

         //           addProductToCart(indexPath: indexPath)
    ///  **I commented this out because I don't have the code for `Cart`**
    //Update Cart with product
         //        cart.updateCart(with: product)
    // self.navigationItem.rightBarButtonItem?.title = "Checkout (\(cart.items.count))"
        //        notificationButton.badge = String(cart.items.count) // making badge equal to noofitems in cart

      }
     }

    func addProductToCart(indexPath: IndexPath) {
     if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
    if let imageView = cell.imagename {

        let initialImageViewFrame = imageView.convert(imageView.frame, to: self.view)
        let targetImageViewFrame = self.notificationButton.frame

        let imgViewTemp = UIImageView(frame: initialImageViewFrame)
        imgViewTemp.clipsToBounds = true
        imgViewTemp.contentMode = .scaleAspectFill
        imgViewTemp.image = imageView.image

        self.view.addSubview(imgViewTemp)

        UIView.animate(withDuration: 1.0, animations: {
            imgViewTemp.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
        }) {  _ in
            UIView.animate(withDuration: 0.5, animations: {
                imgViewTemp.transform = CGAffineTransform(scaleX: 0.2, y: 0.2).rotated(by: CGFloat(Double.pi))
                imgViewTemp.frame = targetImageViewFrame
            }) { _ in
                imgViewTemp.removeFromSuperview()

                UIView.animate(withDuration: 1.0, animations: {
                    self.notificationButton.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
                }, completion: {_ in
                    self.notificationButton.transform = CGAffineTransform.identity
                })
            }
          }
        }
         }
        }

  func removeProductFromCart(indexPath: IndexPath) {
   if let cell = tableView.cellForRow(at: indexPath) as? ProductTableViewCell {
    if let imageView = cell.imagename {

        let initialImageViewFrame = self.notificationButton.frame
        let targetImageViewFrame = imageView.convert(imageView.frame, to: self.view)

        let imgViewTemp = UIImageView(frame: initialImageViewFrame)
        imgViewTemp.clipsToBounds = true
        imgViewTemp.contentMode = .scaleAspectFill
        imgViewTemp.image = imageView.image

        self.view.addSubview(imgViewTemp)

        var initialTransform = CGAffineTransform.identity
        initialTransform = initialTransform.scaledBy(x: 0.2, y: 0.2)
        initialTransform = initialTransform.rotated(by: CGFloat(Double.pi))

        UIView.animate(withDuration: 0.5, animations: {
            self.notificationButton.animationZoom(scaleX: 1.4, y: 1.4)
            imgViewTemp.transform = initialTransform
        }) {  _ in
            UIView.animate(withDuration: 1, animations: {
                self.notificationButton.animationZoom(scaleX: 1, y: 1)
                imgViewTemp.transform = CGAffineTransform.identity
                imgViewTemp.frame = targetImageViewFrame
            }) { _ in
                imgViewTemp.removeFromSuperview()
            }
           }
         }
      }
           }

screenshot of the error-

I have tableview in my productviewcotroller as shown below. so, thats not an issusem still errors:-

There are other errors also which it is showing.

How to sort it out ?


问:
Only 1 item is showed in recyclerView and it doesn't even scroll down
I'm starting android development and i was creating a simple recyclerview.
I think code is completely fine but when i run the app only one item is displayed and it isn't even scrolling down.

Here is my main xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

And this is my main java file.

```<code>package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr);
        r.setAdapter(c);
    }
}
</code>```

This is my customadapter class and its xml file.

```<code>package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet) {
        localDataSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
</code>```

And it's xml file.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Any help will be appreciated:)

答:
You should not give fixed height to recyclerview. So just change the height to wrap_content

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Body:
I'm starting android development and i was creating a simple recyclerview.
I think code is completely fine but when i run the app only one item is displayed and it isn't even scrolling down.

Here is my main xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="60dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

And this is my main java file.

package com.example.creatingrecyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    RecyclerView r;
    String arr[]={"1","2","3","4","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        r=findViewById(R.id.rv);
        r.setLayoutManager(new LinearLayoutManager(this));
        CustomAdapter c=new CustomAdapter(arr);
        r.setAdapter(c);
    }
}

This is my customadapter class and its xml file.

package com.example.creatingrecyclerview;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet) {
        localDataSet = dataSet;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);

        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}

And it's xml file.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="124dp"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_weight="1"
            android:text="TextView" />
    </LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Any help will be appreciated:)

Body:
You should not give fixed height to recyclerview. So just change the height to wrap_content

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="0dp"
        android:layout_height="dp"
        android:layout_marginTop="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


问:
Regex differences between Kotlin and Swift
I have an application implemented in Android with Kotlin and in iOS with Swift.

I want the backend to send with a response to the clients a regular expression. This regular expression must then be checked in both apps in order to see if it matches a user's input.

Question:
Do regular expressions have the same syntax in both Kotlin and Swift? If not, what are their differences?

答:
For anyone who may have the same question, after some research, I came to the conclusion that Swift uses ICU for regular expressions, while Kotlin is using the regular expression syntax that Java uses and has this pattern syntax.

You can find the exact differences between ICU and Java regular expressions here.


答:
Setting the img tag color works

```<code>img {color:#fff}
</code>```

http://jsfiddle.net/YEkAt/

body {background:#000022}
img {color:#fff}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" /></code>```

Body:
Setting the img tag color works

img {color:#fff}

http://jsfiddle.net/YEkAt/

body {background:#000022}
img {color:#fff}

<img src="http://badsrc.com/blah" alt="BLAH BLAH BLAH" />