问:
parameter goes null when using
 (Mojarra 2.3)
the xhtml file is getting a Integer parameter which is saved as deck_id. In that xhtml file it is used normally and it works as in the header but when i want to combine it with a
 the param goes to null. I dont know why and I have no idea how to solve it.
As i am new in programming and that is my first project I am lost right now and hours of google didnt help.

the deck_id works  fine in  #{deckListController.getDeckByDeckId(deck_id).name} but doesnt work anymore at

 -->

By pressing the New Card Button i just added a function which prints the deck_id (as u can see in the newCardDialog) in the console and it prints 0 but it should be the ID of the given deck.

xhtml file deck-detail view

```<code>    <ui:param name="deck_id" value="#{param['deck_id']}"/>
    <ui:define name="content">
        <h1>Cards of
            #{deckListController.getDeckByDeckId(deck_id).name}</h1>
        <div class="deck-detail">
            <!--  TODO: ADD NEW CARD -->
            <h:form id="newCardForm">
                <div class="txt-r">
                    <!--  TODO: only see for the creator of the deck -->
                    <!--  one Problem -> deckId somehow is null -> exception becaus of unboxing null is wrong -->
                    <p:commandButton oncomplete="PF('newCardDialog').show()"
                        icon="pi pi-plus" value="new card" title="New">
<!--                        rendered="#{deckListController.getDeckByDeckId(param['deck_id']).createUser == sessionInfoBean.currentUser}"> -->
                    </p:commandButton>

                    <p:commandButton oncomplete="PF('deckEditDialog').show()"
                        icon="pi pi-pencil" value="edit deck" title="Edit" styleClass="btn-light">
                        <f:setPropertyActionListener
                            value="#{deckListController.getDeckByDeckId(deck_id)}"
                            target="#{deckDetailController.deck}" />
                    </p:commandButton>
                </div>
                <br />

                <!-- new Card dialog -->
                <p:dialog header="Create new Card" id="newCardDialog"
                    widgetVar="newCardDialog" modal="true" showEffect="fade"
                    hideEffect="fade" resizable="false" width="400">
                    <p:outputPanel id="newCardData">
                        <p:messages id="messages" closable="true" autoUpdate="true" />
                        <h:panelGrid columns="2">
                            <p:outputLabel for="cardContentFront" value="Question: " />
                            <!-- TODO: required field check is not working yet -->
                            <p:inputTextarea id="cardContentFront"
                                value="#{newCardController.card.contentFront}" required="true"
                                requiredMessage="Question of card is required" />
                            <p:outputLabel for="cardContentBack" value="Answer: " />
                            <p:inputTextarea id="cardContentBack"
                                value="#{newCardController.card.contentBack}" required="true"
                                requiredMessage="Answer of card is required" />
                        </h:panelGrid>
                        <p:separator />
                        <h:panelGrid columns="2">
                            <p:outputLabel for="flipped" value="Flipped: " />
                            <p:selectBooleanCheckbox id="flipped"
                                value="#{newCardController.card.flipped}" />
                        </h:panelGrid>
                        <p:separator />
                        <h:panelGrid columns="3">
                            <p:commandButton value="Cancel"
                                onclick="PF('newCardDialog').hide()" styleClass="btn-light" />
                            <!-- TODO: after create refreshing of the table -->
                            <p:commandButton value="Create"
                                actionListener="#{cardListController.print(deck_id)}"
                                oncomplete="PF('newCardDialog').hide()" />
                            <!-- action="#{newCardController.doCreateCard(deck_id)}" -->
                            <!-- update="cardForm" /> -->
                        </h:panelGrid>
                    </p:outputPanel>
                </p:dialog>

                <!-- Edit deck dialog  -->
                <p:dialog header="Edit #{deckListController.getDeckByDeckId(param['deck_id']).name}" id="deckEditDialog"
                    widgetVar="deckEditDialog" modal="true" showEffect="fade"
                    hideEffect="fade" resizable="false" width="400">
                    <p:outputPanel id="deckData" rendered="#{ empty deckDetailController.deck}">
                        <h:panelGrid columns="2">
                            <p:outputLabel for="name" value="Deck Name: " />
                            <p:inputText id="name" disabled="false" />
                            <p:outputLabel for="description" value="Desription: " />
                            <p:inputTextarea id="description" disabled="false" />
                        </h:panelGrid>
                        <h:panelGrid columns="2">
                        <p:outputLabel for="public" value="Public: " />
                        <p:selectBooleanCheckbox id="public" />
                    </h:panelGrid>
                        <h:panelGrid columns="3">
                            <p:commandButton value="Cancel"
                                onclick="PF('deckEditDialog').hide()" styleClass="btn-light" />
                            <p:commandButton value="Reload"

                                            update=":cardForm:cardView"
                                            styleClass="btn-light" />
                        <p:commandButton value="Save"

                                        oncomplete="PF('deckEditDialog').hide()"
                                        update=":cardForm:cardView" />
                        </h:panelGrid>
                    </p:outputPanel>
                </p:dialog>

            </h:form>

            <h:form id="cardForm">
                <p:dataGrid id="cardView" var="card"
                    value="#{cardListController.getEnabledCardsOfOneDeckByDeckId(deck_id)}"
                    columns="4" paginator="false">
                    <p:dataViewGridItem>
                        <h3 class="card-name">Question:</h3>
                        <div class="card-grid-item-content">
                            <p class="card-contentFront">#{card.contentFront}</p>
                        </div>
                        <div class="open-btns txt-r">
                            <!--  TODO: edit and delete button in Progress -->
                            <p:commandButton update=":cardForm:cardEditDialog"
                                            oncomplete="PF('cardEditDialog').show()"
                                            type="button" title="edit" value="edit" styleClass="btn-light"
                                            rendered="#{card.createUser == sessionInfoBean.currentUser}">
                                <f:setPropertyActionListener value="#{card}"
                                                            target="#{cardDetailController.card}" />
                            </p:commandButton>
                            <p:commandButton title="delete"
                                            action="#{cardDetailController.doDisableCard}"
                                            rendered="#{card.createUser == sessionInfoBean.currentUser}">
                                <f:setPropertyActionListener value="#{card}"
                                                            target="#{cardDetailController.card}" />

                                <p:confirm header="Confirmation"
                                    message="Are you sure you want do delete this card?"
                                    icon="pi pi-exclamation-triangle" />
                            </p:commandButton>
                        </div>
                    </p:dataViewGridItem>
                </p:dataGrid>

                <!-- Edit card dialog  -->
                <p:dialog header="Edit Card" id="cardEditDialog"
                    widgetVar="cardEditDialog" modal="true" showEffect="fade"
                    hideEffect="fade" resizable="false" width="400">
                    <p:outputPanel id="cardData"
                        rendered="#{not empty cardDetailController.card}">
                        <h:panelGrid columns="2">
                            <p:outputLabel for="contentFront" value="Question: " />
                            <p:inputText id="contentFront"
                                value="#{cardDetailController.card.contentFront}"
                                disabled="false" />
                            <p:outputLabel for="contentBack" value="Answer: " />
                            <p:inputTextarea id="contentBack"
                                value="#{cardDetailController.card.contentBack}"
                                disabled="false" />
                        </h:panelGrid>
                        <h:panelGrid columns="3">
                            <p:commandButton value="Cancel"
                                onclick="PF('cardEditDialog').hide()" styleClass="btn-light" />
                            <p:commandButton value="Reload"
                                action="#{cardDetailController.doReloadCard()}"
                                update=":cardsForm:cardView" styleClass="btn-light" />
                            <p:commandButton value="Save"
                                action="#{cardDetailController.doSaveCard()}"
                                oncomplete="PF('cardEditDialog').hide()"
                                update=":cardForm:cardView" />
                        </h:panelGrid>
                    </p:outputPanel>
                </p:dialog>

                <!--  Deletion confirmation dialog -->
                <p:confirmDialog global="true" showEffect="fade" hideEffect="fade"
                    width="300">
                    <p:commandButton value="Yes" type="button"
                        styleClass="ui-confirmdialog-yes btn-light" />
                    <p:commandButton value="No" type="button"
                        styleClass="ui-confirmdialog-no" />
                </p:confirmDialog>

            </h:form>
        </div>
    </ui:define>
</ui:composition>
</code>```

xhtml file where the param is given to deck-detail view

