问:
Missing properties error when using Sequelize association
I'm using Sequelize in TypeScript to implement an API in Express. I'm encountering a type-related error when using the value returned by an association mixin.

Here is a portion of my data model as I've defined it:

```<code>export class User extends Model {
  id!: number;
  username!: string;
  email!: string;
  password!: string;
  active!: boolean;

  createdAt!: Date;
  updatedAt!: Date;
}

export class UserSession extends Model {
  token!: string;
  userId!: number;
  expiresAt!: Date;
  renewalHours!: number;

  getUser!: BelongsToGetAssociationMixin<User>;
}
</code>```

Here is how I'm attempting to authenticate a request during a session (within an Express middleware):

```<code>UserSession.findOne({ where: { token: req.body.token }, include: [User] })
  .then(session => {
    if (session) {
      const now = moment();
      if (session.expiresAt > now.toDate()) {
        session.set('expiresAt',
                    now.add(session.renewalHours, 'hours').toDate());
        session.save();

        req.user = session.getUser();
        next();
      } else {
        session.destroy();
        res.status(400).json({ msg: 'Session expired' });
      }
    } else {
      res.status(403).json({ msg: 'Not logged in' });
    }
  });
</code>```

I have associated UserSession with User via UserSession.belongsTo(User) (details omitted).

The particular line

```<code>req.user = session.getUser();
</code>```

produces the following error from TypeScript:

```<code> Type 'Bluebird<User>' is missing the following properties from type 'User': id, username, email, password, and 26 more.
</code>```

req is an Express Request. I've added a user field to it (for purposes of TypeScript) as follows:

```<code>declare global {
  namespace Express {
    export interface Request {
      user?: User;
      session?: UserSession;
    }
  }
}
</code>```

I know that Sequelize is now built upon the Bluebird Promise framework, so I suspect this has to do with my type definitions. It seems like TypeScript doesn't think that UserSession.getUser will return something with User's attributes. Why not?

答:
As predicted, this was a very simple misunderstanding of the way Sequelize's mixin functions work. As with everything in Sequelize, they are of course asynchronous calls using Bluebird! Therefore, UserSession.getUser doesn't return User but rather a Promise that will return user. The line is fixed as follows:

```<code>req.user = await session.getUser();
</code>```

and of course marking this function as async. This could also be done using session.getUser().then( ... ).

Body:
I'm using Sequelize in TypeScript to implement an API in Express. I'm encountering a type-related error when using the value returned by an association mixin.

Here is a portion of my data model as I've defined it:

export class User extends Model {
  id!: number;
  username!: string;
  email!: string;
  password!: string;
  active!: boolean;

  createdAt!: Date;
  updatedAt!: Date;
}

export class UserSession extends Model {
  token!: string;
  userId!: number;
  expiresAt!: Date;
  renewalHours!: number;

  getUser!: BelongsToGetAssociationMixin<User>;
}

Here is how I'm attempting to authenticate a request during a session (within an Express middleware):

UserSession.findOne({ where: { token: req.body.token }, include: [User] })
  .then(session => {
    if (session) {
      const now = moment();
      if (session.expiresAt > now.toDate()) {
        session.set('expiresAt',
                    now.add(session.renewalHours, 'hours').toDate());
        session.save();

        req.user = session.getUser();
        next();
      } else {
        session.destroy();
        res.status(400).json({ msg: 'Session expired' });
      }
    } else {
      res.status(403).json({ msg: 'Not logged in' });
    }
  });

I have associated UserSession with User via UserSession.belongsTo(User) (details omitted).

The particular line

req.user = session.getUser();

produces the following error from TypeScript:

 Type 'Bluebird<User>' is missing the following properties from type 'User': id, username, email, password, and 26 more.

req is an Express Request. I've added a user field to it (for purposes of TypeScript) as follows:

declare global {
  namespace Express {
    export interface Request {
      user?: User;
      session?: UserSession;
    }
  }
}

I know that Sequelize is now built upon the Bluebird Promise framework, so I suspect this has to do with my type definitions. It seems like TypeScript doesn't think that UserSession.getUser will return something with User's attributes. Why not?

Body:
As predicted, this was a very simple misunderstanding of the way Sequelize's mixin functions work. As with everything in Sequelize, they are of course asynchronous calls using Bluebird! Therefore, UserSession.getUser doesn't return User but rather a Promise that will return user. The line is fixed as follows:

req.user = await session.getUser();

and of course marking this function as async. This could also be done using session.getUser().then( ... ).


来源: stackexchange

问:
How to connect android view to XML view programatically?
Here's y custom GLSurfaceView:

```<code>public class MyGLSurfaceView extends GLSurfaceView {
</code>```

Normally I'd create my custom view by doing:

```<code><MyGLSurfaceView
        android:id="@+id/glsurfaceview1"
        android:layout_width="640px"
        android:layout_height="480px"
        />
</code>```

But I want to create it through code, not through XML. So which XML item I must put on my XML? Perhaps

```<code><SurfaceView
            android:id="@+id/glsurfaceview1"
            android:layout_width="640px"
            android:layout_height="480px"
            />
</code>```

?

But then how do I set my GlSurfaceView to appear on this XML item? How do I connect it?

答:
You can do it like this.

Add FrameLayout to xml file and in code do something like this:

```<code>    MyGlSurfaceView mySurfaceView = ...

    FrameLayout frameLayout = findViewById(R.id.frame_layout);
    frameLayout.addView(mySurfaceView);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here's y custom GLSurfaceView:

public class MyGLSurfaceView extends GLSurfaceView {

Normally I'd create my custom view by doing:

<MyGLSurfaceView
        android:id="@+id/glsurfaceview1"
        android:layout_width="640px"
        android:layout_height="480px"
        />

But I want to create it through code, not through XML. So which XML item I must put on my XML? Perhaps

<SurfaceView
            android:id="@+id/glsurfaceview1"
            android:layout_width="640px"
            android:layout_height="480px"
            />

?

But then how do I set my GlSurfaceView to appear on this XML item? How do I connect it?

Body:
You can do it like this.

Add FrameLayout to xml file and in code do something like this:

    MyGlSurfaceView mySurfaceView = ...

    FrameLayout frameLayout = findViewById(R.id.frame_layout);
    frameLayout.addView(mySurfaceView);


问:
Right to Left text writing support in windows phone 7?
I m building an application for Arabic and in this i want that i should write text from right to left in textbox but i can see only the option to align the text to left or right.

How can i get this feature?

答:
Right-to-Left text support is only available in the Windows Phone 7 framework for Mango (7.1), which will not be available to consumers until November(ish) this year.

You can download the current beta of the Mango tools from the App Hub and develop applications for Mango in advance of the consumer release. The documentation for the FlowDirection property is on MSDN: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.flowdirection(v=VS.95).aspx

ContentLicense: CC BY-SA 3.0


问:
Extract part of href link using beautiful soup
I'm new to python requests and beautiful soup, I was trying to create a script to automatically login and logout, but I need the "_wpnonce" value to send a valid post request. I am wondering if there is a way to extract the "_wpnonce" value from this link using beautiful soup, any help is appreciated.

```<code><a href="https://www.example.com/wp-login.php?action=logout&_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>
</code>```

The extracted value would be "fc789123fe"

答:
this should work

```<code>tag = r'<a href="https://www.example.com/wp-login.phpaction=logout&_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>'
tag = tag.split("_wpnonce=")[1]
tag = tag.split("&")[0]
print(tag)
</code>```

output

```<code>fc789123fe
</code>```

Body:
I'm new to python requests and beautiful soup, I was trying to create a script to automatically login and logout, but I need the "_wpnonce" value to send a valid post request. I am wondering if there is a way to extract the "_wpnonce" value from this link using beautiful soup, any help is appreciated.

Sign Out

The extracted value would be "fc789123fe"

Body:
this should work

tag = r'<a href="https://www.example.com/wp-login.phpaction=logout&amp;_wpnonce=fc789123fe&redirect_to=%2Fuser%2Flogout">Sign Out</a>'
tag = tag.split("_wpnonce=")[1]
tag = tag.split("&")[0]
print(tag)

output

fc789123fe


问:
Access VBA loop to export Excel files
I have some code that I copied and modified from Export Query in VBA loop to select data based on String Value

The code works although the problem is that when it runs it creates a query in the database which is then deleted at the end. If the code breaks half way through, this query is still in the database. So when the code is run again it gives an error message saying it can't create the query as it already exists.

The query that is created within the database is named "Select * from SalesData"

The objective is that I have a query called "SalesData" which includes sales information for a number of countries. I want to export all the data for each country into an Excel file in a loop without creating any additional Access objects. Is it possible to just filter the existing query within the VBA without creating the temporary object?

Can anyone suggest any modifications to the below code to achieve this?

```<code>Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim v As String
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String