```<code><ui:composition xmlns="http://www.w3c.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

    <div class="personal-decks">
        <h:form id="newDeckForm">
            <div class="txt-r">
                <p:commandButton oncomplete="PF('newDeckDialog').show()"
                    icon="pi pi-plus" value="new deck" title="New" />
            </div>
            <br />
            <!-- NEW deck dialog-->
            <p:dialog header="Create new Deck" id="newDeckDialog"
                widgetVar="newDeckDialog" modal="true" showEffect="fade"
                hideEffect="fade" resizable="false" width="400">
                <p:outputPanel id="newDeckData">
                    <p:messages id="messages" closable="true" autoUpdate="true" />
                    <h:panelGrid columns="2">
                        <p:outputLabel for="deckName" value="Deck Name: " />
                        <!-- TODO: required field check is not working yet -->
                        <p:inputText id="deckName" value="#{newDeckController.deck.name}"
                            required="true" requiredMessage="Name of deck is required" />
                        <p:outputLabel for="deckDescription" value="Description: " />
                        <p:inputTextarea id="deckDescription"
                            value="#{newDeckController.deck.description}" disabled="false" />
                    </h:panelGrid>
                    <h:panelGrid columns="3">
                        <p:commandButton value="Cancel"
                            onclick="PF('newDeckDialog').hide()" styleClass="btn-light" />
                        <p:commandButton value="Create"
                            action="#{newDeckController.doCreateDeck()}">
                        </p:commandButton>
                    </h:panelGrid>
                </p:outputPanel>
            </p:dialog>
        </h:form>

        <!-- PRIVATE decks view-->
        <h:form id="privateDecksForm">
            <p:dataGrid id="decksView"
                        var="deck"
                        value="#{deckListController.userDecks}" columns="4"
                        paginator="false">

                <p:dataViewGridItem>
                    <div class="edit-btns">
                        <p:commandButton update=":deckTabs:privateDecksForm:deckEditDialog"
                                         oncomplete="PF('deckEditDialog').show()" icon="pi pi-pencil"
                                         title="Edit">
                            <f:setPropertyActionListener value="#{deck}"
                                                         target="#{deckDetailController.deck}" />
                        </p:commandButton>
                        <p:commandButton action="#{deckDetailController.doDisableDeck}"
                                         icon="pi pi-trash" title="Delete"
                                         update=":deckTabs:privateDecksForm:decksView">
                            <f:setPropertyActionListener value="#{deck}"
                                                         target="#{deckDetailController.deck}" />
                            <p:confirm header="Confirmation"
                                       message="Are you sure that you want to delete this deck? You cannot undo this operation."
                                       icon="pi pi-exclamation-triangle" />
                        </p:commandButton>
                    </div>
                    <h3 class="deck-name">#{deck.name}</h3>
                    <div class="deck-grid-item-content">
                        <p class="deck-description">#{deck.description}</p>
                        <p class="deck-no-cards">
                            New cards: #{deckDetailController.getNewCardsCount(deck)}
                            <br />
                            Repeatable cards: #{deckDetailController.getRepeatableCardsCount(deck)}
                        </p>
                    </div>
                    <div class="open-btns txt-r">
                        <p:linkButton outcome="deck-detail" value="view"
                            styleClass="btn-light">
                            <f:param name="deck_id" value="#{deck.deckID}" />
                        </p:linkButton>
                        <p:linkButton outcome="learning-view" value="learn">
                            <f:param name="deck_id" value="#{deck.deckID}" />
                        </p:linkButton>
                    </div>
                </p:dataViewGridItem>
            </p:dataGrid>

            <!-- Edit deck dialog-->
            <p:dialog header="Edit Deck" id="deckEditDialog"
                widgetVar="deckEditDialog" modal="true" showEffect="fade"
                hideEffect="fade" resizable="false" width="400">
                <p:outputPanel id="deckData"
                    rendered="#{not empty deckDetailController.deck}">
                    <h:panelGrid columns="2">
                        <p:outputLabel for="name" value="Deck Name: " />
                        <p:inputText id="name" value="#{deckDetailController.deck.name}"
                            disabled="false" />
                        <p:outputLabel for="description" value="Description: " />
                        <p:inputTextarea id="description"
                            value="#{deckDetailController.deck.description}" disabled="false" />
                    </h:panelGrid>
                    <h:panelGrid columns="2">
                        <p:outputLabel for="public" value="Public: " />
                        <p:selectBooleanCheckbox id="public"
                            value="#{deckDetailController.deck.publiclyShared}" />
                    </h:panelGrid>
                    <h:panelGrid columns="3">
                        <p:commandButton value="Cancel"
                            onclick="PF('deckEditDialog').hide()"
                            styleClass="btn-light" />
                        <p:commandButton value="Reload"
                            action="#{deckDetailController.doReloadDeck()}"
                            update=":deckTabs:privateDecksForm:decksView"
                            styleClass="btn-light" />
                        <p:commandButton value="Save"
                            action="#{deckDetailController.doSaveDeck()}"
                            oncomplete="PF('deckEditDialog').hide()"
                            update=":deckTabs:privateDecksForm:decksView" />
                    </h:panelGrid>
                </p:outputPanel>
            </p:dialog>

            <!-- Deletion confirmation dialog -->
            <p:confirmDialog global="true" showEffect="fade" hideEffect="fade"
                width="300">
                <p:commandButton value="Yes" type="button"
                    styleClass="ui-confirmdialog-yes btn-light" />
                <p:commandButton value="No" type="button"
                    styleClass="ui-confirmdialog-no" />
            </p:confirmDialog>

        </h:form>

    </div>
</ui:composition>
</code>```

cardListController

```<code>package at.qe.skeleton.ui.controllers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import at.qe.skeleton.model.Deck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import at.qe.skeleton.model.Card;
import at.qe.skeleton.services.CardService;

/**
 * Controller for the Card list view.
 *
 * This class is part of the skeleton project provided for students of the
 * course "Software Architecture" offered by Innsbruck University.
*/
@Component
@Scope("view")
public class CardListController implements Serializable {

    @Autowired
    private CardService cardService;

    /**
     * Returns a list of all Cards.
     *
     * @return Collection
     */
    public Collection<Card> getCards() {
        return cardService.getAll();
    }

    /**
     * Returns a list of all Cards.
     *
     * @return Collection
     */
    public Collection<Card> getEnabledCardsOfOneDeckByDeckId(Integer deckId) {
        if(deckId == null)
            return new ArrayList<>();

        return cardService.findAllEnabledCardsByDeckId(deckId);
    }

    public void print(int deckId) {
        System.out.println("deckId is " + deckId);
    }

    /**
     * Returns the current Deck.
     *
     * @return Deck
     */
    public Deck getDeck(Integer deckId) {

        return cardService.findDeck(deckId);
    }
}

</code>```

i tried to change action to actionListener as somebody said in a forum.
and i figured out it may has to do with Mojarra but dont really underdtand why.

Title: parameter goes null when using <p:commandButton> (Mojarra 2.3)

Body:
the xhtml file is getting a Integer parameter which is saved as deck_id. In that xhtml file it is used normally and it works as in the header but when i want to combine it with a
 the param goes to null. I dont know why and I have no idea how to solve it.
As i am new in programming and that is my first project I am lost right now and hours of google didnt help.

the deck_id works  fine in  #{deckListController.getDeckByDeckId(deck_id).name} but doesnt work anymore at

 -->

By pressing the New Card Button i just added a function which prints the deck_id (as u can see in the newCardDialog) in the console and it prints 0 but it should be the ID of the given deck.

xhtml file deck-detail view

    <ui:param name="deck_id" value="#{param['deck_id']}"/>
    <ui:define name="content">

Cards of
            #{deckListController.getDeckByDeckId(deck_id).name}

            <h:form id="newCardForm">

                        <f:setPropertyActionListener
                            value="#{deckListController.getDeckByDeckId(deck_id)}"
                            target="#{deckDetailController.deck}" />

                        <h:panelGrid columns="2">

                        </h:panelGrid>

                        <h:panelGrid columns="2">

                        </h:panelGrid>

                        <h:panelGrid columns="3">

                        </h:panelGrid>

                        <h:panelGrid columns="2">

                        </h:panelGrid>
                        <h:panelGrid columns="2">

                    </h:panelGrid>
                        <h:panelGrid columns="3">

                        </h:panelGrid>

            </h:form>

            <h:form id="cardForm">

Question:

#{card.contentFront}

                                <f:setPropertyActionListener value="#{card}"
                                                            target="#{cardDetailController.card}" />

                                <f:setPropertyActionListener value="#{card}"
                                                            target="#{cardDetailController.card}" />

                        <h:panelGrid columns="2">

                        </h:panelGrid>
                        <h:panelGrid columns="3">

                        </h:panelGrid>

            </h:form>

    </ui:define>
</ui:composition>

xhtml file where the param is given to deck-detail view

<ui:composition xmlns="http://www.w3c.org/1999/xhtml"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    xmlns:p="http://primefaces.org/ui">

        <h:form id="newDeckForm">

                    <h:panelGrid columns="2">

                    </h:panelGrid>
                    <h:panelGrid columns="3">

                    </h:panelGrid>

        </h:form>

        <h:form id="privateDecksForm">

                            <f:setPropertyActionListener value="#{deck}"
                                                         target="#{deckDetailController.deck}" />

                            <f:setPropertyActionListener value="#{deck}"
                                                         target="#{deckDetailController.deck}" />

#{deck.name}

#{deck.description}

                            New cards: #{deckDetailController.getNewCardsCount(deck)}

                            Repeatable cards: #{deckDetailController.getRepeatableCardsCount(deck)}

                            <f:param name="deck_id" value="#{deck.deckID}" />

                            <f:param name="deck_id" value="#{deck.deckID}" />

                    <h:panelGrid columns="2">

                    </h:panelGrid>
                    <h:panelGrid columns="2">

                    </h:panelGrid>
                    <h:panelGrid columns="3">

                    </h:panelGrid>

        </h:form>

</ui:composition>

cardListController

package at.qe.skeleton.ui.controllers;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import at.qe.skeleton.model.Deck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import at.qe.skeleton.model.Card;
import at.qe.skeleton.services.CardService;

/**
 * Controller for the Card list view.
 *
 * This class is part of the skeleton project provided for students of the
 * course "Software Architecture" offered by Innsbruck University.
*/
@Component
@Scope("view")
public class CardListController implements Serializable {

    @Autowired
    private CardService cardService;

    /**
     * Returns a list of all Cards.
     *
     * @return Collection
     */
    public Collection<Card> getCards() {
        return cardService.getAll();
    }

    /**
     * Returns a list of all Cards.
     *
     * @return Collection
     */
    public Collection<Card> getEnabledCardsOfOneDeckByDeckId(Integer deckId) {
        if(deckId == null)
            return new ArrayList<>();

        return cardService.findAllEnabledCardsByDeckId(deckId);
    }

    public void print(int deckId) {
        System.out.println("deckId is " + deckId);
    }

    /**
     * Returns the current Deck.
     *
     * @return Deck
     */
    public Deck getDeck(Integer deckId) {

        return cardService.findDeck(deckId);
    }
}

i tried to change action to actionListener as somebody said in a forum.
and i figured out it may has to do with Mojarra but dont really underdtand why.


来源: stackexchange

问:
Why can't NSE be used with functions stored in lists in R?
I recently found it useful to store functions in lists for data analysis. However, I noticed that normal functions and functions stored in lists behave differently. I am not familiar with all of them, but it seems that functions stored in lists are not specifically allowed to use the NSE notation. An example is shown below.

Why can't NSE be used with functions stored in lists?
Also, what is the overall difference between normal functions and functions stored in lists?

# function stored in list
x <- tibble::lst(
  f = \(var) {
    var <- rlang::enquo(var)
    mtcars |>
      dplyr::summarise(mean = mean(!!var))
  }
)

x$f(var = mpg)
#> Warning in mean.default(function (x, y = NULL, na.rm = FALSE, use) : argument is
#> not numeric or logical: returning NA
#>   mean
#> 1   NA

# normal function
f <- \(var) {
  var <- rlang::enquo(var)
  mtcars |>
    dplyr::summarise(mean = mean(!!var))
}