strQDF = "select * from SalesData"

Do While Not rs1.EOF
    v = rs1.Fields(0).Value

    strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"

    Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
    qdfTemp.Close
    Set qdfTemp = Nothing

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
    strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True

    CurrentDb.QueryDefs.Delete strQDF
    rs1.MoveNext
Loop

rs1.Close

 End Sub
</code>```

答:
Thanks to the input here, it seems that the only way to do it is to manipulate an existing query in the database or to create a query in the VBA script and then delete it at the end.

See below for an example of the first approach, the code uses a query already in the database called "blankquery".

```<code>Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim qdfTemp As DAO.QueryDef
Dim v As String
Dim strQry As String
Dim strQDF As String

strQDF = "blankquery"

Do While Not rs1.EOF
v = rs1.Fields(0).Value
strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"
db.QueryDefs(strQDF).sql = strQry
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True
rs1.MoveNext
Loop

rs1.Close

End Sub
</code>```

Title: Access VBA loop to export Excel files

Body:
I have some code that I copied and modified from Export Query in VBA loop to select data based on String Value

The code works although the problem is that when it runs it creates a query in the database which is then deleted at the end. If the code breaks half way through, this query is still in the database. So when the code is run again it gives an error message saying it can't create the query as it already exists.

The query that is created within the database is named "Select * from SalesData"

The objective is that I have a query called "SalesData" which includes sales information for a number of countries. I want to export all the data for each country into an Excel file in a loop without creating any additional Access objects. Is it possible to just filter the existing query within the VBA without creating the temporary object?

Can anyone suggest any modifications to the below code to achieve this?

Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim v As String
Dim strQry As String
Dim qdfTemp As DAO.QueryDef
Dim strQDF As String

strQDF = "select * from SalesData"

Do While Not rs1.EOF
    v = rs1.Fields(0).Value

    strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"

    Set qdfTemp = CurrentDb.CreateQueryDef(strQDF, strQry)
    qdfTemp.Close
    Set qdfTemp = Nothing

    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
    strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True

    CurrentDb.QueryDefs.Delete strQDF
    rs1.MoveNext
Loop

rs1.Close

 End Sub

Body:
Thanks to the input here, it seems that the only way to do it is to manipulate an existing query in the database or to create a query in the VBA script and then delete it at the end.

See below for an example of the first approach, the code uses a query already in the database called "blankquery".

Sub TEST()
Dim db As DAO.Database
Set db = CurrentDb()

Dim rs1 As DAO.Recordset
Set rs1 = db.OpenRecordset("Select Distinct Country From SalesData")

Dim qdfTemp As DAO.QueryDef
Dim v As String
Dim strQry As String
Dim strQDF As String

strQDF = "blankquery"

Do While Not rs1.EOF
v = rs1.Fields(0).Value
strQry = "SELECT * FROM SalesData WHERE Country = '" & v & "'"
db.QueryDefs(strQDF).sql = strQry
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, _
strQDF, "C:\Users\me\Desktop\VBA_TEST\" & v & ".xlsx", True
rs1.MoveNext
Loop

rs1.Close

End Sub


问:
making a quick view modal for your shopping cart
I'm making a shopping cart with asp.net core mvc and jquery. I get items into a foreach loop to display all items in a grid and other information into @Html.Hidden("Description", (object)item.Description). I created a quick view button to popup for more details of the product. The challenge I have is that when I click on the quick view, I want to be able to view details of the selected product. I have been able to get the image of the product, when any of the items quick view is clicked using this code:

```<code>var selectedImage = $(this).parent('.hov-img0').find('img:first');
var slectedImageUrl = selectedImage.attr('src');
</code>```

Apart from the image, I've been having difficulty getting other properties, such as price, description, alternate image etc, which are all in hidden fields. Please check my code below:

```<code><div class="row isotope-grid">
        @if (ViewBag.AllProducts != null)
        {
            foreach (var item in ViewBag.AllProducts)
            {
                var photoPath4 = "~/images/" + (@item.PicPathMain ?? "placehold.jpg");

                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women">
                    <!-- Block2 -->
                    <div class="block2">
                        <div class="block2-pic hov-img0">
                            <img src=@photoPath4 id="imgPix2" alt="IMG-PRODUCT" asp-append-version="true" />

                            <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
                                Quick View
                            </a>
                        </div>

                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                                <a href="@Url.Action("ProductDetail", new { ID = item.ID })" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                                    @item.Name
                                </a>

                                @Html.Hidden("Image1", (object)item.PicPathMain)
                                @Html.Hidden("Image2", (object)item.PicPathLeft)
                                @Html.Hidden("Image3", (object)item.PicPathRight)
                                @Html.Hidden("Description", (object)item.Description)
                                @Html.Hidden("Price", (object)item.Price)
                                @Html.Hidden("Size", (object)item.Size)
                                @Html.Hidden("ProdName", (object)item.Name)
                                <span class="stext-105 cl3">
                                    N @item.Price
                                </span>
                            </div>

                            <div class="block2-txt-child2 flex-r p-t-3">
                                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                                    <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
                                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            }
        }

    </div>
</code>```

This is my jquery code

```<code>$('.js-show-modal1').on('click',function(e){
    e.preventDefault();
    $('.js-modal1').addClass('show-modal1');
    //Get Product Image
    var selectedImage = $(this).parent('.hov-img0').find('img:first');
    var slectedImageUrl = selectedImage.attr('src');
    $('#imgPic1').attr('src', slectedImageUrl);

    //Get Product Name
    var productName = $(this).parent('.hov-img0').find('input[name="ProdName"]');
    var selectedName = productName.attr('value');
    $('.mtext-105').html(selectedName);
});
</code>```

Update:
Please check below the rendered html of the grid.

```<code><div class="row isotope-grid" style="position: relative; height: 890px;">
                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 0px;">
                    <!-- Block2 -->
                    <div class="block2">
                        <div class="block2-pic hov-img0">
                            <img src="/images/476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg?v=clql7fMRxRm6EOgTPdinW74B9xv6lFre36t5VFvywJk" id="imgPix2" alt="IMG-PRODUCT">

                            <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
                                Quick View
                            </a>
                        </div>

                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                                <a href="/Home/ProductDetail/1" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                                    AFRO KINKY
                                </a>

                                <input id="Image1" name="Image1" type="hidden" value="476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="17a7303e-6d2f-44d7-bc2c-7516a04311c4_DSS-620-X-600-1.jpg.pagespeed.ce.4HxAdKZ6OR.jpg">
                                <input id="Image3" name="Image3" type="hidden" value="f3914b31-337b-4a16-bb21-9e49e0f8c343_ed1.jpg">
                                <input id="Description" name="Description" type="hidden" value="ROSA">
                                <input id="Price" name="Price" type="hidden" value="15000.00">
                                <input id="Size" name="Size" type="hidden" value="14">
                                <input id="ProdName" name="ProdName" type="hidden" value="AFRO KINKY">
                                <span class="stext-105 cl3">
                                    N 15000.00
                                </span>
                            </div>

                            <div class="block2-txt-child2 flex-r p-t-3">
                                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                                    <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
                                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 0px;">
                    <!-- Block2 -->
                    <div class="block2">
                        <div class="block2-pic hov-img0">
                            <img src="/images/5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg?v=g2USmv3vBYuLBjEOKra5zavJnxo_4CoMlz8LtDl8hLQ" id="imgPix2" alt="IMG-PRODUCT">

                            <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
                                Quick View
                            </a>
                        </div>

                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                                <a href="/Home/ProductDetail/2" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                                    LACE WIG
                                </a>

                                <input id="Image1" name="Image1" type="hidden" value="5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="16000.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
                                <span class="stext-105 cl3">
                                    N 16000.00
                                </span>
                            </div>

                            <div class="block2-txt-child2 flex-r p-t-3">
                                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                                    <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
                                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 445px;">
                    <!-- Block2 -->
                    <div class="block2">
                        <div class="block2-pic hov-img0">
                            <img src="/images/ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg?v=lLlRsUR3vXeV76vghx52VY8HicpXGNKpVTSFurOtleM" id="imgPix2" alt="IMG-PRODUCT">

                            <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
                                Quick View
                            </a>
                        </div>

                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                                <a href="/Home/ProductDetail/3" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                                    LACE WIG
                                </a>

                                <input id="Image1" name="Image1" type="hidden" value="ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="22500.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
                                <span class="stext-105 cl3">
                                    N 22500.00
                                </span>
                            </div>

                            <div class="block2-txt-child2 flex-r p-t-3">
                                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                                    <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
                                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 445px;">
                    <!-- Block2 -->
                    <div class="block2">
                        <div class="block2-pic hov-img0">
                            <img src="/images/e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg?v=wnPvcpEnY7CmfOZbwzVKf2sfZqeGOUdx0znVbL9RHsU" id="imgPix2" alt="IMG-PRODUCT">

                            <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
                                Quick View
                            </a>
                        </div>

                        <div class="block2-txt flex-w flex-t p-t-14">
                            <div class="block2-txt-child1 flex-col-l ">
                                <a href="/Home/ProductDetail/4" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
                                    RED ROSES
                                </a>

                                <input id="Image1" name="Image1" type="hidden" value="e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="17000.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="RED ROSES">
                                <span class="stext-105 cl3">
                                    N 17000.00
                                </span>
                            </div>

                            <div class="block2-txt-child2 flex-r p-t-3">
                                <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
                                    <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
                                    <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
                                </a>
                            </div>
                        </div>
                    </div>
                </div>

    </div>
</code>```

答:
You can do it like this. Note that you haven't added your HTML for the modal, so the class names to which the results are written to are just examples and have to be adjusted by you. Also note that your HTML isn't valid because you use duplicate ids while ids have to be unique. There might be no need to use ids like Image1, Image2 and so on as all of the inputs also have a name attribute with the same value.

$('.js-show-modal1').on('click', function(e) {
  e.preventDefault();
  $('.js-modal1').addClass('show-modal1');

  var selectedImage = $(this).parent('.hov-img0').find('img:first');
  var selectedImageUrl = selectedImage.attr('src');
  $('#imgPic1').attr('src', selectedImageUrl);

  var productName = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="ProdName"]');
  var selectedName = productName.attr('value');
  $('.mtext-105').html(selectedName);

  var productPrice = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Price"]');
  var selectedPrice = productPrice.attr('value');
  $('.mtext-106').html(selectedPrice);

  var productDescription = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Description"]');
  var selectedDescription = productDescription.attr('value');
  $('.mtext-107').html(selectedDescription);

  var productSize = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Size"]');
  var selectedSize = productSize.attr('value');
  $('.mtext-107').html(selectedSize);

  var selectedImage2 = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Image2"]');
  var selectedImage2Url = selectedImage2.attr('value');
  $('#imgPic2').attr('src', selectedImage2Url);

  var selectedImage3 = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Image3"]');
  var selectedImage3Url = selectedImage3.attr('value');
  $('#imgPic3').attr('src', selectedImage3Url);

   console.log("Product Name: " + selectedName);
   console.log("Product Image: " + selectedImageUrl);
   console.log("Product Price: " + selectedPrice);
   console.log("Product Size: " + selectedSize);
   console.log("Product Description: " + selectedDescription);
   console.log("Product Image 2: " + selectedImage2Url);
   console.log("Product Image 3: " + selectedImage3Url);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row isotope-grid" style="position: relative; height: 890px;">
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 0px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg?v=clql7fMRxRm6EOgTPdinW74B9xv6lFre36t5VFvywJk" id="imgPix2" alt="IMG-PRODUCT">

          Quick View

      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">

            AFRO KINKY

          <input id="Image1" name="Image1" type="hidden" value="476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg">
          <input id="Image2" name="Image2" type="hidden" value="17a7303e-6d2f-44d7-bc2c-7516a04311c4_DSS-620-X-600-1.jpg.pagespeed.ce.4HxAdKZ6OR.jpg">
          <input id="Image3" name="Image3" type="hidden" value="f3914b31-337b-4a16-bb21-9e49e0f8c343_ed1.jpg">
          <input id="Description" name="Description" type="hidden" value="ROSA">
          <input id="Price" name="Price" type="hidden" value="15000.00">
          <input id="Size" name="Size" type="hidden" value="14">
          <input id="ProdName" name="ProdName" type="hidden" value="AFRO KINKY">
          <span class="stext-105 cl3">
            N 15000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">

            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">

        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 0px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg?v=g2USmv3vBYuLBjEOKra5zavJnxo_4CoMlz8LtDl8hLQ" id="imgPix2" alt="IMG-PRODUCT">

          Quick View

      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">

            LACE WIG

          <input id="Image1" name="Image1" type="hidden" value="5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="16000.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
          <span class="stext-105 cl3">
            N 16000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">

            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">

        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 445px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg?v=lLlRsUR3vXeV76vghx52VY8HicpXGNKpVTSFurOtleM" id="imgPix2" alt="IMG-PRODUCT">

          Quick View

      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">

            LACE WIG

          <input id="Image1" name="Image1" type="hidden" value="ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="22500.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
          <span class="stext-105 cl3">
            N 22500.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">

            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">

        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 445px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg?v=wnPvcpEnY7CmfOZbwzVKf2sfZqeGOUdx0znVbL9RHsU" id="imgPix2" alt="IMG-PRODUCT">

          Quick View

      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">

            RED ROSES

          <input id="Image1" name="Image1" type="hidden" value="e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="17000.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="RED ROSES">
          <span class="stext-105 cl3">
            N 17000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">

            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">

        </div>
      </div>
    </div>
  </div>

</div></code>```

Body:
I'm making a shopping cart with asp.net core mvc and jquery. I get items into a foreach loop to display all items in a grid and other information into @Html.Hidden("Description", (object)item.Description). I created a quick view button to popup for more details of the product. The challenge I have is that when I click on the quick view, I want to be able to view details of the selected product. I have been able to get the image of the product, when any of the items quick view is clicked using this code:

var selectedImage = $(this).parent('.hov-img0').find('img:first');
var slectedImageUrl = selectedImage.attr('src');

Apart from the image, I've been having difficulty getting other properties, such as price, description, alternate image etc, which are all in hidden fields. Please check my code below:

        @if (ViewBag.AllProducts != null)
        {
            foreach (var item in ViewBag.AllProducts)
            {
                var photoPath4 = "~/images/" + (@item.PicPathMain ?? "placehold.jpg");

                                Quick View

                                    @item.Name

                                @Html.Hidden("Image1", (object)item.PicPathMain)
                                @Html.Hidden("Image2", (object)item.PicPathLeft)
                                @Html.Hidden("Image3", (object)item.PicPathRight)
                                @Html.Hidden("Description", (object)item.Description)
                                @Html.Hidden("Price", (object)item.Price)
                                @Html.Hidden("Size", (object)item.Size)
                                @Html.Hidden("ProdName", (object)item.Name)

                                    N @item.Price

            }
        }

This is my jquery code