f(var = mpg)
#>       mean
#> 1 20.09062
```
<p><sup>Created on 2023-01-07 with reprex v2.0.2</sup></p>
<hr />
<p><strong>Edit</strong>:
As zephryl pointed out, it looks like the problem was caused by using <code>tibble::lst()</code>. I still don't know why it doesn't work with <code>lst()</code>, but it looks like I should just use <code>list()</code> for now.</p>
<hr />
<p><strong>Edit2</strong>:
G. Grothendieck pointed out that an NSE implementation using <code>eval()</code> and <code>substitute()</code> would work fine with <code>lst()</code>. So, the initial problem seems to be a complex one involving the use of <code>lst()</code> and the NSE implementation with {rlang}.</p>
<p>I do not know more than this with my little knowledge, but new answers are always welcome.</p>
<pre class="lang-r prettyprint-override"><code>x <- tibble::lst(
  f = \(var) eval(substitute({
    mtcars |> dplyr::summarise(mean = mean(var))
    }))
  )
x$f(var = mpg)
#>       mean
#> 1 20.09062
</code>```

In addition, a very interesting technique was demonstrated.

x <- tibble::lst(
  f = !!\(var) {
    var <- rlang::enquo(var)
    mtcars |>
      dplyr::summarise(mean = mean(!!var))
  }
)
x$f(var = mpg)
#>       mean
#> 1 20.09062
```

Created on 2023-01-07 with reprex v2.0.2

ContentLicense: CC BY-SA 4.0

Body:
I recently found it useful to store functions in lists for data analysis. However, I noticed that normal functions and functions stored in lists behave differently. I am not familiar with all of them, but it seems that functions stored in lists are not specifically allowed to use the NSE notation. An example is shown below.

Why can't NSE be used with functions stored in lists?
Also, what is the overall difference between normal functions and functions stored in lists?

# function stored in list
x <- tibble::lst(
  f = \(var) {
    var <- rlang::enquo(var)
    mtcars |>
      dplyr::summarise(mean = mean(!!var))
  }
)

x$f(var = mpg)
#> Warning in mean.default(function (x, y = NULL, na.rm = FALSE, use) : argument is
#> not numeric or logical: returning NA
#>   mean
#> 1   NA

# normal function
f <- \(var) {
  var <- rlang::enquo(var)
  mtcars |>
    dplyr::summarise(mean = mean(!!var))
}

f(var = mpg)
#>       mean
#> 1 20.09062

Created on 2023-01-07 with reprex v2.0.2

Edit:
As zephryl pointed out, it looks like the problem was caused by using tibble::lst(). I still don't know why it doesn't work with lst(), but it looks like I should just use list() for now.

Edit2:
G. Grothendieck pointed out that an NSE implementation using eval() and substitute() would work fine with lst(). So, the initial problem seems to be a complex one involving the use of lst() and the NSE implementation with {rlang}.

I do not know more than this with my little knowledge, but new answers are always welcome.

x <- tibble::lst(
  f = \(var) eval(substitute({
    mtcars |> dplyr::summarise(mean = mean(var))
    }))
  )
x$f(var = mpg)
#>       mean
#> 1 20.09062

In addition, a very interesting technique was demonstrated.

x <- tibble::lst(
  f = !!\(var) {
    var <- rlang::enquo(var)
    mtcars |>
      dplyr::summarise(mean = mean(!!var))
  }
)
x$f(var = mpg)
#>       mean
#> 1 20.09062

Created on 2023-01-07 with reprex v2.0.2


问:
What is the equivalent of Image.AFFINE for torch tensor inputs
I am wondering how to rewrite Image.AFFINE to work for torch tensor.

Here is the code:

```<code>            frame = torch.load(file_path + '/' + f)
            offset += random.randrange(-v, v)
            offset = min(offset, 3 * v)
            offset = max(offset, -3 * v)
            frame = frame.transform(frame.size, Image.AFFINE, (1, 0, offset, 0, 1, 0))
            if self.transform is not None:
                frame = self.transform[0](frame)
            frames.append(frame)
</code>```

Body:
I am wondering how to rewrite Image.AFFINE to work for torch tensor.

Here is the code:

            frame = torch.load(file_path + '/' + f)
            offset += random.randrange(-v, v)
            offset = min(offset, 3 * v)
            offset = max(offset, -3 * v)
            frame = frame.transform(frame.size, Image.AFFINE, (1, 0, offset, 0, 1, 0))
            if self.transform is not None:
                frame = self.transform[0](frame)
            frames.append(frame)


问:
Can't find the right name in dictionary and also prints the last value from dictionary
I'm writing the telegram bot, currently I'm doing the buttons which handles the text, if you press the button it's supposed to open the recipe from the dictionary with the name which is the same with the button name. I have over hundreds of recipes, so I don't want to do every button by myself, so I wrote a function which does it, but for some reason it doesn't work properly. It always backs the last value from the dictionary. What should I change?

```<code>for inx, recipe_name in enumerate(breakfast_titles_rus):
    key = f'{inx + 1}. {recipe_name}'
    recipe2idx[key] = inx
for key, inx in recipe2idx.items():
    @dp.message_handler(text=[key])
    async def breakfest_fist_choice(message: types.message):
        print(key)
        name=key.split('.')
        name.pop(0)
        clear=f'{name[0].lstrip()}'
        print(clear)
        if ('item_name', clear) in breakfast_dict.items():
            for k, v in list(breakfast_dict.items())[:inx]:
                breakfast_card_rus=f"\nНазвание: {v['item_name']}\nВремя: " f"{v['item_times']}\nКоличетсво лайков: " f"{v['item_rating']}\nКоличество ингредиентов: " f"{v['items_total_amount_ingridients']}\nКоличество каллорий: " f"{v['item_kcal']}\nКоличество белков: " f"{v['item_belki']}\nКоличество жиров: " f"{v['item_zhiri']}\nКоличество углеводов: " f"{v['item_uglevodi']}\n\nНеобходимые ингредиенты: "f"{v['item_ingridients']}\n\nРецепет: "f"{v['item_recipe']}"f"{v['item_photo']}"
            back_to_menu=KeyboardButton("Назад к началу")
            mark_up=ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(back_to_menu)
            await bot.send_message(message.from_user.id, text=breakfast_card_rus, reply_markup=mark_up)
</code>```

I tried to debug it by myself, and it didn't work.

Body:
I'm writing the telegram bot, currently I'm doing the buttons which handles the text, if you press the button it's supposed to open the recipe from the dictionary with the name which is the same with the button name. I have over hundreds of recipes, so I don't want to do every button by myself, so I wrote a function which does it, but for some reason it doesn't work properly. It always backs the last value from the dictionary. What should I change?

for inx, recipe_name in enumerate(breakfast_titles_rus):
    key = f'{inx + 1}. {recipe_name}'
    recipe2idx[key] = inx
for key, inx in recipe2idx.items():
    @dp.message_handler(text=[key])
    async def breakfest_fist_choice(message: types.message):
        print(key)
        name=key.split('.')
        name.pop(0)
        clear=f'{name[0].lstrip()}'
        print(clear)
        if ('item_name', clear) in breakfast_dict.items():
            for k, v in list(breakfast_dict.items())[:inx]:
                breakfast_card_rus=f"\nНазвание: {v['item_name']}\nВремя: " f"{v['item_times']}\nКоличетсво лайков: " f"{v['item_rating']}\nКоличество ингредиентов: " f"{v['items_total_amount_ingridients']}\nКоличество каллорий: " f"{v['item_kcal']}\nКоличество белков: " f"{v['item_belki']}\nКоличество жиров: " f"{v['item_zhiri']}\nКоличество углеводов: " f"{v['item_uglevodi']}\n\nНеобходимые ингредиенты: "f"{v['item_ingridients']}\n\nРецепет: "f"{v['item_recipe']}"f"{v['item_photo']}"
            back_to_menu=KeyboardButton("Назад к началу")
            mark_up=ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=True).add(back_to_menu)
            await bot.send_message(message.from_user.id, text=breakfast_card_rus, reply_markup=mark_up)

I tried to debug it by myself, and it didn't work.


问:
AWS Elasticache tags
I'm new in aws technology and redis. I want get one tag value by tag key in golang. Now I can use ListTagsForResource() func, but this func return to me all listing of tags. I want get 1 tag. How I can achieve this?

I could not find normal information either on the Internet or in the documentation.

ARN - amazon resource name,
cred - StaticCredintials with access keys

```<code>    svc := elasticache.New(mySession, aws.NewConfig().WithRegion("us-east-1").WithCredentials(creds))
input := &elasticache.ListTagsForResourceInput{
    ResourceName: aws.String(ARN),
}

result, err := svc.ListTagsForResource(input)
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case elasticache.ErrCodeCacheClusterNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeInvalidReplicationGroupStateFault:
            fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
        case elasticache.ErrCodeReplicationGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeReservedCacheNodeNotFoundFault:
            fmt.Println(elasticache.ErrCodeReservedCacheNodeNotFoundFault, aerr.Error())
        case elasticache.ErrCodeSnapshotNotFoundFault:
            fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
        case elasticache.ErrCodeUserNotFoundFault:
            fmt.Println(elasticache.ErrCodeUserNotFoundFault, aerr.Error())
        case elasticache.ErrCodeUserGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeUserGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeInvalidARNFault:
            fmt.Println(elasticache.ErrCodeInvalidARNFault, aerr.Error())
        default:
            fmt.Println(aerr.Error())
        }
    } else {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
    }
    return
}