$('.js-show-modal1').on('click',function(e){
    e.preventDefault();
    $('.js-modal1').addClass('show-modal1');
    //Get Product Image
    var selectedImage = $(this).parent('.hov-img0').find('img:first');
    var slectedImageUrl = selectedImage.attr('src');
    $('#imgPic1').attr('src', slectedImageUrl);

    //Get Product Name
    var productName = $(this).parent('.hov-img0').find('input[name="ProdName"]');
    var selectedName = productName.attr('value');
    $('.mtext-105').html(selectedName);
});

Update:
Please check below the rendered html of the grid.

                                Quick View

                                    AFRO KINKY

                                <input id="Image1" name="Image1" type="hidden" value="476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="17a7303e-6d2f-44d7-bc2c-7516a04311c4_DSS-620-X-600-1.jpg.pagespeed.ce.4HxAdKZ6OR.jpg">
                                <input id="Image3" name="Image3" type="hidden" value="f3914b31-337b-4a16-bb21-9e49e0f8c343_ed1.jpg">
                                <input id="Description" name="Description" type="hidden" value="ROSA">
                                <input id="Price" name="Price" type="hidden" value="15000.00">
                                <input id="Size" name="Size" type="hidden" value="14">
                                <input id="ProdName" name="ProdName" type="hidden" value="AFRO KINKY">

                                    N 15000.00

                                Quick View

                                    LACE WIG

                                <input id="Image1" name="Image1" type="hidden" value="5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="16000.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">

                                    N 16000.00

                                Quick View

                                    LACE WIG

                                <input id="Image1" name="Image1" type="hidden" value="ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="22500.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">

                                    N 22500.00

                                Quick View

                                    RED ROSES

                                <input id="Image1" name="Image1" type="hidden" value="e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg">
                                <input id="Image2" name="Image2" type="hidden" value="">
                                <input id="Image3" name="Image3" type="hidden" value="">
                                <input id="Description" name="Description" type="hidden" value="HAIR DOM">
                                <input id="Price" name="Price" type="hidden" value="17000.00">
                                <input id="Size" name="Size" type="hidden" value="15">
                                <input id="ProdName" name="ProdName" type="hidden" value="RED ROSES">

                                    N 17000.00

Body:
You can do it like this. Note that you haven't added your HTML for the modal, so the class names to which the results are written to are just examples and have to be adjusted by you. Also note that your HTML isn't valid because you use duplicate ids while ids have to be unique. There might be no need to use ids like Image1, Image2 and so on as all of the inputs also have a name attribute with the same value.

$('.js-show-modal1').on('click', function(e) {
  e.preventDefault();
  $('.js-modal1').addClass('show-modal1');

  var selectedImage = $(this).parent('.hov-img0').find('img:first');
  var selectedImageUrl = selectedImage.attr('src');
  $('#imgPic1').attr('src', selectedImageUrl);

  var productName = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="ProdName"]');
  var selectedName = productName.attr('value');
  $('.mtext-105').html(selectedName);

  var productPrice = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Price"]');
  var selectedPrice = productPrice.attr('value');
  $('.mtext-106').html(selectedPrice);

  var productDescription = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Description"]');
  var selectedDescription = productDescription.attr('value');
  $('.mtext-107').html(selectedDescription);

  var productSize = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Size"]');
  var selectedSize = productSize.attr('value');
  $('.mtext-107').html(selectedSize);

  var selectedImage2 = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Image2"]');
  var selectedImage2Url = selectedImage2.attr('value');
  $('#imgPic2').attr('src', selectedImage2Url);

  var selectedImage3 = $(this).parent('.hov-img0').next(".block2-txt").find('input[name="Image3"]');
  var selectedImage3Url = selectedImage3.attr('value');
  $('#imgPic3').attr('src', selectedImage3Url);

   console.log("Product Name: " + selectedName);
   console.log("Product Image: " + selectedImageUrl);
   console.log("Product Price: " + selectedPrice);
   console.log("Product Size: " + selectedSize);
   console.log("Product Description: " + selectedDescription);
   console.log("Product Image 2: " + selectedImage2Url);
   console.log("Product Image 3: " + selectedImage3Url);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row isotope-grid" style="position: relative; height: 890px;">
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 0px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg?v=clql7fMRxRm6EOgTPdinW74B9xv6lFre36t5VFvywJk" id="imgPix2" alt="IMG-PRODUCT">

        <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
          Quick View
        </a>
      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">
          <a href="/Home/ProductDetail/1" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
            AFRO KINKY
          </a>

          <input id="Image1" name="Image1" type="hidden" value="476cd102-95e4-406e-b4b1-bc24ff56c08a_73_AFRO1_L.jpg">
          <input id="Image2" name="Image2" type="hidden" value="17a7303e-6d2f-44d7-bc2c-7516a04311c4_DSS-620-X-600-1.jpg.pagespeed.ce.4HxAdKZ6OR.jpg">
          <input id="Image3" name="Image3" type="hidden" value="f3914b31-337b-4a16-bb21-9e49e0f8c343_ed1.jpg">
          <input id="Description" name="Description" type="hidden" value="ROSA">
          <input id="Price" name="Price" type="hidden" value="15000.00">
          <input id="Size" name="Size" type="hidden" value="14">
          <input id="ProdName" name="ProdName" type="hidden" value="AFRO KINKY">
          <span class="stext-105 cl3">
            N 15000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">
          <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 0px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg?v=g2USmv3vBYuLBjEOKra5zavJnxo_4CoMlz8LtDl8hLQ" id="imgPix2" alt="IMG-PRODUCT">

        <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
          Quick View
        </a>
      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">
          <a href="/Home/ProductDetail/2" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
            LACE WIG
          </a>

          <input id="Image1" name="Image1" type="hidden" value="5d7e96c5-2c01-4f3f-9cfa-09f327aab817_model-model-remy-dream-weaver-dream-weaver-yaky-10.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="16000.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
          <span class="stext-105 cl3">
            N 16000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">
          <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 0%; top: 445px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg?v=lLlRsUR3vXeV76vghx52VY8HicpXGNKpVTSFurOtleM" id="imgPix2" alt="IMG-PRODUCT">

        <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
          Quick View
        </a>
      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">
          <a href="/Home/ProductDetail/3" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
            LACE WIG
          </a>

          <input id="Image1" name="Image1" type="hidden" value="ed347c52-e1ab-4059-9207-742c04f6d242_KZ6OR.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="22500.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="LACE WIG">
          <span class="stext-105 cl3">
            N 22500.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">
          <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
          </a>
        </div>
      </div>
    </div>
  </div>
  <div class="col-sm-6 col-md-4 col-lg-3 p-b-35 isotope-item women" style="position: absolute; left: 50%; top: 445px;">
    <!-- Block2 -->
    <div class="block2">
      <div class="block2-pic hov-img0">
        <img src="/images/e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg?v=wnPvcpEnY7CmfOZbwzVKf2sfZqeGOUdx0znVbL9RHsU" id="imgPix2" alt="IMG-PRODUCT">

        <a href="#" class="block2-btn flex-c-m stext-103 cl2 size-102 bg0 bor2 hov-btn1 p-lr-15 trans-04 js-show-modal1">
          Quick View
        </a>
      </div>

      <div class="block2-txt flex-w flex-t p-t-14">
        <div class="block2-txt-child1 flex-col-l ">
          <a href="/Home/ProductDetail/4" class="stext-104 cl4 hov-cl1 trans-04 js-name-b2 p-b-6">
            RED ROSES
          </a>

          <input id="Image1" name="Image1" type="hidden" value="e72f6dd5-a2f1-448f-abf6-a3ed08547bb7_ed6.jpg">
          <input id="Image2" name="Image2" type="hidden" value="">
          <input id="Image3" name="Image3" type="hidden" value="">
          <input id="Description" name="Description" type="hidden" value="HAIR DOM">
          <input id="Price" name="Price" type="hidden" value="17000.00">
          <input id="Size" name="Size" type="hidden" value="15">
          <input id="ProdName" name="ProdName" type="hidden" value="RED ROSES">
          <span class="stext-105 cl3">
            N 17000.00
          </span>
        </div>

        <div class="block2-txt-child2 flex-r p-t-3">
          <a href="#" class="btn-addwish-b2 dis-block pos-relative js-addwish-b2">
            <img class="icon-heart1 dis-block trans-04" src="images/icons/icon-heart-01.png" alt="ICON">
            <img class="icon-heart2 dis-block trans-04 ab-t-l" src="images/icons/icon-heart-02.png" alt="ICON">
          </a>
        </div>
      </div>
    </div>
  </div>

</div>


问:
Doing a sum of specific values of an array in java
good afternoon, practicing exercises I am having a problem, which I already identified, but I have not managed to solve, it must be something simple that I do not see, this is what the exercise asks for:

Write a program that reads an array of ints and an integer number n. The program must sum all the array elements greater than n.

Input data format

The first line contains the size of an array.
The second line contains elements of the array separated by spaces.
The third line contains the number n.

Output data format

Only a single number representing the sum.

Sample Input 1:

5

5 8 11 2 10

8

Sample Output 1:

21

This is my code that I have so far:

```<code> public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    int n = in.nextInt();

    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
            if (array[i] > n) {
                sum += array[i];
            }
    }
    System.out.println(sum);
}
</code>```

I identify that my program prints 37 and not 21, because it is not comparing the number well, since it asks me for the value of n in the second line that I enter and it should be after it has the elements of the arrangement, I would like them to help me, try placing if, for, and did not reach the solution.

I really appreciate your time and help, thanks.

答:
You should fill the array before iterating over the numbers and making the comparison. However, the question states that the numbers should be written on the same line separated by space. Here is the solution:

```<code>Scanner in = new Scanner(System.in);
int size = in.nextInt(); //read the size
int[] array = new int[size];
in.nextLine();
String nums = in.nextLine(); //read the array
int n = in.nextInt(); //read n
int sum = 0;
String[] numbers = nums.split(" "); //split array elements
if(numbers.length == size) {
    for(int i = 0; i < numbers.length; i++) {
        int current = Integer.valueOf(numbers[i]); //convert to int
        if(current > n) //compare
            sum += current;
    }
    System.out.println(sum);
}
</code>```

Sample Input/Output:

```<code>5
5 8 11 2 10
8
21
</code>```

Body:
good afternoon, practicing exercises I am having a problem, which I already identified, but I have not managed to solve, it must be something simple that I do not see, this is what the exercise asks for:

Write a program that reads an array of ints and an integer number n. The program must sum all the array elements greater than n.

Input data format

The first line contains the size of an array.
The second line contains elements of the array separated by spaces.
The third line contains the number n.

Output data format

Only a single number representing the sum.

Sample Input 1:

5

5 8 11 2 10

8

Sample Output 1:

21

This is my code that I have so far:

 public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int size = in.nextInt();
    int[] array = new int[size];
    int sum = 0;

    int n = in.nextInt();

    for (int i = 0; i < array.length; i++) {
        array[i] = in.nextInt();
            if (array[i] > n) {
                sum += array[i];
            }
    }
    System.out.println(sum);
}