fmt.Println("Get Data", result)
</code>```

I found only this function for get data from cluster (ListTagsForResource).

Console

```<code>PS C:\Users\MrDipper\go\src\redisConn> go run main.go
</code>```

Get Data {
{
Key: "Service",
Value: "ElastiCache"
},
{
Key: "APIVersion",
Value: "20150202"
},
{
Key: "APIersion",
Value: "20150202"
},
{
Key: "Sevice",
Value: "ElastiCache"
}
]
}

Title: AWS Elasticache tags

Body:
I'm new in aws technology and redis. I want get one tag value by tag key in golang. Now I can use ListTagsForResource() func, but this func return to me all listing of tags. I want get 1 tag. How I can achieve this?

I could not find normal information either on the Internet or in the documentation.

ARN - amazon resource name,
cred - StaticCredintials with access keys

    svc := elasticache.New(mySession, aws.NewConfig().WithRegion("us-east-1").WithCredentials(creds))
input := &elasticache.ListTagsForResourceInput{
    ResourceName: aws.String(ARN),
}

result, err := svc.ListTagsForResource(input)
if err != nil {
    if aerr, ok := err.(awserr.Error); ok {
        switch aerr.Code() {
        case elasticache.ErrCodeCacheClusterNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheClusterNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheParameterGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheParameterGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheSecurityGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheSecurityGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeCacheSubnetGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeCacheSubnetGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeInvalidReplicationGroupStateFault:
            fmt.Println(elasticache.ErrCodeInvalidReplicationGroupStateFault, aerr.Error())
        case elasticache.ErrCodeReplicationGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeReplicationGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeReservedCacheNodeNotFoundFault:
            fmt.Println(elasticache.ErrCodeReservedCacheNodeNotFoundFault, aerr.Error())
        case elasticache.ErrCodeSnapshotNotFoundFault:
            fmt.Println(elasticache.ErrCodeSnapshotNotFoundFault, aerr.Error())
        case elasticache.ErrCodeUserNotFoundFault:
            fmt.Println(elasticache.ErrCodeUserNotFoundFault, aerr.Error())
        case elasticache.ErrCodeUserGroupNotFoundFault:
            fmt.Println(elasticache.ErrCodeUserGroupNotFoundFault, aerr.Error())
        case elasticache.ErrCodeInvalidARNFault:
            fmt.Println(elasticache.ErrCodeInvalidARNFault, aerr.Error())
        default:
            fmt.Println(aerr.Error())
        }
    } else {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
    }
    return
}

fmt.Println("Get Data", result)

I found only this function for get data from cluster (ListTagsForResource).

Console

PS C:\Users\MrDipper\go\src\redisConn> go run main.go

Get Data {
{
Key: "Service",
Value: "ElastiCache"
},
{
Key: "APIVersion",
Value: "20150202"
},
{
Key: "APIersion",
Value: "20150202"
},
{
Key: "Sevice",
Value: "ElastiCache"
}
]
}


问:
C++ Index may have a value of '1000000' which is out of bounds

Intro

I do performance tests with the following array sizes 1,000,000, 10,000,000 and 100,000,000. My IDE (CLion) shows me the following warning message:

Index may have a value of '1000000' which is out of bounds

This warning appears only in the first for-loop in each line where bodies[i] is accessed:

    void doPerformanceTestBodiesAsAoS(const size_t n) {
        auto *bodies = new Body<long double, double[3], double[3]>[n];

        for (size_t i = 0; i < n; ++i) {
            bodies[i].mass = static_cast<double>(i);
            bodies[i].position[0] = static_cast<double>(i);
            bodies[i].position[1] = static_cast<double>(i + 1);
            bodies[i].position[2] = static_cast<double>(i + 2);
            bodies[i].velocity[0] = static_cast<double>(i);
            bodies[i].velocity[1] = static_cast<double>(i + 1);
            bodies[i].velocity[2] = static_cast<double>(i + 2);
        }

        const auto startTimeInNanoSeconds = std::chrono::high_resolution_clock::now();
        for (size_t i = 0; i < (n - 1); ++i) {
            const size_t nextBodyIndex = i + 1;
            std::sqrt(
                    PhysicsEngine::math::pow2(bodies[i].position[0] - bodies[nextBodyIndex].position[0]) +
                    PhysicsEngine::math::pow2(bodies[i].position[1] - bodies[nextBodyIndex].position[1]) +
                    PhysicsEngine::math::pow2(bodies[i].position[2] - bodies[nextBodyIndex].position[2])
            );
        }
        auto endTimeInNanoSeconds = std::chrono::high_resolution_clock::now();
        std::cout.precision(17);
        std::cout << "Processing of AoS took: "
                  << static_cast<long double>(std::chrono::duration_cast<std::chrono::nanoseconds>(endTimeInNanoSeconds - startTimeInNanoSeconds).count()) / 1e+9 << " seconds for N = " << n << std::endl;

        delete[] bodies;
    }
// ...

TEST(PerformanceTest, PerformanceTest1MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(1'000'000);
}

TEST(PerformanceTest, PerformanceTest10MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(10'000'000);
}

TEST(PerformanceTest, PerformanceTest100MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(100'000'000);
}
```
<h1>Problem</h1>
<p>I'm now unsure whether this warning <strong>is a false positive (?!)</strong> or whether I'm missing something and thus possibly falsifying my performance tests.</p>
<h1>What have I already done</h1>
<ol>
<li>I have checked that on my system sizes 1,000,000 - 100,000,000 do not exceed the MAX_INT value to ensure indexing does not arithmetically overflow. This shouldn't happen because <code>int</code> is 4 bytes and <code>size_t</code> is 8 bytes on my system.</li>
<li>I restarted my IDE several times, cleaned up caches etc.</li>
<li>I changed every <code>size_t</code> to <code>int</code> because I assume the index operator <code>[]</code> expects an <code>int</code> instead of <code>size_t</code>? But that didn't resolve the warning.</li>
<li>I searched for similar question but couldn't find any.</li>
</ol>
<p>So I'm asking for a code review, whether it's false positive or I have a bug.</p>
<h1>Additional information</h1>
<ol>
<li>I am using Windows 10 64, MingGW and an Intel processor.</li>
<li>The <code>typedef</code> of <code>size_t</code> is:</li>
</ol>
<pre class="lang-cpp prettyprint-override"><code>#ifdef _WIN64
  __MINGW_EXTENSION typedef unsigned __int64 size_t;
#else
  typedef unsigned int size_t;
#endif /* _WIN64 */
</code>```

Body:
Intro

I do performance tests with the following array sizes 1,000,000, 10,000,000 and 100,000,000. My IDE (CLion) shows me the following warning message:

Index may have a value of '1000000' which is out of bounds

This warning appears only in the first for-loop in each line where bodies[i] is accessed:

    void doPerformanceTestBodiesAsAoS(const size_t n) {
        auto *bodies = new Body<long double, double[3], double[3]>[n];

        for (size_t i = 0; i < n; ++i) {
            bodies[i].mass = static_cast<double>(i);
            bodies[i].position[0] = static_cast<double>(i);
            bodies[i].position[1] = static_cast<double>(i + 1);
            bodies[i].position[2] = static_cast<double>(i + 2);
            bodies[i].velocity[0] = static_cast<double>(i);
            bodies[i].velocity[1] = static_cast<double>(i + 1);
            bodies[i].velocity[2] = static_cast<double>(i + 2);
        }

        const auto startTimeInNanoSeconds = std::chrono::high_resolution_clock::now();
        for (size_t i = 0; i < (n - 1); ++i) {
            const size_t nextBodyIndex = i + 1;
            std::sqrt(
                    PhysicsEngine::math::pow2(bodies[i].position[0] - bodies[nextBodyIndex].position[0]) +
                    PhysicsEngine::math::pow2(bodies[i].position[1] - bodies[nextBodyIndex].position[1]) +
                    PhysicsEngine::math::pow2(bodies[i].position[2] - bodies[nextBodyIndex].position[2])
            );
        }
        auto endTimeInNanoSeconds = std::chrono::high_resolution_clock::now();
        std::cout.precision(17);
        std::cout << "Processing of AoS took: "
                  << static_cast<long double>(std::chrono::duration_cast<std::chrono::nanoseconds>(endTimeInNanoSeconds - startTimeInNanoSeconds).count()) / 1e+9 << " seconds for N = " << n << std::endl;

        delete[] bodies;
    }
// ...

TEST(PerformanceTest, PerformanceTest1MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(1'000'000);
}

TEST(PerformanceTest, PerformanceTest10MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(10'000'000);
}

TEST(PerformanceTest, PerformanceTest100MioBodiesAsAoS) {
    doPerformanceTestBodiesAsAoS(100'000'000);
}

Problem

I'm now unsure whether this warning is a false positive (?!) or whether I'm missing something and thus possibly falsifying my performance tests.

What have I already done

I have checked that on my system sizes 1,000,000 - 100,000,000 do not exceed the MAX_INT value to ensure indexing does not arithmetically overflow. This shouldn't happen because int is 4 bytes and size_t is 8 bytes on my system.

I restarted my IDE several times, cleaned up caches etc.

I changed every size_t to int because I assume the index operator [] expects an int instead of size_t? But that didn't resolve the warning.

I searched for similar question but couldn't find any.

So I'm asking for a code review, whether it's false positive or I have a bug.

Additional information

I am using Windows 10 64, MingGW and an Intel processor.

The typedef of size_t is:

#ifdef _WIN64
  __MINGW_EXTENSION typedef unsigned __int64 size_t;
#else
  typedef unsigned int size_t;
#endif /* _WIN64 */


问:
Adminer changes the name of the foreign key when I change its cascade options
I'm using Adminer to manage my MariaDB database.

There is a problem though. When I want to change a foreign key that has a name, it changes the name to its default.

How can I prevent that?

I need the name of my foreign keys to remain what I have named them, because of some policies that exist in my company and from our customers.


问:
No module named 'sklearn' while running django server
I saved a model using joblib and was trying to run server using but it shows no module as sklearn even though it is downloaded in the environment, can anyone please help?</p>


问:
R create serial number based on two different columns
I wanted to create serial number based on two different columns. 'item' should be assigned serial number based on each 'name'. Please let me know how to do this.

```<code>name <-  c('Name1', 'Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3', 'Name3')
item <-  c('item1' , 'item2' , 'item1','item2','item3','item1','item1','item3')

     name  item