I identify that my program prints 37 and not 21, because it is not comparing the number well, since it asks me for the value of n in the second line that I enter and it should be after it has the elements of the arrangement, I would like them to help me, try placing if, for, and did not reach the solution.

I really appreciate your time and help, thanks.

Body:
You should fill the array before iterating over the numbers and making the comparison. However, the question states that the numbers should be written on the same line separated by space. Here is the solution:

Scanner in = new Scanner(System.in);
int size = in.nextInt(); //read the size
int[] array = new int[size];
in.nextLine();
String nums = in.nextLine(); //read the array
int n = in.nextInt(); //read n
int sum = 0;
String[] numbers = nums.split(" "); //split array elements
if(numbers.length == size) {
    for(int i = 0; i < numbers.length; i++) {
        int current = Integer.valueOf(numbers[i]); //convert to int
        if(current > n) //compare
            sum += current;
    }
    System.out.println(sum);
}

Sample Input/Output:

5
5 8 11 2 10
8
21


问:
How to check which string resource of a ListItem in a ListView was clicked?
Is there a way to check the string resource of ListView item click rather than index of the ListView (which is often demonstrated in tutorials)?
e.g. I have a ListView with 3 items: "Item A", "Item B" and "Item C". If the string resource of the clicked ListView item is "Item A", do something.

MainPage class

```<code>public sealed partial class MainPage : Page
{
    private List<ListItemMain> mainItems;

    public MainPage()
    {
        this.InitializeComponent();

        gridItemMains = MainItemManger.GetGridItems();
    }

    private void ListView_ItemClick(object sender, ItemClickEventArgs e)
    {

    }
}
</code>```

Item class

```<code>public class ListItem
    {
        public string Name { get; set; }
    }

    public class BookManger
    {
        public static List<Book> GetListItems()
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            var items = new List<Book>
            {
                new Book { Name = resourceLoader.GetString("ItemA") },
                new Book { Name = resourceLoader.GetString("ItemB") },
                new Book { Name = resourceLoader.GetString("ItemC") }
            };

            return items;
        }
    }
</code>```

XAML

```<code><Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding Book}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>
</code>```

答:
You need to set IsItemClickEnabled property to true to get ItemClick event from the ListView.

Refer to docs page for ItemClick Event.

Here is the updated XAML would look like:

```<code><ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick" IsItemClickEnabled="True">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:ListItem">
            <StackPanel>
                <TextBlock Text="{Binding Book}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>
</code>```

And the event handler code:

```<code>void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
    // TODO: Add your code by accessing e.ClickedItem here
}
</code>```

Body:
Is there a way to check the string resource of ListView item click rather than index of the ListView (which is often demonstrated in tutorials)?
e.g. I have a ListView with 3 items: "Item A", "Item B" and "Item C". If the string resource of the clicked ListView item is "Item A", do something.

MainPage class

public sealed partial class MainPage : Page
{
    private List<ListItemMain> mainItems;

    public MainPage()
    {
        this.InitializeComponent();

        gridItemMains = MainItemManger.GetGridItems();
    }

    private void ListView_ItemClick(object sender, ItemClickEventArgs e)
    {

    }
}

Item class

public class ListItem
    {
        public string Name { get; set; }
    }

    public class BookManger
    {
        public static List<Book> GetListItems()
        {
            var resourceLoader = Windows.ApplicationModel.Resources.ResourceLoader.GetForCurrentView();

            var items = new List<Book>
            {
                new Book { Name = resourceLoader.GetString("ItemA") },
                new Book { Name = resourceLoader.GetString("ItemB") },
                new Book { Name = resourceLoader.GetString("ItemC") }
            };

            return items;
        }
    }

XAML

<Page
    x:Class="My_App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:data="using:My_App.Models"
    mc:Ignorable="d">

        <ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="data:ListItem">
                    <StackPanel>
                        <TextBlock Text="{Binding Book}" />
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
</Page>

Body:
You need to set IsItemClickEnabled property to true to get ItemClick event from the ListView.

Refer to docs page for ItemClick Event.

Here is the updated XAML would look like:

<ListView ItemsSource="{x:Bind listItems}" ItemClick="ListView_ItemClick" IsItemClickEnabled="True">
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="data:ListItem">
            <StackPanel>
                <TextBlock Text="{Binding Book}" />
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And the event handler code:

void ListView_ItemClick(object sender, ItemClickEventArgs e)
{
    // TODO: Add your code by accessing e.ClickedItem here
}


问:
fread() under mingw not working properly
I have written a C application under Linux with GTK. A friend wanted to test it under Windows. So we compiled it using MinGW64.

The GUI and everything looks/works as it should. However, the fread() call does not work.

```<code>read = fread(workbuff, sizeof(char), rec_data_length, bin_file);

    if (read != rec_data_length) {
        /* Here is some error handling */
    }
</code>```

rec_data_length is 608. I ensured that the file is not corrupted and that these 608 bytes are available. The function returns 87.

Can someone explain this to me? Why does it work under Linux but not under Windows?

答:
The problem with reading from this file was, that I opened a binary file with

```<code>fopen("foo", "r");
</code>```