1 Name1 item1
2 Name1 item2
3 Name2 item1
4 Name2 item2
5 Name2 item3
6 Name3 item1
7 Name3 item1
8 Name3 item3
</code>```

Expected out put.

```<code>  name  item sl.no
1 Name1 item1     1
2 Name1 item2     2
3 Name2 item1     1
4 Name2 item2     2
5 Name2 item3     3
6 Name3 item1     1
7 Name3 item1     1
8 Name3 item3     2
</code>```

Body:
I wanted to create serial number based on two different columns. 'item' should be assigned serial number based on each 'name'. Please let me know how to do this.

name <-  c('Name1', 'Name1', 'Name2', 'Name2', 'Name2', 'Name3', 'Name3', 'Name3')
item <-  c('item1' , 'item2' , 'item1','item2','item3','item1','item1','item3')

     name  item
1 Name1 item1
2 Name1 item2
3 Name2 item1
4 Name2 item2
5 Name2 item3
6 Name3 item1
7 Name3 item1
8 Name3 item3

Expected out put.

  name  item sl.no
1 Name1 item1     1
2 Name1 item2     2
3 Name2 item1     1
4 Name2 item2     2
5 Name2 item3     3
6 Name3 item1     1
7 Name3 item1     1
8 Name3 item3     2


问:
How do I create and use a spring boot testing utility class?
I want to create a utility class just for my tests that have some methods that all tests will use to reduce code duplication.

Where do I create this class and how do I import it in my tests?

Errors

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'FooTest': Unsatisfied dependency
expressed through field 'myTestUtils'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:

No qualifying bean of type 'com.utils.MyTestUtils' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

</code>```

Files

```<code>// src/test/com/example/utils/MyTestUtils.java

public class MyTestUtils {

 public String foo = "bar";

}
</code>```
```<code>// src/test/com/example/services/FooTest.java

import com.example.utils.TestUtils;

@SpringBootTest

public class FooTest {

  // If I remove this decorator I get that this.testUtils is null
  @Autowired
  MyTestUtils myTestUtils

  @Test
  public void testFoo() throws Exception {}
  Asserthat(myTestUtils.foo).equals("bar")
}
</code>```

Update

I solved the problem above with annotating the myTestUtils class with @Service

This works.

```<code>// src/test/com/example/utils/MyTestUtils.java

@Service
public class MyTestUtils {

 public String foo = "bar";

}
</code>```

Body:
I want to create a utility class just for my tests that have some methods that all tests will use to reduce code duplication.

Where do I create this class and how do I import it in my tests?

Errors

org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'FooTest': Unsatisfied dependency
expressed through field 'myTestUtils'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException:

No qualifying bean of type 'com.utils.MyTestUtils' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Files

// src/test/com/example/utils/MyTestUtils.java

public class MyTestUtils {

 public String foo = "bar";

}

// src/test/com/example/services/FooTest.java

import com.example.utils.TestUtils;

@SpringBootTest

public class FooTest {

  // If I remove this decorator I get that this.testUtils is null
  @Autowired
  MyTestUtils myTestUtils

  @Test
  public void testFoo() throws Exception {}
  Asserthat(myTestUtils.foo).equals("bar")
}

Update

I solved the problem above with annotating the myTestUtils class with @Service

This works.

// src/test/com/example/utils/MyTestUtils.java

@Service
public class MyTestUtils {

 public String foo = "bar";

}


问:
connect ECONNREFUSED 127.0.0.1:5432 when trying to deploy nestjs with Postgres using docker
So I am trying to deploy my nestjs project to digitalocean and having problems with connecting database. First I created network and then run the following command in my server

```<code>docker run --name postgre -d -p 5432:5432 --network backend -e POSTGRES_PASSWORD=0808 -e POSTGRES_DB=webs postgres
</code>```

Then in .env.production I change the host to the created container name as follows

```<code>POSTGRES_HOST=postgre
</code>```

and keep the rest the same as in .env.deployment. My env:

```<code>POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_DB=webs
POSTGRES_PASSWORD=0808
</code>```

Then I am trying to run my project by pulling the Dockerfile which I pushed to my to dockerhub as follows:

```<code>docker container run -p 3000:3000 --network backend --env .env.production --name mindgame musnn/mindgame
</code>```

And it gives out the following error:

```<code>[Nest] 1  - 01/07/2023, 10:02:59 AM   ERROR [ExceptionHandler] connect ECONNREFUSED 127.0.0.1:5432
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432
</code>```

How can I solve this?

My app.module.ts:

```<code>import { AuthModule } from './auth/auth.module';
import { UsersModule } from './user/user.module';
import { BoardModule } from './board/board.module';
import { MessagesModule } from './messages/messages.module';
import { BoardCards } from './board/board-cards.model';
import { UserCards } from './user/user-card.model';
import { SequelizeModule } from '@nestjs/sequelize';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { User } from './user/user.model';
import { Board } from './board/board.model';
import { Card } from './board/card.model';
import {ConfigModule} from "@nestjs/config";

@Module({
  imports: [
    ConfigModule.forRoot({
           envFilePath: `.env.${process.env.NODE_ENV}`
        }),
    SequelizeModule.forRoot({
            dialect: 'postgres',
            protocol: 'postgres',
            host: process.env.POSTGRES_HOST,
            port: Number(process.env.POSTGRES_PORT),
            username: process.env.POSTGRES_USER,
            password: process.env.POSTGRES_PASSWORD,
            database: process.env.POSTGRES_DB,
            models: [User, Board, Card, UserCards, BoardCards],
            autoLoadModels: true
        }),
       MessagesModule,
       BoardModule,
       UsersModule,
       AuthModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

</code>```

My Dockerfile (taken from the the internet documentation):

```<code>#using official 'node' image, with the alpine 3.15 branch as base image for development stage
FROM node:18.12.1-alpine3.15 As development

# create working directory inside the container
WORKDIR /usr/src/app

#copy package.json and package-lock.json files
COPY package*.json ./

#install dependencies
RUN npm install --only=development

#copy all files from current directory into container
COPY . .

# build the application
RUN npm run build

# expose on port 3000
EXPOSE 3000

#using official 'node' image, with the alpine 3.15 branch as base image for production stage
FROM node:18.12.1-alpine3.15 As production

#define the default value for NODE_ENV
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

# create working directory inside the container
WORKDIR /usr/src/app

#copy package.json and package-lock.json files
COPY package*.json ./

# install only dependencies defined in 'dependencies' in package.json
RUN npm install --only=production

#copy all files from current directory into container
COPY . .

# copy files
COPY --from=development /usr/src/app/dist ./dist

# command to start the server using the production build
CMD ["node", "dist/main"]
</code>```

Body:
So I am trying to deploy my nestjs project to digitalocean and having problems with connecting database. First I created network and then run the following command in my server

docker run --name postgre -d -p 5432:5432 --network backend -e POSTGRES_PASSWORD=0808 -e POSTGRES_DB=webs postgres

Then in .env.production I change the host to the created container name as follows

POSTGRES_HOST=postgre

and keep the rest the same as in .env.deployment. My env:

POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_DB=webs
POSTGRES_PASSWORD=0808

Then I am trying to run my project by pulling the Dockerfile which I pushed to my to dockerhub as follows:

docker container run -p 3000:3000 --network backend --env .env.production --name mindgame musnn/mindgame

And it gives out the following error:

[Nest] 1  - 01/07/2023, 10:02:59 AM   ERROR [ExceptionHandler] connect ECONNREFUSED 127.0.0.1:5432
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432

How can I solve this?

My app.module.ts:

import { AuthModule } from './auth/auth.module';
import { UsersModule } from './user/user.module';
import { BoardModule } from './board/board.module';
import { MessagesModule } from './messages/messages.module';
import { BoardCards } from './board/board-cards.model';
import { UserCards } from './user/user-card.model';
import { SequelizeModule } from '@nestjs/sequelize';
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { User } from './user/user.model';
import { Board } from './board/board.model';
import { Card } from './board/card.model';
import {ConfigModule} from "@nestjs/config";