This worked fine under Linux. But on Windows I had to change it to

```<code>fopen("foo", "rb");
</code>```

This solution works on both systems and behaves now as expected.

Body:
I have written a C application under Linux with GTK. A friend wanted to test it under Windows. So we compiled it using MinGW64.

The GUI and everything looks/works as it should. However, the fread() call does not work.

read = fread(workbuff, sizeof(char), rec_data_length, bin_file);

    if (read != rec_data_length) {
        /* Here is some error handling */
    }

rec_data_length is 608. I ensured that the file is not corrupted and that these 608 bytes are available. The function returns 87.

Can someone explain this to me? Why does it work under Linux but not under Windows?

Body:
The problem with reading from this file was, that I opened a binary file with

fopen("foo", "r");

This worked fine under Linux. But on Windows I had to change it to

fopen("foo", "rb");

This solution works on both systems and behaves now as expected.


问:
How to add a header in the margin?
I need to include a header in a page like this simple Google page:

I am trying to put the text "Google" inside the top margin of the page but it's 2.5 cm under, when the top margin ends). I want this:

My HTML file:

```<code><html lang="es-AR">
<body>
    <header>Google</header>
    <h1 class="title">Hello, world</h1>
    Trying to put a header.
</body>
</html>
</code>```

My CSS file:

```<code>@page {
    size: 21cm 29.7cm;
    margin-top: 2.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}
</code>```

The page is a report so it will be printed.

答:
One option is to take the margin-top from the @page (since you will not have an actual margin on page view, you want an html content to be there) and give the header fixed height of 2.5cm which will function as your top margin:

```<code>@page{
      size: 21cm 29.7cm;
      margin-right: 2.5cm;
      margin-bottom: 2.5cm;
      margin-left: 2.5cm;
}

header{
    height: 2.5cm
}
</code>```

Title: How to add a header in the margin?

Body:
I need to include a header in a page like this simple Google page:

I am trying to put the text "Google" inside the top margin of the page but it's 2.5 cm under, when the top margin ends). I want this:

My HTML file:

    Google

Hello, world

    Trying to put a header.

My CSS file:

@page {
    size: 21cm 29.7cm;
    margin-top: 2.5cm;
    margin-right: 2.5cm;
    margin-bottom: 2.5cm;
    margin-left: 2.5cm;
}

The page is a report so it will be printed.

Body:
One option is to take the margin-top from the @page (since you will not have an actual margin on page view, you want an html content to be there) and give the header fixed height of 2.5cm which will function as your top margin:

@page{
      size: 21cm 29.7cm;
      margin-right: 2.5cm;
      margin-bottom: 2.5cm;
      margin-left: 2.5cm;
}

header{
    height: 2.5cm
}


问:
integrate() gives totally wrong number
integrate() gives horribly wrong answer:

```<code>integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23
</code>```

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

```<code>require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0
</code>```

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

```<code>integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))
</code>```

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

答:
From the online documentation:  "Like all numerical integration routines, these evaluate the function on a finite set of points. If the function is approximately constant (in particular, zero) over nearly all its range it is possible that the result and error estimate may be seriously wrong."

I take this to mean "caveat emptor".  I notice that in your example, the absolute error is greater than value of the integral.  Given that you know f(x) > 0 for all x, at least it's giving you the chance to spot that something has gone wrong.  It's down to you to take the opportunity.

```<code>integrate( function(x) dnorm(x, -5, 0.07), -20, 10, subdivisions=1000L)
</code>```

Gives

```<code>1 with absolute error < 9.8e-07
</code>```

The warning in the online doc says to me that, given your apparent definition of buggy, the answer to your question is "no, there is no reliable numerical intergration method.  Not in R or any other language".  No numerical integration technique should be used blindly.  The user needs to check their inputs are sensible and the output is reasonable.  It's no good believing an answer just because the computer gave it to you.

See also this post.

Title: integrate() gives totally wrong number

Body:
integrate() gives horribly wrong answer:

integrate(function (x) dnorm(x, -5, 0.07), -Inf, Inf, subdivisions = 10000L)
# 2.127372e-23 with absolute error < 3.8e-23

The return value should obviously be 1 (normal distrubution integrates to 1), but integrate() returns ridiculously small number, with wrong error reporting, and no warning...

Any ideas?

This seems the default integrate() is horribly buggy... and I just found this by chance! Is there any reliable R package to compute numerical integration?

EDIT: I tried package pracma and I see the same problem! :

require(pracma)
integral(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
# For infinite domains Gauss integration is applied!
# [1] 0

EDIT: Hmm... digging deeper, it seems that he has trouble to find the very narrow domain for the function which is numerically > 0. When I set the limits  to certain (very close to 0, 1) quantiles, it starts to work:

integral(function (x) dnorm(x, -5, 0.07), qnorm(1e-10, -5, 0.07), qnorm(1 - 1e-10, -5, 0.07))

But anyway, this is quite horrible gotcha... wonder if there is any remedy for this.

Body:
From the online documentation:  "Like all numerical integration routines, these evaluate the function on a finite set of points. If the function is approximately constant (in particular, zero) over nearly all its range it is possible that the result and error estimate may be seriously wrong."

I take this to mean "caveat emptor".  I notice that in your example, the absolute error is greater than value of the integral.  Given that you know f(x) > 0 for all x, at least it's giving you the chance to spot that something has gone wrong.  It's down to you to take the opportunity.

integrate( function(x) dnorm(x, -5, 0.07), -20, 10, subdivisions=1000L)

Gives

1 with absolute error < 9.8e-07

The warning in the online doc says to me that, given your apparent definition of buggy, the answer to your question is "no, there is no reliable numerical intergration method.  Not in R or any other language".  No numerical integration technique should be used blindly.  The user needs to check their inputs are sensible and the output is reasonable.  It's no good believing an answer just because the computer gave it to you.

See also this post.


答:
Try package cubature.

```<code>library(cubature)

hcubature(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
#$integral
#[1] 1
#
#$error
#[1] 9.963875e-06
#
#$functionEvaluations
#[1] 405
#
#$returnCode
#[1] 0
</code>```

Note that function pcubature in the same package also returns 0.

From vignette("cubature"), section Introduction. My emphasis.

This R cubature package exposes both the hcubature and pcubature
  routines of the underlying C cubature library, including the
  vectorized interfaces.

Per the documentation, use of pcubature is advisable only for smooth
  integrands in dimensions up to three at most. In fact, the pcubature
  routines perform significantly worse than the vectorized hcubature
  in inappropriate cases. So when in doubt, you are better off using
  hcubature.

Since in this case the integrand is the normal density, a smooth and 1-dimensional function, there would be reasons to prefer pcubature. But it doesn't give the right result. The vignette concludes the following.

Vectorized hcubature seems to be a good starting point.

For smooth integrands in low dimensions (≤3),  pcubature might be worth trying out. Experiment before using in a production package.

Title: integrate() gives totally wrong number

Body:
Try package cubature.

library(cubature)

hcubature(function (x) dnorm(x, -5, 0.07), -Inf, Inf)
#$integral
#[1] 1
#
#$error
#[1] 9.963875e-06
#
#$functionEvaluations
#[1] 405
#
#$returnCode
#[1] 0

Note that function pcubature in the same package also returns 0.

From vignette("cubature"), section Introduction. My emphasis.

This R cubature package exposes both the hcubature and pcubature
  routines of the underlying C cubature library, including the
  vectorized interfaces.

Per the documentation, use of pcubature is advisable only for smooth
  integrands in dimensions up to three at most. In fact, the pcubature
  routines perform significantly worse than the vectorized hcubature
  in inappropriate cases. So when in doubt, you are better off using
  hcubature.

Since in this case the integrand is the normal density, a smooth and 1-dimensional function, there would be reasons to prefer pcubature. But it doesn't give the right result. The vignette concludes the following.

Vectorized hcubature seems to be a good starting point.

For smooth integrands in low dimensions (≤3),  pcubature might be worth trying out. Experiment before using in a production package.


问:
How do I use the iPhone Simulator in 3.2 (not iPad Simulator)
I'm fixing my app to be a universal binary.  Testing on the simulator seems to default to the iPad.  For small corrections like checking orientations and small UI updates, the only way I can find to get the iPhone version is to plug in my iPhone and build and run on device.

Loading the debugger takes valuable time, when running on simulator is so much faster for this kind of work.  Can I set the simulator to default to iPhone for this?  Setting it to 3.1.3 doesn't work because of the 3.2 code I have in the binary for the iPad.

EDIT:

The Hardware -> Device, and ->Version menu choices in the simulator quits my app.  When I relaunch, it goes back to the iPad.  The app is not installed in the simulator

答:
I finally solved this problem myself.

First, install new version of xCode, which is xCode 4.

Then set project scheme to iphone simulator and run app in xCode several times.

And re-install xCode 3 and the problem will be gone away!

ContentLicense: CC BY-SA 2.5


问:
Any other reason forEach() is provided a reference to the array itself aside from scoping?
According to MDN, the callback provided to the forEach function is given 3 parameters: currentValue, index, array.

I'm trying to understand the purpose the forEach callback is provided the reference to the array itself as the 3rd parameter and the only reason I can see why is because of scoping.

1st Example:

function printLastName(value, index, array) {
  if (index === (array.length - 1)) {
    console.log(value);
  }
}

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach(printLastName);
}

setupNames();

```

<p>What I wish to illustrate in the 1st example above is that <code>printLastName()</code> used as the <code>forEach()</code> callback does not have a reference to the original <code>names</code> array and thus, if it needs to use the array, it needs to be provided the <code>3rd parameter</code>, hence the only reason I see why the <code>forEach</code> callback is provided a reference to the original <code>array</code>. </p>

<p>2nd Example:</p>

<pre class="lang-js prettyprint-override"><code>function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach((value, index, array) => {
    if (index === (names.length - 1)) {
      console.log(value);
    }
  });
}

setupNames();
</code>```

In the 2nd example, the line (index === (names.length - 1)), I could have either used names or array since it's available to me. And to my understanding, there is absolutely no difference using either one.

To wrap it up, here's my question:

The callback to the forEach method is provided the array as the 3rd parameter solely because of scoping issue (1st Example) and not for any other reason, correct?

In the 2nd example, there is absolutely no difference between me using names or array in the lambda callback to forEach no matter what the lambda callback logic is, correct?

答:
I came across this use-case recently which made me understand why the array parameter can be useful (when I previously didn't see the usefulness of it either).

Consider:

```<code>const names = ['John', 'Paul', 'John Paul', 'John Smith', 'James'];

names.filter(n => n.startsWith('John')).forEach((john, index, array) => {
   // If it's not the first or last entry, then we want to write it to console
   if (index !== 0 || index !== array.length - 1) console.log(john);
});
</code>```

If you are creating a new collection as the result of a .filter etc, then the new collection won't be available as a reference if written as above. The array parameter provides you access to the collection that you are iterating with .forEach.

Body:
According to MDN, the callback provided to the forEach function is given 3 parameters: currentValue, index, array.

I'm trying to understand the purpose the forEach callback is provided the reference to the array itself as the 3rd parameter and the only reason I can see why is because of scoping.

1st Example:

function printLastName(value, index, array) {
  if (index === (array.length - 1)) {
    console.log(value);
  }
}

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach(printLastName);
}

setupNames();

What I wish to illustrate in the 1st example above is that printLastName() used as the forEach() callback does not have a reference to the original names array and thus, if it needs to use the array, it needs to be provided the 3rd parameter, hence the only reason I see why the forEach callback is provided a reference to the original array.

2nd Example:

function setupNames() {
  const names = ['A', 'B', 'C'];
  names.forEach((value, index, array) => {
    if (index === (names.length - 1)) {
      console.log(value);
    }
  });
}

setupNames();

In the 2nd example, the line (index === (names.length - 1)), I could have either used names or array since it's available to me. And to my understanding, there is absolutely no difference using either one.

To wrap it up, here's my question:

The callback to the forEach method is provided the array as the 3rd parameter solely because of scoping issue (1st Example) and not for any other reason, correct?

In the 2nd example, there is absolutely no difference between me using names or array in the lambda callback to forEach no matter what the lambda callback logic is, correct?

Body:
I came across this use-case recently which made me understand why the array parameter can be useful (when I previously didn't see the usefulness of it either).

Consider:

const names = ['John', 'Paul', 'John Paul', 'John Smith', 'James'];

names.filter(n => n.startsWith('John')).forEach((john, index, array) => {
   // If it's not the first or last entry, then we want to write it to console
   if (index !== 0 || index !== array.length - 1) console.log(john);
});

If you are creating a new collection as the result of a .filter etc, then the new collection won't be available as a reference if written as above. The array parameter provides you access to the collection that you are iterating with .forEach.


问:
Flutter Stack and Card using
I want it to look like the first picture, but I couldn't find a way, please help?

I try to stack and positioned widget for this but when i use positioned widget top or left negative value my container doesnt seem i couldn't handle it.

my main problem is i can't get the green circle container out of the card area

```<code>Stack(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(left: 10),
                          child: Center(
                            child: Container(
                              width: 52,
                              height: 52,
                              decoration: BoxDecoration(
                                color: Color(0xffDCDCDC),
                                borderRadius: BorderRadius.circular(20),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          top: 0,
                          left: 0,
                          child: Container(
                            width: 31,
                            height: 19,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: Color(0xffE9E9E9),
                            ),
                            child: Container(
                              margin: EdgeInsets.only(left: 12),
                              decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Colors.white),
                              child: Container(
                                width: 15,
                                height: 15,
                                decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(0xff5CE02E)),
                              ),
                            ),
                          ),
                        ),
</code>```

答:
```<code>Stack(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(left: 10),
                          child: Center(
                            child: Container(
                              width: 52,
                              height: 52,
                              decoration: BoxDecoration(
                                color: Color(0xffDCDCDC),
                                borderRadius: BorderRadius.circular(20),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          top: 10,
                          left: 10,
                          child: Container(
                            width: 31,
                            height: 19,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: Color(0xffE9E9E9),
                            ),
                            child: Container(
                              margin: EdgeInsets.only(left: 12),
                              decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Colors.white),
                              child: Container(
                                width: 15,
                                height: 15,
                                decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(0xff5CE02E)),
                              ),
                            ),
                          ),
                        ),
</code>```

Title: Flutter Stack and Card using

Body:
I want it to look like the first picture, but I couldn't find a way, please help?

I try to stack and positioned widget for this but when i use positioned widget top or left negative value my container doesnt seem i couldn't handle it.

my main problem is i can't get the green circle container out of the card area

Stack(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.only(left: 10),
                          child: Center(
                            child: Container(
                              width: 52,
                              height: 52,
                              decoration: BoxDecoration(
                                color: Color(0xffDCDCDC),
                                borderRadius: BorderRadius.circular(20),
                              ),
                            ),
                          ),
                        ),
                        Positioned(
                          top: 0,
                          left: 0,
                          child: Container(
                            width: 31,
                            height: 19,
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              color: Color(0xffE9E9E9),
                            ),
                            child: Container(
                              margin: EdgeInsets.only(left: 12),
                              decoration: BoxDecoration(
                                  shape: BoxShape.circle,
                                  color: Colors.white),
                              child: Container(
                                width: 15,
                                height: 15,
                                decoration: BoxDecoration(
                                    shape: BoxShape.circle,
                                    color: Color(0xff5CE02E)),
                              ),
                            ),
                          ),
                        ),


问:
Cannot assign to read only property on deep copied object
I am using angular 9 and ngrx 9

I have a selector that do like this :

```<code>    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });
</code>```

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