@Module({
  imports: [
    ConfigModule.forRoot({
           envFilePath: `.env.${process.env.NODE_ENV}`
        }),
    SequelizeModule.forRoot({
            dialect: 'postgres',
            protocol: 'postgres',
            host: process.env.POSTGRES_HOST,
            port: Number(process.env.POSTGRES_PORT),
            username: process.env.POSTGRES_USER,
            password: process.env.POSTGRES_PASSWORD,
            database: process.env.POSTGRES_DB,
            models: [User, Board, Card, UserCards, BoardCards],
            autoLoadModels: true
        }),
       MessagesModule,
       BoardModule,
       UsersModule,
       AuthModule
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

My Dockerfile (taken from the the internet documentation):

#using official 'node' image, with the alpine 3.15 branch as base image for development stage
FROM node:18.12.1-alpine3.15 As development

# create working directory inside the container
WORKDIR /usr/src/app

#copy package.json and package-lock.json files
COPY package*.json ./

#install dependencies
RUN npm install --only=development

#copy all files from current directory into container
COPY . .

# build the application
RUN npm run build

# expose on port 3000
EXPOSE 3000

#using official 'node' image, with the alpine 3.15 branch as base image for production stage
FROM node:18.12.1-alpine3.15 As production

#define the default value for NODE_ENV
ARG NODE_ENV=production
ENV NODE_ENV=${NODE_ENV}

# create working directory inside the container
WORKDIR /usr/src/app

#copy package.json and package-lock.json files
COPY package*.json ./

# install only dependencies defined in 'dependencies' in package.json
RUN npm install --only=production

#copy all files from current directory into container
COPY . .

# copy files
COPY --from=development /usr/src/app/dist ./dist

# command to start the server using the production build
CMD ["node", "dist/main"]


问:
How to implement SVGs with Openlayers 7 in react?
I am trying to figure out, how to implement an svg file as Layer in Openlayers with react. I tried Imagelayer and Vectorlayer. The example in the docs from ol doesn`t works for my case. The svg is located below src/assets/example.svg

Anyone who can help me?


问:
Checkout.com Payment response JavaScript
I am trying to integrate https://www.checkout.com/ in my app.
I tried there sample code to get token.

```<code>
Frames.addEventHandler(
            Frames.Events.CARD_TOKENIZED,
            function (data) {
                Frames.addCardToken(form, data.token);
                if (data.token) {
                    confirmPayment(data.token);
                } else {
                    console.log(data);
                }
             }

        );
</code>```

I tried https://api.sandbox.checkout.com/payments/ api to do the payments,
payment successfully captures, but I am unable to read its response to or redirect user on successfully attempt.

```<code>async function confirmPayment(token) {

            // Storing response
            const response = await fetch('https://api.sandbox.checkout.com/payments/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer sk_sbox_..abc'
                },

                body: JSON.stringify({
                    "source": {
                        "type": "token",
                        "token": token
                    },
                    "Capture": true,
                    "processing_channel_id": "pc_..abc",
                    'amount': 1000,
                    'currency': 'USD',
                    "3ds": {
                        "enabled": false
                    },
                    "customer": {
                        "email": "test.testUI@example.com",
                        "name": "John Test"
                    },
                    'reference': 'ORD-175-759',
                    "metadata": {
                        "udf1": "UI-CALL-TEST",
                        "coupon_code": "NY2018",
                        "partner_id": 123989
                    },
                    "success_url": "http://example.com/payments/success",
                    "failure_url": "http://example.com/payments/fail"
                })
            });

            // Storing data in form of JSON
            var data = await response.json();
            console.log(data);
            if (response) {

            }
            show(data);
        }

</code>```

I want to get a payment response like errors "card invalid" etc
Also redirect to Url if successful.

Please let me know if this is a correct way to do the payment or If there any JavaScript library that I can use?
I want to do payment on client side and use webhook later.

Thank you

Body:
I am trying to integrate https://www.checkout.com/ in my app.
I tried there sample code to get token.

Frames.addEventHandler(
            Frames.Events.CARD_TOKENIZED,
            function (data) {
                Frames.addCardToken(form, data.token);
                if (data.token) {
                    confirmPayment(data.token);
                } else {
                    console.log(data);
                }
             }

        );

I tried https://api.sandbox.checkout.com/payments/ api to do the payments,
payment successfully captures, but I am unable to read its response to or redirect user on successfully attempt.

async function confirmPayment(token) {

            // Storing response
            const response = await fetch('https://api.sandbox.checkout.com/payments/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': 'Bearer sk_sbox_..abc'
                },

                body: JSON.stringify({
                    "source": {
                        "type": "token",
                        "token": token
                    },
                    "Capture": true,
                    "processing_channel_id": "pc_..abc",
                    'amount': 1000,
                    'currency': 'USD',
                    "3ds": {
                        "enabled": false
                    },
                    "customer": {
                        "email": "test.testUI@example.com",
                        "name": "John Test"
                    },
                    'reference': 'ORD-175-759',
                    "metadata": {
                        "udf1": "UI-CALL-TEST",
                        "coupon_code": "NY2018",
                        "partner_id": 123989
                    },
                    "success_url": "http://example.com/payments/success",
                    "failure_url": "http://example.com/payments/fail"
                })
            });

            // Storing data in form of JSON
            var data = await response.json();
            console.log(data);
            if (response) {

            }
            show(data);
        }

I want to get a payment response like errors "card invalid" etc
Also redirect to Url if successful.

Please let me know if this is a correct way to do the payment or If there any JavaScript library that I can use?
I want to do payment on client side and use webhook later.

Thank you


问:
Failed to load pre trained onnx models in OpenCV C++
This is my first time with ONNX models and I’m not sure if I’m having a newbie problem so sorry in advance!

I’ve just tried to load a couple of models and I have the same assert always:

```<code>[ERROR:0@0.460] global onnx_importer.cpp:1054 cv::dnn::dnn4_v20221220::ONNXImporter::handleNode DNN/ONNX: ERROR during processing node with 3 inputs and 1 outputs: [Concat]:(onnx_node!Concat_2) from domain='ai.onnx'
OpenCV: terminate handler is called! The last OpenCV error is:
OpenCV(4.7.0-dev) Error: Unspecified error (> Node [Concat@ai.onnx]:(onnx_node!Concat_2) parse error: OpenCV(4.7.0-dev) C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\dnn\src\layers\concat_layer.cpp:105: error: (-215:Assertion failed) curShape.size() == outputs[0].size() in function 'cv::dnn::ConcatLayerImpl::getMemoryShapes'
> ) in cv::dnn::dnn4_v20221220::ONNXImporter::handleNode, file C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\dnn\src\onnx\onnx_importer.cpp, line 1073
</code>```

Both models come from https://github.com/PeterL1n/RobustVideoMatting and they are “rvm_resnet50_fp32.onnx” and “rvm_mobilenetv3_fp32.onnx”

Obviously I’m loading them with

```<code>robustNN = cv::dnn::readNetFromONNX(robustNNPath);
</code>```

Thank you in advance for any tip!

Body:
This is my first time with ONNX models and I’m not sure if I’m having a newbie problem so sorry in advance!

I’ve just tried to load a couple of models and I have the same assert always:

[ERROR:0@0.460] global onnx_importer.cpp:1054 cv::dnn::dnn4_v20221220::ONNXImporter::handleNode DNN/ONNX: ERROR during processing node with 3 inputs and 1 outputs: [Concat]:(onnx_node!Concat_2) from domain='ai.onnx'
OpenCV: terminate handler is called! The last OpenCV error is:
OpenCV(4.7.0-dev) Error: Unspecified error (> Node [Concat@ai.onnx]:(onnx_node!Concat_2) parse error: OpenCV(4.7.0-dev) C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\dnn\src\layers\concat_layer.cpp:105: error: (-215:Assertion failed) curShape.size() == outputs[0].size() in function 'cv::dnn::ConcatLayerImpl::getMemoryShapes'
> ) in cv::dnn::dnn4_v20221220::ONNXImporter::handleNode, file C:\GHA-OCV-2\_work\ci-gha-workflow\ci-gha-workflow\opencv\modules\dnn\src\onnx\onnx_importer.cpp, line 1073

Both models come from https://github.com/PeterL1n/RobustVideoMatting and they are “rvm_resnet50_fp32.onnx” and “rvm_mobilenetv3_fp32.onnx”

Obviously I’m loading them with

robustNN = cv::dnn::readNetFromONNX(robustNNPath);

Thank you in advance for any tip!


问:
Efficient approach of sending data from a .NET based program to a C++ based OpenGL GUI
We're writing a visualization tool of complex 3D geometries of a existing 3D modelling software (A). After some initial experiments, we realized that the A does not have the API for all of our visualization purposes, and we decided to write our own one in c++ with OpenGL as a GUI executable program B, which can be called out from A.

For A (.NET based):
We'll write a small plugin for A that can call out B and send geometry data to B.

For B:
An OpenGL window (perhaps with simple buttons), called out by A, can receive data from A and visualize it.

For the data:
mesh-based or line-based geometric data, million-billion level.

We're aiming for instant feedback, as interactivity is very important for 3D designers. We are considering using WebSocket for the transmission, but not sure if this is the right choice.

We're pretty ignorant when talking about data transmission between programmes. So any experience and thoughts are welcome.

EDIT:

From the comments, it seems TCP is good enough for this task, unless series performance is needed and we can go for memory-mapped files.

The next question then would be, is there any recommendation on TCP libraries?

I did some simple search in the vcpkg package collection and github, it seems some TCP lib are designed to focus on heavy Internet use.

I only need one simple and easy-to-use cpp library for 1-2 client communication between local software, and I'm not sure if there's a difference between the use case.


问:
Routes are not working in cPanel deployed json-server
I recently tried to deploy json-server to my interserver's shared hosting plan via cPanel.
I uploaded the app and configured a Node.js app and I'm able to access the endpoint via 'https://soltonbaev.com/json-server/api/contacts' however the jsonServer.rewriter() is not rewriting the "/api/" route to the "/".

In addition I cannot access the individual object via it's id, like for instance "https://soltonbaev.com/json-server/api/contacts/1". Server returns 404.

So clearly, JSON server is not picking up the routes when it is supposed to.

Here is the content of my server.js file

```<code>require('dotenv').config();
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('database.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(
   jsonServer.rewriter({
      '/api/*': '/$1',
   })
);

server.use(cors({origin: process.env.REMOTE_CLIENT_APP, credentials: true}));
server.use(middlewares);
server.use(router);
server.listen(port, () => {
   console.log(
      ` JSON Server is running on ${process.env.REMOTE_CLIENT_APP}:${port}}`
   );
});
</code>```

Body:
I recently tried to deploy json-server to my interserver's shared hosting plan via cPanel.
I uploaded the app and configured a Node.js app and I'm able to access the endpoint via 'https://soltonbaev.com/json-server/api/contacts' however the jsonServer.rewriter() is not rewriting the "/api/" route to the "/".

In addition I cannot access the individual object via it's id, like for instance "https://soltonbaev.com/json-server/api/contacts/1". Server returns 404.

So clearly, JSON server is not picking up the routes when it is supposed to.

Here is the content of my server.js file

require('dotenv').config();
const jsonServer = require('json-server');
const cors = require('cors');
const server = jsonServer.create();
const router = jsonServer.router('database.json');
const middlewares = jsonServer.defaults();
const port = process.env.PORT || 3000;
server.use(
   jsonServer.rewriter({
      '/api/*': '/$1',
   })
);

server.use(cors({origin: process.env.REMOTE_CLIENT_APP, credentials: true}));
server.use(middlewares);
server.use(router);
server.listen(port, () => {
   console.log(
      ` JSON Server is running on ${process.env.REMOTE_CLIENT_APP}:${port}}`
   );
});


问:
Kernel dies everytime I run the fit command,why?
```<code>resnet=ResNet50(input_shape=IMAGE_SIZE+[3],weights="imagenet",include_top=False)
x=Flatten()(resnet.output)
predictions=Dense(units=len(folders),activation="softmax")(x)
model=Model(inputs=resnet.input,outputs=predictions)
model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"])
train_datagen=ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)
test_datagen=ImageDataGenerator(rescale=1./255)
training_set=train_datagen.flow_from_directory('Datasets/train',target_size=(224,224),batch_size=32,class_mode="categorical")
testing_set=train_datagen.flow_from_directory('Datasets/test',target_size=   (224,224),batch_size=32,class_mode="categorical")
model.fit(training_set,validation_data=testing_set,epochs=50)
</code>```

I am trying image classification using tensorflow and keras. But everytime I run "model.fit", kernel dies automatically.What may be the possible reasons?

Body:
resnet=ResNet50(input_shape=IMAGE_SIZE+[3],weights="imagenet",include_top=False)
x=Flatten()(resnet.output)
predictions=Dense(units=len(folders),activation="softmax")(x)
model=Model(inputs=resnet.input,outputs=predictions)
model.compile(optimizer="adam",loss="categorical_crossentropy",metrics=["accuracy"])
train_datagen=ImageDataGenerator(rescale=1./255,shear_range=0.2,zoom_range=0.2,horizontal_flip=True)
test_datagen=ImageDataGenerator(rescale=1./255)
training_set=train_datagen.flow_from_directory('Datasets/train',target_size=(224,224),batch_size=32,class_mode="categorical")
testing_set=train_datagen.flow_from_directory('Datasets/test',target_size=   (224,224),batch_size=32,class_mode="categorical")
model.fit(training_set,validation_data=testing_set,epochs=50)

I am trying image classification using tensorflow and keras. But everytime I run "model.fit", kernel dies automatically.What may be the possible reasons?


问:
How to get 'outer shell' of self-intersecting polygon
I have a self-intersecting / winding polygon (see in green on picture below). I'd like to get the outer shell (by only keeping the edges that are on the outside of the polygon / removing any inside edges) and therefore end up with a well-defined polygon without any holes inside (see solution in yellow on picture).

How could I do this? Convex/concave hulls won't do because they will take some ground outside the polygon.

I'm using turf-js, so any solution using that would be ideal, but happy to use other libraries / write an algorithm for scratch if not possible.


问:
How to find object's dynamic type which overrides the given virtual function?
```<code>struct Base {
  virtual void foo() {}
};