```<code>      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>
</code>```

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));
</code>```

Which call this reducer :

```<code>const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};
</code>```

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

```<code>this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));
</code>```

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.

答:
These state mutations in a reducer are actually increasing the performance.
It's faster than a (unneeded) rerender of a component, you could make use of the OnPush pipe because the reference of the state will change which will only cause a rerender when it's actually needed.

The docs of Redux has a performance page, which can also be applied to NgRx.

If you don't like to update state this way, there's immer. I actually wrote an immer wrapper around an NgRx reducer. See ngrx-etc.
NgRx also provides the ngrx-entity package which has some helpers to update the state.

Body:
I am using angular 9 and ngrx 9

I have a selector that do like this :

    this.store$
      .pipe(select(SettingsStoreSelectors.selectNavigationSettings), take(1))
      .subscribe((settings: SettingsStoreModels.INavigationSettings) => {
        let copy = JSON.parse(JSON.stringify(settings));
        this.settings = copy.vrMapSettings;
      });

This is the only place settings is assigned in this component

In the component I then have a checkbox that edit a setting property

      <mat-checkbox
        class="setting-input"
        *ngIf="viewer"
        (click)="$event.stopPropagation()"
        (change)="onSettingChange(settings, true)"
        [(ngModel)]="settings.depthTestAgainstTerrain"
      >
        {{ "MAP.SETTINGS.DEPTH_TEST_AGAINST_TERRAIN" | translate }}
      </mat-checkbox>

This keeps triggering

core.js:4117 ERROR TypeError: Cannot assign to read only property 'depthTestAgainstTerrain' of object '[object Object]'

But I don't understand anymore what to do. I deep cloned my store property, I want to edit to resubmit an action but it's not possible. why...

EDIT : actually I found out the reason why but I do not understand how to use it correctly then.

I deep clone the object like above from my selector

When a setting change, I dispatch an action to change the setting object in the store : this action setting object reference the same object that is used by the component.

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: settings } }));

Which call this reducer :

const SET_NAVIGATION_SETTINGS = (state: State, action: featureAction.SetNavigationSettings) => {
  return {
    ...state,
    navigation: {
      ...state.navigation,
      ...action.payload.settings,
    },
  };
};

But then, if I edit again, since the store reference directly the setting object of the component, it trigger the error....

If I deep clone here too

this.store$.dispatch(new SettingsStoreAction.SetNavigationSettings({ settings: { vrMapSettings: JSON.parse(JSON.stringify(settings))} }));

The it works...

But if I have to create small action for EVERY property of settings, or deep clone for EVERY dispatch/selection of the store, there is going to be a HUGE flaw in the performance...

am I using it correctly ?

if need more information please comment I will provide.


问:
Is it possible to define both const and regular version of the function with a single definition? (using templates, auto, decltype, etc)
Suppose that I am writing an iterator and const_iterator for singly linked list.

Suppose that I have a following classes:

```<code>template <typename T>
struct Node
{
    T value;
    Node* next;
}

template <typename T>
struct NodePtr
{
private:
     Node<T>* node;
public:
     T& operator*() { return node->value; }
     const T& operator*() const { return node->value; }

     // Ommitted increment, comparison and so on...
}

class Iterator<T, bool isConst>
{
     private: NodePtr<T> nodePtr;
     using Reference = std::conditional_t<isConst, const T&, T&>;

     Reference operator*() { return *nodePtr; }
     const Reference operator*() const { return *nodePtr; }

     // Ommited
}
</code>```

My question is whether it is possible somehow to replace the lines

```<code>Reference operator*() { return node->value; }
const Reference operator*() const { return node->value; }
</code>```

with a single definition (perhaps using the template argument isConst) and have the const specifier deduced by the compiler?
I want to have * to be const T& operator*() const when isConst = true
and have both versions when isConst = false.
Is it possible? If it is - then how to do it?

答:
I don't think there is a way to write the function only once. Most things you can do with auto and templates but the problem is the const specifier for the function itself. I know of no way to make that in any form conditional. You could make it always const and then the nodePtr mutable but that kind of defeats the point of the whole thing. What you can do is deactivate the non-const overload for the const_iter by doing the following

```<code>template<bool tmp = isConst, std::enable_if_t<!tmp, char> = 0> // you need the tmp so that the enable_if is dependent
Reference operator*() {
    return *nodePtr;
}
</code>```

Body:
Suppose that I am writing an iterator and const_iterator for singly linked list.

Suppose that I have a following classes:

template <typename T>
struct Node
{
    T value;
    Node* next;
}

template <typename T>
struct NodePtr
{
private:
     Node<T>* node;
public:
     T& operator*() { return node->value; }
     const T& operator*() const { return node->value; }

     // Ommitted increment, comparison and so on...
}

class Iterator<T, bool isConst>
{
     private: NodePtr<T> nodePtr;
     using Reference = std::conditional_t<isConst, const T&, T&>;

     Reference operator*() { return *nodePtr; }
     const Reference operator*() const { return *nodePtr; }

     // Ommited
}

My question is whether it is possible somehow to replace the lines

Reference operator*() { return node->value; }
const Reference operator*() const { return node->value; }

with a single definition (perhaps using the template argument isConst) and have the const specifier deduced by the compiler?
I want to have * to be const T& operator*() const when isConst = true
and have both versions when isConst = false.
Is it possible? If it is - then how to do it?

Body:
I don't think there is a way to write the function only once. Most things you can do with auto and templates but the problem is the const specifier for the function itself. I know of no way to make that in any form conditional. You could make it always const and then the nodePtr mutable but that kind of defeats the point of the whole thing. What you can do is deactivate the non-const overload for the const_iter by doing the following

template<bool tmp = isConst, std::enable_if_t<!tmp, char> = 0> // you need the tmp so that the enable_if is dependent
Reference operator*() {
    return *nodePtr;
}


问:
Add item to pandas.Series?
I want to add an integer to my pandas.Series

Here is my code:

```<code>import pandas as pd
input = pd.Series([1,2,3,4,5])
input.append(6)
</code>```

When i run this, i get the following error:

```<code>Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.append(6)
  File "C:\Python33\lib\site-packages\pandas\core\series.py", line 2047, in append
    verify_integrity=verify_integrity)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 878, in concat
    verify_integrity=verify_integrity)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 954, in __init__
    self.new_axes = self._get_new_axes()
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1146, in _get_new_axes
    concat_axis = self._get_concat_axis()
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in _get_concat_axis
    indexes = [x.index for x in self.objs]
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in <listcomp>
    indexes = [x.index for x in self.objs]
AttributeError: 'int' object has no attribute 'index'
</code>```

How can I fix that?

答:
here is a one-line answer It is dependent on how the array is defined. If we use Series is a one d array. Use the array notation like x[index] = new value

example

```<code>import pandas as pd
input = pd.Series([1,2,3,4,5])
newval = 7 # say
input[len(input)] = newval
</code>```

or
use append if the array is being directly defined.

```<code>#if input is defined as []
input2 = [1, 2]
#input2[len(input2)] = 3 # does not work
input2.append(3) #works
input2
</code>```

Title: Add item to pandas.Series?

Body:
I want to add an integer to my pandas.Series

Here is my code:

import pandas as pd
input = pd.Series([1,2,3,4,5])
input.append(6)

When i run this, i get the following error:

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.append(6)
  File "C:\Python33\lib\site-packages\pandas\core\series.py", line 2047, in append
    verify_integrity=verify_integrity)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 878, in concat
    verify_integrity=verify_integrity)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 954, in __init__
    self.new_axes = self._get_new_axes()
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1146, in _get_new_axes
    concat_axis = self._get_concat_axis()
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in _get_concat_axis
    indexes = [x.index for x in self.objs]
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1163, in <listcomp>
    indexes = [x.index for x in self.objs]
AttributeError: 'int' object has no attribute 'index'

How can I fix that?

Body:
here is a one-line answer It is dependent on how the array is defined. If we use Series is a one d array. Use the array notation like x[index] = new value

example

import pandas as pd
input = pd.Series([1,2,3,4,5])
newval = 7 # say
input[len(input)] = newval

or
use append if the array is being directly defined.

#if input is defined as []
input2 = [1, 2]
#input2[len(input2)] = 3 # does not work
input2.append(3) #works
input2