struct Derive1 : Base {
  // missing from the set
  void foo() override { Base::foo(); }
};

struct Derive2 : Derive1 {};

struct Derive3 : Derive2 {
  void foo() override {}
};

void Caller(Base &o) {
    // want to get Derive1
    // typeid(o) will give Derive2
    o.foo();
}

int main() {
    Derive2 x;
    Caller(x);
}
</code>```

I'm trying to resolve the dependency among a set of functions.

I need to keep a set of function definitions which can be called for a given virtual function call. During the execution, if a virtual function is called but missing from the set, I want to be warned about it.

I try to write a unique key into a singleton before o.foo() and check if the key is fulfilled in Base::foo. But Derive1::foo calls Base::foo, so the key will be fulfilled and Derive1::foo goes unchecked. If I can generate a key linked uniquely to Derive1 (a.k.a the dynamic type of o which overrides foo), Base::foo won't be able to fulfill the key using its own unique key, and I can get a warning that a virtual function is missing.

In another word, I need two maps KeyObject and KeyType, where KeyObject(o, Base::foo) == KeyType(Derive1). Equivalent of KeyObject(o, Base::foo) will be called in Caller and KeyType(Derive1) will be called in Derive1::foo. This is pseudocode.

Any other solution is welcome. Thanks.

Body:
struct Base {
  virtual void foo() {}
};

struct Derive1 : Base {
  // missing from the set
  void foo() override { Base::foo(); }
};

struct Derive2 : Derive1 {};

struct Derive3 : Derive2 {
  void foo() override {}
};

void Caller(Base &o) {
    // want to get Derive1
    // typeid(o) will give Derive2
    o.foo();
}

int main() {
    Derive2 x;
    Caller(x);
}

I'm trying to resolve the dependency among a set of functions.

I need to keep a set of function definitions which can be called for a given virtual function call. During the execution, if a virtual function is called but missing from the set, I want to be warned about it.

I try to write a unique key into a singleton before o.foo() and check if the key is fulfilled in Base::foo. But Derive1::foo calls Base::foo, so the key will be fulfilled and Derive1::foo goes unchecked. If I can generate a key linked uniquely to Derive1 (a.k.a the dynamic type of o which overrides foo), Base::foo won't be able to fulfill the key using its own unique key, and I can get a warning that a virtual function is missing.

In another word, I need two maps KeyObject and KeyType, where KeyObject(o, Base::foo) == KeyType(Derive1). Equivalent of KeyObject(o, Base::foo) will be called in Caller and KeyType(Derive1) will be called in Derive1::foo. This is pseudocode.

Any other solution is welcome. Thanks.


问:
Wordpress When creating a post. Redirects to product editing?
On Wordpress When creating an entry. Redirects to editing the product. How to understand where this problem has come from? How to solve or diagnose it?

When woocommerce is disabled, it turns out to add records. But this is not the way to solve the problem. Maybe you need to clear the cache, or after installing other plugins, did any settings get lost? Tell me who knows what to do?

I don't know how to diagnose the problem


问:
Internet Explorer A Ref Click
would need help to click the HREF word
the source code in internet explorer
as follow

```<code><li class="firstlevelfoldinglist">
<a href="menu.........do=SearchRrequest" shape="">
<span class = "" id="menu_3" onclick="javascript:mtdOnClick(this)">Inquiry</span>
</a>
</code>```

i tried

```<code>Set SelectItem = ie.Document.GetElementbyID("menu_3")
SelectItem.Click
</code>```

it didnt work, have been researching for very long, i am noob

Run-time error '91' Object variable or With Block variable not set

Title: Internet Explorer A Ref Click

Body:
would need help to click the HREF word
the source code in internet explorer
as follow

Inquiry

i tried

Set SelectItem = ie.Document.GetElementbyID("menu_3")
SelectItem.Click

it didnt work, have been researching for very long, i am noob

Run-time error '91' Object variable or With Block variable not set


问:
IOCP Threads and GetQueuedCompletionStatus
Been trying to wrap my head around windows IOCP and have run into a few issues as many other people seem to be doing so.

So far what I'm trying to do is run a TCP IOCP server, which creates 3 accept sockets and has a thread for each waiting on a GetQueuedCompletionStatus. Below is the main thread loop for said threads.

The problem I've run into currently - I believe -  is as follow.

Spawn 3 "worker" threads

Create 3 accept sockets in a loop and call AcceptEx() for each

Client 1 connects with no issue on Thread 1

GetQueuedCompletionStatus releases Thread 1 to continue on

Thread 1 now waits for data on WSARecv().

!!PROBLEM!! Client one sends data, Thread 1's WSARecv() seems to now send a completion packet

which is picked up BY ANOTHER THREAD OUT OF THE 3

Code hangs because of obvious reason (Thread 1 is waiting on the GQCS after its WSARecv(), but never receives it because it went to Thread 2 and Thread 2 is told to continue even though it hasn't actually received a client)

I say I believe this to be the issue because I've run it through debugger and outputted thread id's to console and have seen that right after starting a single client I get 2 outputs of "Accepted client on thread ..." with 2 different thread ids.
Also, when I was stepping through the code in the debugger, as soon as I went passed the WSARecv() in Thread 1, the code hit a breakpoint in Thread 2 at the GQCS line.

I'm clearly misunderstanding something about the use/function of GetQueuedCompletionStatus or something related to it. Is my fundamental methodology here just wrong or is this a easy fix I'm just not getting?

How can I get it such that, the WSARecv() sends its completion packet/signal thing to the write thread?

```<code>// Initialize Winsock...

// Create a handle for the completion port
hCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (u_long)0, 0);
if (hCompPort == NULL) {
    wprintf(L"CreateIoCompletionPort failed with error: %u\n",
        GetLastError());
    WSACleanup();
    return 1;
}

//Create worker threads
for (int i = 0; i < 3; i++)
{
    threads.push_back(std::thread(WorkerThreadFun));
}

// Create a listening socket
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

// Associate the listening socket with the completion port
u_long ck = 111;
CreateIoCompletionPort((HANDLE)ListenSocket, hCompPort, (u_long)0, 0);

//----------------------------------------
// Bind the listening socket to the local IP address
// and port 27015

if (bind(ListenSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) {
    wprintf(L"bind failed with error: %u\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

//----------------------------------------
// Start listening on the listening socket
iResult = listen(ListenSocket, 100);

printf("Listening on address: %s:%d\n", ip, port);

iResult = WSAIoctl(ListenSocket, SIO_GET_EXTENSION_FUNCTION_POINTER,
    &GuidAcceptEx, sizeof(GuidAcceptEx),
    &lpfnAcceptEx, sizeof(lpfnAcceptEx),
    &dwBytes, NULL, NULL);
if (iResult == SOCKET_ERROR) {
    wprintf(L"WSAIoctl failed with error: %u\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

//pre-emptively create sockets for connections
for (int i = 0; i < 3; i++)
{
    // Create an accepting socket
    AcceptSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    }
    //create Overlapped struct for AcceptEx and following that GetQueCompStatus
    LPWSAOVERLAPPEDPLUS pOl = new WSAOVERLAPPEDPLUS();

    //Initialise the "extended" overlapped struct with appropriate data
    memset(pOl, 0, sizeof(WSAOVERLAPPEDPLUS));
    pOl->operation = OP_ACCEPTEX;
    pOl->client = AcceptSocket;
    pOl->listenSocket = ListenSocket;

    DWORD expected = sizeof(struct sockaddr_in) + 16;
    int buflen = (sizeof(SOCKADDR_IN) + 16) * 2;
    char* pBuf = new char[buflen];
    memset(pBuf, 0, buflen);

    // Empty our overlapped structure and accept connections.
    //memset(&olOverlap, 0, sizeof(olOverlap));

    bRetVal = lpfnAcceptEx(ListenSocket, AcceptSocket, pBuf,
                            0, //0 to avoid waiting to read data from a send()
                            expected, expected,
                            &pOl->dwBytes,
                            &pOl->ProviderOverlapped);
    if (bRetVal == FALSE)
    {
        int err = WSAGetLastError();
        if (err != ERROR_IO_PENDING)
        {
            wprintf(L"AcceptEx failed with error: %u\n", WSAGetLastError());
            closesocket(AcceptSocket);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }
    }
}//for
</code>```

WorkerThreadFunc()

```<code>while (TRUE)
{
    bOk = GetQueuedCompletionStatus(hCompPort, &bytes_transferred, (PULONG_PTR)&completion_key, &pOverlapped, INFINITE);

    std::thread::id this_id = std::this_thread::get_id();
    std::cout << "Accepted client on thread" << this_id << "Going to sleep for 5 seconds" << std::endl;
    //std::this_thread::sleep_for(std::chrono::seconds(5));
    if (bOk) {
        // Process a successfully completed I/O request

        if (completion_key == 0) {
            // Safe way to extract the customized structure from pointer
            // is to use 'CONTAINING_RECORD'. Read more on 'CONTAINING_RECORD'.
            WSAOVERLAPPEDPLUS* pOl = CONTAINING_RECORD(pOverlapped, WSAOVERLAPPEDPLUS, ProviderOverlapped);

            if (pOl->operation == OP_ACCEPTEX)
            {
                if (hCompPort2 == NULL)
                {
                    hCompPort2 = CreateIoCompletionPort((HANDLE)pOl->client, hCompPort, (u_long)&this_id, 0);
                    // hCompPort2 should be hCompPort if this succeeds
                    if (hCompPort2 == NULL)
                    {
                        wprintf(L"CreateIoCompletionPort associate failed with error: %u\n",
                            GetLastError());
                        closesocket(pOl->client);
                        closesocket(pOl->listenSocket);
                        WSACleanup();
                        break;
                    }//if: CreateIOCP error
                }//if: accept socket already IOCP

                // Before doing any WSASend/WSARecv, inherit the
                // listen socket properties by calling 'setsockopt()'

                setsockopt(pOl->client, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
                    (char*)&pOl->listenSocket, sizeof(pOl->listenSocket));

                DWORD& recvbytes = pOl->dwBytes;
                char buf[MAX_BUF];
                WSABUF wsabuf = { MAX_BUF, buf };
                DWORD flags = 0;

                if (WSARecv(pOl->client, &wsabuf, 1, &pOl->dwBytes, &flags, &pOl->ProviderOverlapped, NULL) == SOCKET_ERROR)
                {
                    int err = WSAGetLastError();
                    if (err != WSA_IO_PENDING)
                    {
                        printf("WSARecv failed with error: %d\n", WSAGetLastError());
                        //return 1;
                    }
                }
                bool qresult = GetQueuedCompletionStatus(hCompPort, &pOl->dwBytes,
                                                        (PULONG_PTR)&completion_key, &pOverlapped, INFINITE);
                if (!qresult)
                {
                    DWORD err = GetLastError();
                    printf("* error %d getting completion port status!!!\n", err);
                }
                int iResult = WSAGetOverlappedResult(pOl->client, &pOl->ProviderOverlapped, &pOl->dwBytes, FALSE, &flags);
                if (iResult == FALSE) {
                    wprintf(L"WSARecv operation failed with error: %d\n", WSAGetLastError());
                    //return 1;
                    break;
                }
                wsabuf.buf[recvbytes] = '\0';
                std::cout << "Bytes received: " << recvbytes << std::endl;
                std::wcout << "Bytes create: " << wsabuf.buf << std::endl;
            }
            delete pOl;
        }
    }
    else {
        // Handle error ...
    }
}
</code>```

}

Body:
Been trying to wrap my head around windows IOCP and have run into a few issues as many other people seem to be doing so.

So far what I'm trying to do is run a TCP IOCP server, which creates 3 accept sockets and has a thread for each waiting on a GetQueuedCompletionStatus. Below is the main thread loop for said threads.

The problem I've run into currently - I believe -  is as follow.

Spawn 3 "worker" threads

Create 3 accept sockets in a loop and call AcceptEx() for each

Client 1 connects with no issue on Thread 1

GetQueuedCompletionStatus releases Thread 1 to continue on

Thread 1 now waits for data on WSARecv().

!!PROBLEM!! Client one sends data, Thread 1's WSARecv() seems to now send a completion packet

which is picked up BY ANOTHER THREAD OUT OF THE 3

Code hangs because of obvious reason (Thread 1 is waiting on the GQCS after its WSARecv(), but never receives it because it went to Thread 2 and Thread 2 is told to continue even though it hasn't actually received a client)

I say I believe this to be the issue because I've run it through debugger and outputted thread id's to console and have seen that right after starting a single client I get 2 outputs of "Accepted client on thread ..." with 2 different thread ids.
Also, when I was stepping through the code in the debugger, as soon as I went passed the WSARecv() in Thread 1, the code hit a breakpoint in Thread 2 at the GQCS line.

I'm clearly misunderstanding something about the use/function of GetQueuedCompletionStatus or something related to it. Is my fundamental methodology here just wrong or is this a easy fix I'm just not getting?

How can I get it such that, the WSARecv() sends its completion packet/signal thing to the write thread?

// Initialize Winsock...

// Create a handle for the completion port
hCompPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, (u_long)0, 0);
if (hCompPort == NULL) {
    wprintf(L"CreateIoCompletionPort failed with error: %u\n",
        GetLastError());
    WSACleanup();
    return 1;
}

//Create worker threads
for (int i = 0; i < 3; i++)
{
    threads.push_back(std::thread(WorkerThreadFun));
}

// Create a listening socket
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

// Associate the listening socket with the completion port
u_long ck = 111;
CreateIoCompletionPort((HANDLE)ListenSocket, hCompPort, (u_long)0, 0);

//----------------------------------------
// Bind the listening socket to the local IP address
// and port 27015

if (bind(ListenSocket, (SOCKADDR*)&service, sizeof(service)) == SOCKET_ERROR) {
    wprintf(L"bind failed with error: %u\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

//----------------------------------------
// Start listening on the listening socket
iResult = listen(ListenSocket, 100);

printf("Listening on address: %s:%d\n", ip, port);

iResult = WSAIoctl(ListenSocket, SIO_GET_EXTENSION_FUNCTION_POINTER,
    &GuidAcceptEx, sizeof(GuidAcceptEx),
    &lpfnAcceptEx, sizeof(lpfnAcceptEx),
    &dwBytes, NULL, NULL);
if (iResult == SOCKET_ERROR) {
    wprintf(L"WSAIoctl failed with error: %u\n", WSAGetLastError());
    closesocket(ListenSocket);
    WSACleanup();
    return 1;
}

//pre-emptively create sockets for connections
for (int i = 0; i < 3; i++)
{
    // Create an accepting socket
    AcceptSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    }
    //create Overlapped struct for AcceptEx and following that GetQueCompStatus
    LPWSAOVERLAPPEDPLUS pOl = new WSAOVERLAPPEDPLUS();

    //Initialise the "extended" overlapped struct with appropriate data
    memset(pOl, 0, sizeof(WSAOVERLAPPEDPLUS));
    pOl->operation = OP_ACCEPTEX;
    pOl->client = AcceptSocket;
    pOl->listenSocket = ListenSocket;

    DWORD expected = sizeof(struct sockaddr_in) + 16;
    int buflen = (sizeof(SOCKADDR_IN) + 16) * 2;
    char* pBuf = new char[buflen];
    memset(pBuf, 0, buflen);

    // Empty our overlapped structure and accept connections.
    //memset(&olOverlap, 0, sizeof(olOverlap));

    bRetVal = lpfnAcceptEx(ListenSocket, AcceptSocket, pBuf,
                            0, //0 to avoid waiting to read data from a send()
                            expected, expected,
                            &pOl->dwBytes,
                            &pOl->ProviderOverlapped);
    if (bRetVal == FALSE)
    {
        int err = WSAGetLastError();
        if (err != ERROR_IO_PENDING)
        {
            wprintf(L"AcceptEx failed with error: %u\n", WSAGetLastError());
            closesocket(AcceptSocket);
            closesocket(ListenSocket);
            WSACleanup();
            return 1;
        }
    }
}//for

WorkerThreadFunc()

while (TRUE)
{
    bOk = GetQueuedCompletionStatus(hCompPort, &bytes_transferred, (PULONG_PTR)&completion_key, &pOverlapped, INFINITE);

    std::thread::id this_id = std::this_thread::get_id();
    std::cout << "Accepted client on thread" << this_id << "Going to sleep for 5 seconds" << std::endl;
    //std::this_thread::sleep_for(std::chrono::seconds(5));
    if (bOk) {
        // Process a successfully completed I/O request

        if (completion_key == 0) {
            // Safe way to extract the customized structure from pointer
            // is to use 'CONTAINING_RECORD'. Read more on 'CONTAINING_RECORD'.
            WSAOVERLAPPEDPLUS* pOl = CONTAINING_RECORD(pOverlapped, WSAOVERLAPPEDPLUS, ProviderOverlapped);

            if (pOl->operation == OP_ACCEPTEX)
            {
                if (hCompPort2 == NULL)
                {
                    hCompPort2 = CreateIoCompletionPort((HANDLE)pOl->client, hCompPort, (u_long)&this_id, 0);
                    // hCompPort2 should be hCompPort if this succeeds
                    if (hCompPort2 == NULL)
                    {
                        wprintf(L"CreateIoCompletionPort associate failed with error: %u\n",
                            GetLastError());
                        closesocket(pOl->client);
                        closesocket(pOl->listenSocket);
                        WSACleanup();
                        break;
                    }//if: CreateIOCP error
                }//if: accept socket already IOCP

                // Before doing any WSASend/WSARecv, inherit the
                // listen socket properties by calling 'setsockopt()'

                setsockopt(pOl->client, SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT,
                    (char*)&pOl->listenSocket, sizeof(pOl->listenSocket));

                DWORD& recvbytes = pOl->dwBytes;
                char buf[MAX_BUF];
                WSABUF wsabuf = { MAX_BUF, buf };
                DWORD flags = 0;

                if (WSARecv(pOl->client, &wsabuf, 1, &pOl->dwBytes, &flags, &pOl->ProviderOverlapped, NULL) == SOCKET_ERROR)
                {
                    int err = WSAGetLastError();
                    if (err != WSA_IO_PENDING)
                    {
                        printf("WSARecv failed with error: %d\n", WSAGetLastError());
                        //return 1;
                    }
                }
                bool qresult = GetQueuedCompletionStatus(hCompPort, &pOl->dwBytes,
                                                        (PULONG_PTR)&completion_key, &pOverlapped, INFINITE);
                if (!qresult)
                {
                    DWORD err = GetLastError();
                    printf("* error %d getting completion port status!!!\n", err);
                }
                int iResult = WSAGetOverlappedResult(pOl->client, &pOl->ProviderOverlapped, &pOl->dwBytes, FALSE, &flags);
                if (iResult == FALSE) {
                    wprintf(L"WSARecv operation failed with error: %d\n", WSAGetLastError());
                    //return 1;
                    break;
                }
                wsabuf.buf[recvbytes] = '\0';
                std::cout << "Bytes received: " << recvbytes << std::endl;
                std::wcout << "Bytes create: " << wsabuf.buf << std::endl;
            }
            delete pOl;
        }
    }
    else {
        // Handle error ...
    }
}

}