问:
Table Id field automatically append with table name that produce invalid column name
I have table Categories With Id column when insert occur is shows it shows errorSqlException: Invalid column name 'CategoriesId'.</p>

```<code> public partial class Categories
    {
        public Categories()
        {
            CategoryTabs = new HashSet<CategoryTabs>();
        }

        public int Id { get; set; }
        public string Title { get; set; }
        public int? ParentId { get; set; }
        public int? SeasonId { get; set; }
        public int? Levels { get; set; }
        public string Image { get; set; }
        public string Description { get; set; }

        public virtual Seasons Season { get; set; }
        public List<Categories> children { get; set; }
        public virtual ICollection<CategoryTabs> CategoryTabs { get; set; }
    }

 public partial class CategoryTabs
    {
        public int Id { get; set; }
        public int? CategoryId { get; set; }
        public int? TabId { get; set; }
         public virtual Categories Category { get; set; }
        public virtual Tabs Tab { get; set; }
    }
</code>```

答:
CategoriesId is the conventional name for the Foreign Key property/column associated with the one-to-many self relationship introduced by

```<code>public List<Categories> children { get; set; }
</code>```

collection navigation property inside Categories entity.

Looking at the entity model, most likely the idea was to use the ParentId for that purpose. Since it doesn't match EF Core naming conventions, it has to be mapped explicitly by using either ForeignKey data annotation:

```<code>[ForeignKey(nameof(ParentId))]
public List<Categories> children { get; set; }
</code>```

or fluent API inside OnModelCreating override:

```<code>modelBuilder.Entity<Categories>()
    .HasMany(e => e.children)
    .WithOne()
    .HasForeignKey(e => e.ParentId);
</code>```

Body:
I have table Categories With Id column when insert occur is shows it shows errorSqlException: Invalid column name 'CategoriesId'.

 public partial class Categories
    {
        public Categories()
        {
            CategoryTabs = new HashSet<CategoryTabs>();
        }

        public int Id { get; set; }
        public string Title { get; set; }
        public int? ParentId { get; set; }
        public int? SeasonId { get; set; }
        public int? Levels { get; set; }
        public string Image { get; set; }
        public string Description { get; set; }

        public virtual Seasons Season { get; set; }
        public List<Categories> children { get; set; }
        public virtual ICollection<CategoryTabs> CategoryTabs { get; set; }
    }

 public partial class CategoryTabs
    {
        public int Id { get; set; }
        public int? CategoryId { get; set; }
        public int? TabId { get; set; }
         public virtual Categories Category { get; set; }
        public virtual Tabs Tab { get; set; }
    }

Body:
CategoriesId is the conventional name for the Foreign Key property/column associated with the one-to-many self relationship introduced by

public List<Categories> children { get; set; }

collection navigation property inside Categories entity.

Looking at the entity model, most likely the idea was to use the ParentId for that purpose. Since it doesn't match EF Core naming conventions, it has to be mapped explicitly by using either ForeignKey data annotation:

[ForeignKey(nameof(ParentId))]
public List<Categories> children { get; set; }

or fluent API inside OnModelCreating override:

modelBuilder.Entity<Categories>()
    .HasMany(e => e.children)
    .WithOne()
    .HasForeignKey(e => e.ParentId);


来源: stackexchange

问:
Get disks information and output to one line
I am trying to read the information on the storage drives and would like to output the results as (on 1 line):

```
1/2 - Samsung Evo - 500GB - 4 partitions - C :, D :, E :, F:
2/2 - USB Transcend - 16GB - 2 partitions - G :, H:
```

```<code>On Error Resume Next
' Create a FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
' Provide file path
Dim result, strComputer, outFile, PropertyArr, ArrayItem
outFile = "C:\Users\MISS\Desktop\ok.txt"
' Sets computer name to the current computer name
strComputer = "."
' Setting up file to write
Set objFile = FSO.CreateTextFile(outFile, True)
' Connect to the WMI Service
Set CIMV2 = GetObject("winmgmts:" & "\\" & strComputer & "\root\CIMV2")
If Err Then
    WScript.StdOut.WriteLine "Unable to access WMI Service."
    WScript.Quit 32
End If
' Fetch all details from Win32_computersystem
Set Win32_DiskDrive = CIMV2.ExecQuery("Select * from Win32_DiskDrive")
PropertyArr = Array("Model","MediaType")
For Each item_PropertyArr In PropertyArr
    ArrayItem = item_PropertyArr
Next
For Each item In Win32_DiskDrive
    result = item.ArrayItem
    WScript.Echo "Result: " & result
Next

Set FSO = Nothing
</code>```

It is empty result.

答:
To get the string output in the desired format, I would suggest using a template string and use Replace() to fill in the details.

Because you want the driveletters that are associated with each partition aswell, you need to do more than just query the Win32_DiskDrive, because that query does not return driveletters. See here

The below code should do what you want:

```<code>Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objDriveLetters, objLogicalDisk
Dim outFile, strFormat, strResult, numCurrentDrive, strMediaType, strID, strQuery, strComputer

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'create an arraylist to capture the drive letters
    Set objDriveLetters = CreateObject("System.Collections.ArrayList")

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            objDriveLetters.Add objLogicalDisk.DeviceID
            'objDriveLetters.Add objLogicalDisk.VolumeName
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(objDriveLetters.ToArray(), ", ")

    Set objDriveLetters = Nothing
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing
</code>```

Update

As per your comments, you would like to not use .NET (the ArrayList) in the code. This can be done of course, but with a little bit more effort:

```<code>Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objLogicalDisk
Dim outFile, strFormat, strResult, strMediaType, strID, strQuery, strComputer
Dim arrDriveLetters, numCurrentDrive, numDriveLetters

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'reset the dynamic array to capture the drive letters
    numDriveLetters = 0
    ReDim arrDriveLetters(numDriveLetters)

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            ReDim Preserve arrDriveLetters(numDriveLetters)
            arrDriveLetters(numDriveLetters) = objLogicalDisk.DeviceID
            numDriveLetters = numDriveLetters + 1
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(arrDriveLetters, ", ")

    Erase arrDriveLetters
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing
</code>```

The output will be something like

```<code>1/4 - Samsung SSD 750 EVO 250GB ATA Device - Fixed hard disk media - 1 partition(s) - C:
2/4 - ST3500418AS ATA Device - Fixed hard disk media - 1 partition(s) - E:
3/4 - WDC WD7501AALS-00J7B0 ATA Device - Fixed hard disk media - 1 partition(s) - D:
4/4 - Generic Ultra HS-SD/MMC USB Device - Unknown - 0 partition(s)
</code>```

Hope that helps

P.S. Best run using CScript instead of WScript, to avoid having popup messages with one line at a time

ContentLicense: CC BY-SA 4.0

Body:
I am trying to read the information on the storage drives and would like to output the results as (on 1 line):

1/2 - Samsung Evo - 500GB - 4 partitions - C :, D :, E :, F:
2/2 - USB Transcend - 16GB - 2 partitions - G :, H:

On Error Resume Next
' Create a FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
' Provide file path
Dim result, strComputer, outFile, PropertyArr, ArrayItem
outFile = "C:\Users\MISS\Desktop\ok.txt"
' Sets computer name to the current computer name
strComputer = "."
' Setting up file to write
Set objFile = FSO.CreateTextFile(outFile, True)
' Connect to the WMI Service
Set CIMV2 = GetObject("winmgmts:" & "\\" & strComputer & "\root\CIMV2")
If Err Then
    WScript.StdOut.WriteLine "Unable to access WMI Service."
    WScript.Quit 32
End If
' Fetch all details from Win32_computersystem
Set Win32_DiskDrive = CIMV2.ExecQuery("Select * from Win32_DiskDrive")
PropertyArr = Array("Model","MediaType")
For Each item_PropertyArr In PropertyArr
    ArrayItem = item_PropertyArr
Next
For Each item In Win32_DiskDrive
    result = item.ArrayItem
    WScript.Echo "Result: " & result
Next

Set FSO = Nothing

It is empty result.

Body:
To get the string output in the desired format, I would suggest using a template string and use Replace() to fill in the details.

Because you want the driveletters that are associated with each partition aswell, you need to do more than just query the Win32_DiskDrive, because that query does not return driveletters. See here

The below code should do what you want:

Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objDriveLetters, objLogicalDisk
Dim outFile, strFormat, strResult, numCurrentDrive, strMediaType, strID, strQuery, strComputer

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'create an arraylist to capture the drive letters
    Set objDriveLetters = CreateObject("System.Collections.ArrayList")

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            objDriveLetters.Add objLogicalDisk.DeviceID
            'objDriveLetters.Add objLogicalDisk.VolumeName
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(objDriveLetters.ToArray(), ", ")

    Set objDriveLetters = Nothing
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing

Update

As per your comments, you would like to not use .NET (the ArrayList) in the code. This can be done of course, but with a little bit more effort:

Option Explicit

Const ForAppending = 8
Dim objFso, objFile, objWMIService, colDiskDrives, objDiskDrive
Dim colPartitions, objDiskPartition, colLogicalDisks, objLogicalDisk
Dim outFile, strFormat, strResult, strMediaType, strID, strQuery, strComputer
Dim arrDriveLetters, numCurrentDrive, numDriveLetters

On Error Resume Next

' set up file to write
outFile = "C:\Users\MISS\Desktop\ok.txt"

Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FileExists(outFile) Then objFso.DeleteFile outFile, True
Set objFile = objFso.OpenTextFile(outFile, ForAppending, True)

strComputer = "."
Set objWMIService = GetObject( "winmgmts:{ impersonationLevel=Impersonate }!//" & strComputer )
Set colDiskDrives = objWMIService.ExecQuery( "Select * FROM Win32_DiskDrive" )

'set up a string as template for the output
strFormat = "{0}/{1} - {2} - {3} - {4} partition(s)"
'create a variable for the current disk count
numCurrentDrive = 1
For Each objDiskDrive In colDiskDrives
    'start building the string to output
    strMediaType = objDiskDrive.MediaType
    If IsNull(strMediaType) Or Len(strMediaType) = 0 Then strMediaType = "Unknown"
    strResult = Replace(strFormat, "{0}", numCurrentDrive)
    strResult = Replace(strResult, "{1}", colDiskDrives.Count)
    strResult = Replace(strResult, "{2}", objDiskDrive.Model)
    strResult = Replace(strResult, "{3}", strMediaType)
    strResult = Replace(strResult, "{4}", objDiskDrive.Partitions)

    'increase the current drive counter
    numCurrentDrive = numCurrentDrive + 1
    'reset the dynamic array to capture the drive letters
    numDriveLetters = 0
    ReDim arrDriveLetters(numDriveLetters)

    'escape the backslashes in objDiskDrive.DeviceID for the query
    strID = Replace( objDiskDrive.DeviceID, "\", "\\", 1, -1, vbTextCompare )
    strQuery = "Associators Of {Win32_DiskDrive.DeviceID=""" & strID & """} Where AssocClass = Win32_DiskDriveToDiskPartition"
    Set colPartitions = objWMIService.ExecQuery(strQuery)
    For Each objDiskPartition In colPartitions
        'get the drive letter for each partition
        strQuery = "Associators Of {Win32_DiskPartition.DeviceID=""" & objDiskPartition.DeviceID & """} Where AssocClass = Win32_LogicalDiskToPartition"
        Set colLogicalDisks = objWMIService.ExecQuery(strQuery)
        For Each objLogicalDisk In colLogicalDisks
            ReDim Preserve arrDriveLetters(numDriveLetters)
            arrDriveLetters(numDriveLetters) = objLogicalDisk.DeviceID
            numDriveLetters = numDriveLetters + 1
        Next

        Set colLogicalDisks = Nothing
    Next

    'add the driveletters to the output string
    strResult = strResult & " - " & Join(arrDriveLetters, ", ")

    Erase arrDriveLetters
    Set colPartitions = Nothing

    'output on screen
    WScript.Echo strResult
    'output to file
    objFile.WriteLine strResult
Next

'close the file
objFile.Close
Set objFile = Nothing
Set colDiskDrives = Nothing
Set objWMIService = Nothing

The output will be something like

1/4 - Samsung SSD 750 EVO 250GB ATA Device - Fixed hard disk media - 1 partition(s) - C:
2/4 - ST3500418AS ATA Device - Fixed hard disk media - 1 partition(s) - E:
3/4 - WDC WD7501AALS-00J7B0 ATA Device - Fixed hard disk media - 1 partition(s) - D:
4/4 - Generic Ultra HS-SD/MMC USB Device - Unknown - 0 partition(s)

Hope that helps

P.S. Best run using CScript instead of WScript, to avoid having popup messages with one line at a time


问:
How to use QString toUtf8 and fromUtf8?
I have a weird problem:

```<code>    QString s1="abc";
    const char * ss1=s1.toUtf8().constData();
    QString s2=QString::fromUtf8(ss1);
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";
</code>```

The output of the above code is "s1!=s2". In fact, the content of ss1 and s2 is a mess. But the output of the following code is "s1==s2". Why?

```<code>    QString s1="abc";
    QString s2=QString::fromUtf8(s1.toUtf8().constData());
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";
</code>```

答:
Because you have undefined behavior in your code:

```<code>const char * ss1 = s1.toUtf8().constData();
</code>```

The QByteArray returned by the toUtf8() function is a temporary object and is destroyed. But you are keeping a pointer to its data which you then try to use:

```<code>QString s2=QString::fromUtf8(ss1);
</code>```

This results in undefined behavior.

For this to work, you need to keep the temporary QByteArray object alive. You can use a const reference for that. It will extend the life of the temporary object:

```<code>QString s1 = "abc";
const auto& bytes = s1.toUtf8();
const char * ss1 = bytes.constData();
</code>```

Your second example is fine, because you are not using any pointers to internal memory of destroyed objects:

```<code>QString s2 = QString::fromUtf8(s1.toUtf8().constData());
</code>```

The temporary QByteArray object returned by toUtf8() is only destroyed after the call to fromUtf8() returns. So the constData() pointer is valid for long enough to allow the function to read the data.

Title: How to use QString toUtf8 and fromUtf8?

Body:
I have a weird problem:

    QString s1="abc";
    const char * ss1=s1.toUtf8().constData();
    QString s2=QString::fromUtf8(ss1);
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";

The output of the above code is "s1!=s2". In fact, the content of ss1 and s2 is a mess. But the output of the following code is "s1==s2". Why?

    QString s1="abc";
    QString s2=QString::fromUtf8(s1.toUtf8().constData());
    if(s1==s2)
      qDebug()<<"s1==s2";
    else
      qDebug()<<"s1!=s2";

Body:
Because you have undefined behavior in your code:

const char * ss1 = s1.toUtf8().constData();

The QByteArray returned by the toUtf8() function is a temporary object and is destroyed. But you are keeping a pointer to its data which you then try to use:

QString s2=QString::fromUtf8(ss1);

This results in undefined behavior.

For this to work, you need to keep the temporary QByteArray object alive. You can use a const reference for that. It will extend the life of the temporary object:

QString s1 = "abc";
const auto& bytes = s1.toUtf8();
const char * ss1 = bytes.constData();

Your second example is fine, because you are not using any pointers to internal memory of destroyed objects:

QString s2 = QString::fromUtf8(s1.toUtf8().constData());

The temporary QByteArray object returned by toUtf8() is only destroyed after the call to fromUtf8() returns. So the constData() pointer is valid for long enough to allow the function to read the data.


问:
how to write PHP module in C
how can i write my own module in C ?
is it possible ?</p>

答:
Yes, it is possible. Here's an old article that I used when I wrote my first extension:

http://web.archive.org/web/20110222035803/http://devzone.zend.com/article/1021

Things may have changed since then, so you may want to search for similar tutorials for additional references.

Oh, and this should be useful:

http://www.php.net/manual/en/internals2.php

ContentLicense: CC BY-SA 3.0

Title: how to write PHP module in C


问:
Why my getRequest() in saga doesn't see data from json.db after postRequest
My saga.ts :

```<code>export function* postSomething(object:object){
        yield postRequest(object);
        const Objects=yield getRequest();
        console.log(Objects);
        yield put(showObject(Objects));
}
</code>```

**db.json is my little database

My db.json is empty at the beginning, and after first postRequest(object), db.json will have one object,but when I try to get that object with getRequest I get [ ] (empty array)!?Why?

My console.log(Object) doesn't print anything.

Next time when I do postRequest(object) and post to my db.json one more object, that means db.json will have two objects, but after that, when I try to pull objects with getRequest(), my console.log print only one object?Why?

How to get all objects from db.json after postRequest() ?

postRequest(object)(post object to db.json using fetch,method "post") is service function which communicate with db.json,

getRequest()( fetch(url) which need to return all object from db.json )
.

答:
This is a generator function so every time it returns it restarts after the last yield statement so the second time through, it starts at line 3.

Redux saga has the call effect:

```<code>import {call, put} from 'redux-saga/effects';

export function* postSomething(object:object){
        yield call(postRequest, object);
        const Objects=yield call(getRequest());
        console.log(Objects);
        yield put(showObject(Objects));
}
</code>```

In your case, though, it seems like you should probably be using 2 chained sagas here.

Body:
My saga.ts :

export function* postSomething(object:object){
        yield postRequest(object);
        const Objects=yield getRequest();
        console.log(Objects);
        yield put(showObject(Objects));
}

**db.json is my little database

My db.json is empty at the beginning, and after first postRequest(object), db.json will have one object,but when I try to get that object with getRequest I get [ ] (empty array)!?Why?

My console.log(Object) doesn't print anything.

Next time when I do postRequest(object) and post to my db.json one more object, that means db.json will have two objects, but after that, when I try to pull objects with getRequest(), my console.log print only one object?Why?

How to get all objects from db.json after postRequest() ?

postRequest(object)(post object to db.json using fetch,method "post") is service function which communicate with db.json,

getRequest()( fetch(url) which need to return all object from db.json )
.

Body:
This is a generator function so every time it returns it restarts after the last yield statement so the second time through, it starts at line 3.

Redux saga has the call effect:

import {call, put} from 'redux-saga/effects';

export function* postSomething(object:object){
        yield call(postRequest, object);
        const Objects=yield call(getRequest());
        console.log(Objects);
        yield put(showObject(Objects));
}

In your case, though, it seems like you should probably be using 2 chained sagas here.


问:
How can I solve this datatype problem with only one function,best with pattern matching
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
</code>```

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

```<code>data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

</code>```

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

答:
Here's a simple solution, perhaps not efficient though. The general idea is to keep track of which tokens we've already parsed, which chars are to be added to the next Text token and what is left.

First we'll call a helper function named tokenize' (note the single quote at the end) which takes an additional param named partial that is a list of accumulated chars, which are partial Text-type Token.

When we encounter a '{' we scan the rest of the string to split on the first '}', create a Placeholder token and continue to process the rest of the string recursively. If we encounter any other char, we simply append it to partial.

Since it's a homework assignment, I've left the implementation of splitPlaceholder as an exercise.

```<code>tokenize :: String -> [Token]
tokenize str = tokenize' str  []

partialToText :: String -> [Token]
partialToText [] = []
partialToText xs = [Text xs]

tokenize' :: String -> String -> [Token]
tokenize' [] partial  = partialToText partial
tokenize' ('{':xs) partial  =
      let splitted = splitPlaceholder xs
          placeholderText = Placeholder (head splitted)
          rest = head $ tail splitted
          nextToken = partialToText partial
      in nextToken ++ (placeholderText : tokenize' rest [])
tokenize' (x:xs) partial = tokenize' xs (partial ++ [x])

    -- split input to two parts, first is everything till the first '}' (not including)
    -- and the second is the rest of the input string
    splitPlaceholder :: String -> [String]
    -- implementation left as an exercise
</code>```

Body:
I'm doing my Haskell Datentyp homework, and have try to solve this problem for a whole day.

The question is like this .

Use this Datentyp and only one function tokenize, other functions in the library are not permitted.

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]

The brace is the sign of Placeholder

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

I have tried for a whole day, only Text output or Placehold is OK, but I have several problems:

How to handle curly brackets {}

How to use pattern match to match "{longtext...}"

Because of Datentype [token],  tokenize (x: xs) = x :[ Text (xs:[])] do not works , so how to deal with it

how to combine the comma and all of them together, with only type [token] result function,I have tried ++ and : , but they all report error.

According to 4, there is a common question besides this homework: when using Datentype, and type of result doesn't fits type of input,  how to use recursion.

This is the last edition of my answer, it is still far away

data Token = Text String
           | Placeholder String
             deriving (Eq, Show)

tokenize :: String -> [Token]
tokenize [] = []
tokenize ('{':x:xs) = [ Placeholder (x:xs)]
tokenize (x: xs) = [ Text (x:xs)]
otherwise = error "TODO: Implementierung vervollstaendigen"

The result should like this:
when we give input"Hallo {name}, {xyz}."

should give [Text "Hallo ", Placeholder "name", Text ", ", Placeholder "xyz", Text "."] out

Suppose all the input without internal bracket and are correctly denoted by curly brackets{}

Body:
Here's a simple solution, perhaps not efficient though. The general idea is to keep track of which tokens we've already parsed, which chars are to be added to the next Text token and what is left.

First we'll call a helper function named tokenize' (note the single quote at the end) which takes an additional param named partial that is a list of accumulated chars, which are partial Text-type Token.

When we encounter a '{' we scan the rest of the string to split on the first '}', create a Placeholder token and continue to process the rest of the string recursively. If we encounter any other char, we simply append it to partial.

Since it's a homework assignment, I've left the implementation of splitPlaceholder as an exercise.

tokenize :: String -> [Token]
tokenize str = tokenize' str  []

partialToText :: String -> [Token]
partialToText [] = []
partialToText xs = [Text xs]

tokenize' :: String -> String -> [Token]
tokenize' [] partial  = partialToText partial
tokenize' ('{':xs) partial  =
      let splitted = splitPlaceholder xs
          placeholderText = Placeholder (head splitted)
          rest = head $ tail splitted
          nextToken = partialToText partial
      in nextToken ++ (placeholderText : tokenize' rest [])
tokenize' (x:xs) partial = tokenize' xs (partial ++ [x])

    -- split input to two parts, first is everything till the first '}' (not including)
    -- and the second is the rest of the input string
    splitPlaceholder :: String -> [String]
    -- implementation left as an exercise


问:
Unit test a non returnable function which randomly generates numbers
Am new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another,  I read about the mocking library but it's still confusing to me, how can I unit test this function.

What I want to test

Testing if numbers are generated between 1000 and 8876.

Checking the positions of different numbers with a 4 -digit values are not equal to each other. e.g 1234, this number is allowed because it has no repetitions. but 1123 is not allowed because it has a number repeated in different positions. That's what the while loop is doing.

I tried to read similar questions e.g link 1  link 2 but I couldn't connect to this scenario

```<code>def num(self):

                    random = randint(1000, 8876)

                    random = list(map(int, str(random)))

                    while random[0] == random[1] or random[0] == random[2] or random[0] == random[3] or random[1] == random[2] or random[1] == random[3] or random[2] == random[3]:

                            random = randint(1000, 8876)

                            random = list(map(int, str(random)))

                    num = ""

                    self.num = int(num.join(map(str,random)))
</code>```

答:
First of all, if you post code, please only post complete and executable code. In your case, self.num is defined twice, once as variable and once as function. Also, there is no class body around the function.

It is important to post complete code, because the surrounding structure could be of importance for the answer. In your case, I just have to assume how the containing class looks like, therefore the answer might not be applicable to your problem.

This is how I would write a unit test for your specific problem:

from random import randint
import unittest

class RandomGen:
    def __init__(self):
        self.num = None

    def compute_num(self):
        random = randint(1000, 8876)
        random = list(map(int, str(random)))
        while random[0] == random[1] or random[0] == random[2] or \
              random[0] == random[3] or random[1] == random[2] or \
              random[1] == random[3] or random[2] == random[3]:
            random = randint(1000, 8876)
            random = list(map(int, str(random)))
        num = ""
        self.num = int(num.join(map(str,random)))

class RandomGenTest(unittest.TestCase):

    # It's hard to test random number generators deterministically.
    # Therefore, just repeat it a bunch of times to increase the chance for
    # incorrect results to show up. In this case, 10000 times.

    def test_range(self):
        gen = RandomGen()
        for i in range(10000):
            gen.compute_num()
            self.assertGreaterEqual(gen.num, 1000)
            self.assertLessEqual(gen.num, 8876)

    def test_duplicates(self):
        gen = RandomGen()
        for i in range(10000):
            gen.compute_num()
            numbers = list(map(int, str(gen.num)))
            self.assertEqual(len(numbers), len(set(numbers)))

if __name__ == '__main__':
    unittest.main()
```

Body:
Am new in unit testing, I have a function which doesn't return anything and generates numbers randomly from a certain number to another,  I read about the mocking library but it's still confusing to me, how can I unit test this function.

What I want to test

Testing if numbers are generated between 1000 and 8876.

Checking the positions of different numbers with a 4 -digit values are not equal to each other. e.g 1234, this number is allowed because it has no repetitions. but 1123 is not allowed because it has a number repeated in different positions. That's what the while loop is doing.

I tried to read similar questions e.g link 1  link 2 but I couldn't connect to this scenario

def num(self):

                    random = randint(1000, 8876)

                    random = list(map(int, str(random)))

                    while random[0] == random[1] or random[0] == random[2] or random[0] == random[3] or random[1] == random[2] or random[1] == random[3] or random[2] == random[3]:

                            random = randint(1000, 8876)

                            random = list(map(int, str(random)))

                    num = ""

                    self.num = int(num.join(map(str,random)))


问:
Mongodb group and push with empty arrays
I'm having a problem with a group when there is an array that could be empty.
The collection could be like this:

```<code>{
    "_id" : "Contract_1",
    "ContactId" : "Contact_1",
    "Specifications" : [ ]
}

{
    "_id" : "Contract_2",
    "ContactId" : "Contact_2",
    "Specifications" : [
        {
            "Description" : "Descrizione1",
            "VehicleId" : "Vehicle_1",
            "Customizations" : [
                {
                    "Description" : "Random furniture",
                    "ContactId" : "Contact_5"
                },
                {
                    "Description" : "Random furniture 2",
                    "ContactId" : "Contact_3"
                }
            ]
        },
        {
            "Description" : "Descrizione2",
            "VehicleId" : "Vehicle_2",
            "Customizations" : [
                {
                    "Description" : "Random furniture",
                    "ContactId" : "Contact_5"
                },
                {
                    "Description" : "Random furniture 2",
                    "ContactId" : "Contact_3"
                }
            ]
        }
    ]
}

{
    "_id" : "Contract_3",
    "ContactId" : "Contact_25",
    "Specifications" : [
        {
            "Description" : "Descrizione1",
            "VehicleId" : "Vehicle_1",
            "Customizations" : []
        },
        {
            "Description" : "Descrizione2",
            "VehicleId" : "Vehicle_2",
            "Customizations" : []
        }
    ]
}
</code>```

As you can see, sometimes Specifications can be null, and also Customizations.
And this is the query that I execute:

```<code>db.getCollection("Contract").aggregate([
  { "$lookup": {
    "from": "Contact",
    "localField": "ContactId",
    "foreignField": "_id",
    "as": "Contact"
  }},
  { "$unwind": {"path":"$Contact", "preserveNullAndEmptyArrays":true }},
  { "$unwind": { "path": "$Specifications", "preserveNullAndEmptyArrays":true }},
  { "$lookup": {
    "from": "Vehicle",
    "localField": "Specifications.VehicleId",
    "foreignField": "_id",
    "as": "Specifications.Vehicle"
  }},
  { "$unwind": {"path": {"$Specifications.Vehicle","preserveNullAndEmptyArrays":true} },
  { "$unwind": {"path": {"$Specifications.Customizations","preserveNullAndEmptyArrays":true} },
  { "$lookup": {
    "from": "Contact",
    "localField": "Specifications.Customizations.ContactId",
    "foreignField": "_id",
    "as": "Specifications.Customizations.Contact"
  }},
  { "$unwind": {"path": {"$Specifications.Customizations.Contact","preserveNullAndEmptyArrays":true} },
  { "$group": {
    "_id": {
      "_id": "$_id",
      "Description": "$Specifications.Description"
    },
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": "$Specifications.Customizations"
    }
  }},
  { "$group": {
    "_id": "$_id._id",
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": {
        "Description": "$_id.Description",
        "Customizations": "$Specifications"
      }
    }
  }}
])
}},
   { "$group": {
    "_id": "$_id._id",
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": {
        "Description": "$_id.Description",
        "Customizations": "$Specifications"
      }
    }
  }}
])
</code>```

Once the query execute, when it's doing the 2 $group it creates a problem, since for the first one when pushing $Specifications.Customizations will create an array with an empty element inside. What I want is that If Specifications is an empty array, will stay so without adding an empty element inside.

答:
This is I can see one of the drawback of the $unwind and $group for the nested arrays. To get rid from this you need to add one more stage $addFields to filter out the empty nested arrays.

Add this at the end of the pipeline

```<code>{ "$addFields": {
  "Specifications": {
    "$filter": {
      "input": "$Specifications",
      "cond": { "$ne": ["$$this.Description", undefined] }
    }
  }
}}
</code>```

Body:
I'm having a problem with a group when there is an array that could be empty.
The collection could be like this:

{
    "_id" : "Contract_1",
    "ContactId" : "Contact_1",
    "Specifications" : [ ]
}

{
    "_id" : "Contract_2",
    "ContactId" : "Contact_2",
    "Specifications" : [
        {
            "Description" : "Descrizione1",
            "VehicleId" : "Vehicle_1",
            "Customizations" : [
                {
                    "Description" : "Random furniture",
                    "ContactId" : "Contact_5"
                },
                {
                    "Description" : "Random furniture 2",
                    "ContactId" : "Contact_3"
                }
            ]
        },
        {
            "Description" : "Descrizione2",
            "VehicleId" : "Vehicle_2",
            "Customizations" : [
                {
                    "Description" : "Random furniture",
                    "ContactId" : "Contact_5"
                },
                {
                    "Description" : "Random furniture 2",
                    "ContactId" : "Contact_3"
                }
            ]
        }
    ]
}

{
    "_id" : "Contract_3",
    "ContactId" : "Contact_25",
    "Specifications" : [
        {
            "Description" : "Descrizione1",
            "VehicleId" : "Vehicle_1",
            "Customizations" : []
        },
        {
            "Description" : "Descrizione2",
            "VehicleId" : "Vehicle_2",
            "Customizations" : []
        }
    ]
}

As you can see, sometimes Specifications can be null, and also Customizations.
And this is the query that I execute:

db.getCollection("Contract").aggregate([
  { "$lookup": {
    "from": "Contact",
    "localField": "ContactId",
    "foreignField": "_id",
    "as": "Contact"
  }},
  { "$unwind": {"path":"$Contact", "preserveNullAndEmptyArrays":true }},
  { "$unwind": { "path": "$Specifications", "preserveNullAndEmptyArrays":true }},
  { "$lookup": {
    "from": "Vehicle",
    "localField": "Specifications.VehicleId",
    "foreignField": "_id",
    "as": "Specifications.Vehicle"
  }},
  { "$unwind": {"path": {"$Specifications.Vehicle","preserveNullAndEmptyArrays":true} },
  { "$unwind": {"path": {"$Specifications.Customizations","preserveNullAndEmptyArrays":true} },
  { "$lookup": {
    "from": "Contact",
    "localField": "Specifications.Customizations.ContactId",
    "foreignField": "_id",
    "as": "Specifications.Customizations.Contact"
  }},
  { "$unwind": {"path": {"$Specifications.Customizations.Contact","preserveNullAndEmptyArrays":true} },
  { "$group": {
    "_id": {
      "_id": "$_id",
      "Description": "$Specifications.Description"
    },
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": "$Specifications.Customizations"
    }
  }},
  { "$group": {
    "_id": "$_id._id",
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": {
        "Description": "$_id.Description",
        "Customizations": "$Specifications"
      }
    }
  }}
])
}},
   { "$group": {
    "_id": "$_id._id",
    "ContactId": { "$first": "$ContactId" },
    "Contact": { "$first": "$Contact" },
    "Specifications": {
      "$push": {
        "Description": "$_id.Description",
        "Customizations": "$Specifications"
      }
    }
  }}
])

Once the query execute, when it's doing the 2 $group it creates a problem, since for the first one when pushing $Specifications.Customizations will create an array with an empty element inside. What I want is that If Specifications is an empty array, will stay so without adding an empty element inside.

Body:
This is I can see one of the drawback of the $unwind and $group for the nested arrays. To get rid from this you need to add one more stage $addFields to filter out the empty nested arrays.

Add this at the end of the pipeline

{ "$addFields": {
  "Specifications": {
    "$filter": {
      "input": "$Specifications",
      "cond": { "$ne": ["$$this.Description", undefined] }
    }
  }
}}


问:
If column A's value is within the range of Column B and C then copy
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

```<code>             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo
</code>```

答:
Just do an if in each of the columns G and H.

In G1:

```<code>=IF(AND(A1<=C1,A1>=B1),D1,"")
</code>```

And in H1:

```<code>=IF(AND(A1<=C1,A1>=B1),E1,"")
</code>```

Or in H1 simply check if there is a value in G1 as:

```<code>=IF(G1<>"",E1,"")
</code>```

Body:
in this project i have to check column's A value between Column B and Column C. If  columnA's values>= Columns B value or Columns A value<= Columns C value then i need to copy column d and e values and need to put into sheet1 column G and H. Column A is in sheet1 and Column B, C, D and E in sheet2.

I am sorry with my wordings i know its difficult to understand. If someone can help me with this i would be forever grateful. Thank you

             A       B    c   D     E
             1       1    9   Dog   Naruto
             11      10   19  Cat   one piece
             21      20   30  Duck  lo

          i want the outcome like this
           A    G       H
           1    Dog     Naruto
           11   cat     One piece
           21    duck     lo

Body:
Just do an if in each of the columns G and H.

In G1:

=IF(AND(A1<=C1,A1>=B1),D1,"")

And in H1:

=IF(AND(A1<=C1,A1>=B1),E1,"")

Or in H1 simply check if there is a value in G1 as:

=IF(G1<>"",E1,"")


问:
A program that's supposed to find out whether a number is prime or not isn't working as expected
I'm trying to make a program which will find if a number is prime or not with a very simple formula: divide the number(x) by 4. see if any number from 1 to x/4 divides perfectly by x. If not, x will be prime.

The program currently shows me the result from dividing x by every number from 1 to x/4. I want to do this: If there's a number that divides perfectly, print that x is not prime and end the program. Or if there's no numbers that divide by x, just say that x is prime and end the program.

I tried using booleans but then it showed every number as prime, which it should not do since the program doesn't know yet that x can be perfectly divided by 1 but will still be prime.

```<code>value = int(input("Type a number: "))

# prime = True

if value.__class__ == int:
    x = value / 4
    list = list(range(1, int(x) + 1))
    for number in list:
        y = value / number

        while y >= 0:
            y -= 1
            if y == 0:
                print(f"{value} is not prime")
                # print("yes")
                # y == -1
            elif 0 < y < 1:
                print(f"{value} is prime")
                # print("no")
    # if prime:
    #     print(f"{value} is prime")
    # else:
    #     print(f"{value} is not prime")
</code>```

答:
first of all where did you find this formula?

second you didn't implement what you said in your code.
you need to check all four kinds that are possible after dividing and choose the result according to all of them, not in any loop.

Body:
I'm trying to make a program which will find if a number is prime or not with a very simple formula: divide the number(x) by 4. see if any number from 1 to x/4 divides perfectly by x. If not, x will be prime.

The program currently shows me the result from dividing x by every number from 1 to x/4. I want to do this: If there's a number that divides perfectly, print that x is not prime and end the program. Or if there's no numbers that divide by x, just say that x is prime and end the program.

I tried using booleans but then it showed every number as prime, which it should not do since the program doesn't know yet that x can be perfectly divided by 1 but will still be prime.

value = int(input("Type a number: "))

# prime = True

if value.__class__ == int:
    x = value / 4
    list = list(range(1, int(x) + 1))
    for number in list:
        y = value / number

        while y >= 0:
            y -= 1
            if y == 0:
                print(f"{value} is not prime")
                # print("yes")
                # y == -1
            elif 0 < y < 1:
                print(f"{value} is prime")
                # print("no")
    # if prime:
    #     print(f"{value} is prime")
    # else:
    #     print(f"{value} is not prime")


问:
Catch the Error message text in a rxjs subscribe method in Angular
I have a nodeJS express server application in TypeScript. When an error occurs I want to add some text to it and read it in the client Angular application.

NodeJS Server, express  code:

```<code>import {
  Request,
  Response
} from 'express';

if (medewerker) {
  verifyPassword(medewerker.id, req.body.wachtwoord).then(isVerifiedPassword => {

    if (isVerifiedPassword) {

      .......

    } else {
      throw new Error('Wachtwoord niet juist ingevoerd');
    }

  }).catch(error => {
    console.log(error);
    res.status(401).json('I want to show this text: ' + error);
  })
}
</code>```

Client code:

```<code>this.httpClient.put(this.url + 'medewerker/login', {
    'email': authData.userId,
    'wachtwoord': authData.password
  }, {
    headers: this.headertjes,
    withCredentials: true,
    observe: 'response',
    responseType: 'json'
  })
  .subscribe((data1: HttpResponse < MedewerkerTypeId > ) => {

    if (data1 != null) {
      .....
    }

  }, ((error: HttpErrorResponse) => {
    console.log(error.statusText) //here I want to grep and show my text.
  }));
</code>```

But I get an error: undefined message.
I tried all the options but only default properties like  error.status and error.message works. But no Custom messages like I want.

Maybe somebody can help me ?

答:
The body of the ErrorResponse can be accessed  using the error property.

Change your code like this:

```<code>this.httpClient.put(this.url + 'medewerker/login', {
    'email': authData.userId,
    'wachtwoord': authData.password
  }, {
    headers: this.headertjes,
    withCredentials: true,
    observe: 'response',
    responseType: 'json'
  })
  .subscribe((data1: HttpResponse < MedewerkerTypeId > ) => {

    if (data1 != null) {
      .....
    }

  }, ((error: HttpErrorResponse) => {
    console.log(error.error) //here error contains the text
  }));
</code>```

Body:
I have a nodeJS express server application in TypeScript. When an error occurs I want to add some text to it and read it in the client Angular application.

NodeJS Server, express  code:

import {
  Request,
  Response
} from 'express';

if (medewerker) {
  verifyPassword(medewerker.id, req.body.wachtwoord).then(isVerifiedPassword => {

    if (isVerifiedPassword) {

      .......

    } else {
      throw new Error('Wachtwoord niet juist ingevoerd');
    }

  }).catch(error => {
    console.log(error);
    res.status(401).json('I want to show this text: ' + error);
  })
}

Client code:

this.httpClient.put(this.url + 'medewerker/login', {
    'email': authData.userId,
    'wachtwoord': authData.password
  }, {
    headers: this.headertjes,
    withCredentials: true,
    observe: 'response',
    responseType: 'json'
  })
  .subscribe((data1: HttpResponse < MedewerkerTypeId > ) => {

    if (data1 != null) {
      .....
    }

  }, ((error: HttpErrorResponse) => {
    console.log(error.statusText) //here I want to grep and show my text.
  }));

But I get an error: undefined message.
I tried all the options but only default properties like  error.status and error.message works. But no Custom messages like I want.

Maybe somebody can help me ?

Body:
The body of the ErrorResponse can be accessed  using the error property.

Change your code like this:

this.httpClient.put(this.url + 'medewerker/login', {
    'email': authData.userId,
    'wachtwoord': authData.password
  }, {
    headers: this.headertjes,
    withCredentials: true,
    observe: 'response',
    responseType: 'json'
  })
  .subscribe((data1: HttpResponse < MedewerkerTypeId > ) => {

    if (data1 != null) {
      .....
    }

  }, ((error: HttpErrorResponse) => {
    console.log(error.error) //here error contains the text
  }));


问:
How to fix undefined is not a function listing the state in the render
I have problem regarding listing all the details of the users, I don't understand why the error shows that my mapping is undefined is not a function. I create a function which inside the function are the list of users so after i list the users, then I put it on the render, however the mapping shows that  undefined function..

I will show you guys the sample code that I already made:

Constructor:

```<code>  constructor(props) {
    super(props);
    this.state = {
      driver_id:'',
      driver_history_list:[]
    }

    this.renderCardHistoryList = this.renderCardHistoryList.bind(this);
  }
</code>```

Mount:

```<code>async componentDidMount() {
  NavigationBar.setColor('white')
  NavigationBar.setStatusBarColor('#008E9B',true)
  NavigationBar.setStatusBarTheme('white',true)
  const ids_driver =  await AsyncStorage.getItem('IDS');
  axios.get('http://192.168.100.111:8001/api/driver_history/'+ids_driver)
  .then((response) => {
    this.setState({
      driver_history_list:response
   })
  }).catch(function(error) {
    alert(JSON.stringify(error));
  })
}
</code>```

Function:

```<code>renderCardHistoryList() {

      const history_list = Array.isArray(this.state.driver_history_list) && this.state.driver_history_list || [];

      return history_list.map(driver_info => {
        return (
          <Card>
            <CardItem header button onPress={() => alert("This is Card Header")}>
              <Left style={{flex:1}}>

              </Left>
              <Right>
                <Text style={{fontSize:15}}>12 May 2019, 08:46pm</Text>
              </Right>
            </CardItem>
            <CardItem button onPress={() => alert("This is Card Body")}>
              <Body style={{bottom:'6%',position:'relative'}}>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                  <Icon type="MaterialCommunityIcons" name='store' style={{fontSize:20,color:'#0a60ff'}}/>
                  <Text style={{marginLeft:'5%',fontSize:14}}>Store 1790</Text>
                </View>

                <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
                  <Icon type="MaterialCommunityIcons" name='map-marker-radius' style={{fontSize:20,color: "#f92223"}} />
                  <Text style={{marginLeft:'5%',fontSize:14}}></Text>
                </View>

                <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
                  <Icon type="Ionicons" name='ios-checkmark-circle' style={{fontSize:20,color: "#FF9501"}} />
                  <Text style={{marginLeft:'5%',fontSize:14}}></Text>
                </View>
              </Body>
            </CardItem>
          </Card>
        )
      })
    }
</code>```

Render:

```<code>render() {
    return (
      <Container>
        <Header style={{backgroundColor:'#008E9B'}}>
          <Left style={{flex:1}}>
              <Button transparent>
                  <Icon name='arrow-back' />
              </Button>
          </Left>
          <Body style={{ flex: 1,  justifyContent: 'center', alignItems: 'center' }}>
              <Title>History</Title>
          </Body>
          <Right style={{flex: 1}} />
        </Header>
        <Content padder>
          {this.renderCardHistoryList()}
        </Content>
      </Container>
    )
}
</code>```

Result:

答:
Validate your array. const history_list= this.state.driver_history_list || [];

```<code>renderCardHistoryList() {

  const history_list = Array.isArray(this.state.driver_history_list) && this.state.driver_history_list || [];

  return history_list.map(driver_info => {
    return (
      <Card>
        <CardItem header button onPress={() => alert("This is Card Header")}>
          <Left style={{flex:1}}>

          </Left>
          <Right>
            <Text style={{fontSize:15}}>12 May 2019, 08:46pm</Text>
          </Right>
        </CardItem>
        <CardItem button onPress={() => alert("This is Card Body")}>
          <Body style={{bottom:'6%',position:'relative'}}>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              <Icon type="MaterialCommunityIcons" name='store' style={{fontSize:20,color:'#0a60ff'}}/>
              <Text style={{marginLeft:'5%',fontSize:14}}>Store 1790</Text>
            </View>

            <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
              <Icon type="MaterialCommunityIcons" name='map-marker-radius' style={{fontSize:20,color: "#f92223"}} />
              <Text style={{marginLeft:'5%',fontSize:14}}></Text>
            </View>

            <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
              <Icon type="Ionicons" name='ios-checkmark-circle' style={{fontSize:20,color: "#FF9501"}} />
              <Text style={{marginLeft:'5%',fontSize:14}}></Text>
            </View>
          </Body>
        </CardItem>
      </Card>
    )
  })
}
</code>```

EDIT

you are setting the whole response to driver_history_list, which is an object change it to.

```<code>driver_history_list: response.data
</code>```

NOTE

Always validate your data. Don't assume that you'll always get the right data. When working with objects always validate them, as doing data.name, can break your app, if data is null or undefined. for example, given the following object.

```<code>const animal = {};
</code>```

doing

```<code>// throws an error, Cannot read property 'toLowerCase' of undefined
console.log(animal.name.toLowerCase())
</code>```

to prevent that from happening, we need to check if the propery exists, like the following.

```<code>// checks if the name property exists console name, else assign a console log 'Lion'
console.log(animal.name && animal.name.toLowerCase() || 'Lion')
</code>```

Body:
I have problem regarding listing all the details of the users, I don't understand why the error shows that my mapping is undefined is not a function. I create a function which inside the function are the list of users so after i list the users, then I put it on the render, however the mapping shows that  undefined function..

I will show you guys the sample code that I already made:

Constructor:

  constructor(props) {
    super(props);
    this.state = {
      driver_id:'',
      driver_history_list:[]
    }

    this.renderCardHistoryList = this.renderCardHistoryList.bind(this);
  }

Mount:

async componentDidMount() {
  NavigationBar.setColor('white')
  NavigationBar.setStatusBarColor('#008E9B',true)
  NavigationBar.setStatusBarTheme('white',true)
  const ids_driver =  await AsyncStorage.getItem('IDS');
  axios.get('http://192.168.100.111:8001/api/driver_history/'+ids_driver)
  .then((response) => {
    this.setState({
      driver_history_list:response
   })
  }).catch(function(error) {
    alert(JSON.stringify(error));
  })
}

Function:

renderCardHistoryList() {

      const history_list = Array.isArray(this.state.driver_history_list) && this.state.driver_history_list || [];

      return history_list.map(driver_info => {
        return (
          <Card>
            <CardItem header button onPress={() => alert("This is Card Header")}>
              <Left style={{flex:1}}>

              </Left>
              <Right>
                <Text style={{fontSize:15}}>12 May 2019, 08:46pm</Text>
              </Right>
            </CardItem>
            <CardItem button onPress={() => alert("This is Card Body")}>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
                  <Icon type="MaterialCommunityIcons" name='store' style={{fontSize:20,color:'#0a60ff'}}/>
                  <Text style={{marginLeft:'5%',fontSize:14}}>Store 1790</Text>
                </View>

                <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
                  <Icon type="MaterialCommunityIcons" name='map-marker-radius' style={{fontSize:20,color: "#f92223"}} />
                  <Text style={{marginLeft:'5%',fontSize:14}}></Text>
                </View>

                <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

                <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
                  <Icon type="Ionicons" name='ios-checkmark-circle' style={{fontSize:20,color: "#FF9501"}} />
                  <Text style={{marginLeft:'5%',fontSize:14}}></Text>
                </View>

            </CardItem>
          </Card>
        )
      })
    }

Render:

render() {
    return (
      <Container>

          <Left style={{flex:1}}>
              <Button transparent>
                  <Icon name='arrow-back' />
              </Button>
          </Left>

              <Title>History</Title>

          <Right style={{flex: 1}} />

        <Content padder>
          {this.renderCardHistoryList()}
        </Content>
      </Container>
    )
}

Result:

Body:
Validate your array. const history_list= this.state.driver_history_list || [];

renderCardHistoryList() {

  const history_list = Array.isArray(this.state.driver_history_list) && this.state.driver_history_list || [];

  return history_list.map(driver_info => {
    return (
      <Card>
        <CardItem header button onPress={() => alert("This is Card Header")}>
          <Left style={{flex:1}}>

          </Left>
          <Right>
            <Text style={{fontSize:15}}>12 May 2019, 08:46pm</Text>
          </Right>
        </CardItem>
        <CardItem button onPress={() => alert("This is Card Body")}>
          <Body style={{bottom:'6%',position:'relative'}}>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center' }}>
              <Icon type="MaterialCommunityIcons" name='store' style={{fontSize:20,color:'#0a60ff'}}/>
              <Text style={{marginLeft:'5%',fontSize:14}}>Store 1790</Text>
            </View>

            <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
              <Icon type="MaterialCommunityIcons" name='map-marker-radius' style={{fontSize:20,color: "#f92223"}} />
              <Text style={{marginLeft:'5%',fontSize:14}}></Text>
            </View>

            <Icon type="Entypo" name='dots-two-vertical' style={{fontSize:12,marginLeft:'1%',color:'grey',marginTop:'1%'}}/>

            <View style={{ flex: 1, flexDirection: 'row', alignItems: 'center',marginTop:'1%' }}>
              <Icon type="Ionicons" name='ios-checkmark-circle' style={{fontSize:20,color: "#FF9501"}} />
              <Text style={{marginLeft:'5%',fontSize:14}}></Text>
            </View>
          </Body>
        </CardItem>
      </Card>
    )
  })
}

EDIT

you are setting the whole response to driver_history_list, which is an object change it to.

driver_history_list: response.data

NOTE

Always validate your data. Don't assume that you'll always get the right data. When working with objects always validate them, as doing data.name, can break your app, if data is null or undefined. for example, given the following object.

const animal = {};

doing

// throws an error, Cannot read property 'toLowerCase' of undefined
console.log(animal.name.toLowerCase())

to prevent that from happening, we need to check if the propery exists, like the following.

// checks if the name property exists console name, else assign a console log 'Lion'
console.log(animal.name && animal.name.toLowerCase() || 'Lion')


问:
ViewPager2 default position
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

```<code>viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)
</code>```

答:
setCurrentItem(int item, boolean smoothScroll) works correctly in ViewPager but in ViewPager2 it does not work as expected. Finally, I faced this problem by adding setCurrentItem(int item, boolean smoothScroll) method into a delay like this:

```<code>Handler().postDelayed({
     view.viewPager.setCurrentItem(startPosition, false)
}, 100)
</code>```

Title: ViewPager2 default position

Body:
I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll) method but it doesn't work and nothing happens. How can I achieve it?

viewPager.adapter = adapter
viewPager.setCurrentItem(1, true)

Body:
setCurrentItem(int item, boolean smoothScroll) works correctly in ViewPager but in ViewPager2 it does not work as expected. Finally, I faced this problem by adding setCurrentItem(int item, boolean smoothScroll) method into a delay like this:

Handler().postDelayed({
     view.viewPager.setCurrentItem(startPosition, false)
}, 100)


问:
Why does using uniform initializer syntax result in different behavior to the "old" style ()?
I get different results if I try to use a uniform initializer for std::set.

Example:

```<code>int main()
{
    std::array a {1,2,3,4};
    std::set<int> s1 {a.begin(), a.end()};
    std::set      s2 {a.begin(), a.end()};
    std::set      s3 (a.begin(), a.end());

    for(auto& i: s1) { std::cout << i << "\n"; }
    std::cout << "####" << std::endl;
    for(auto& i: s2) { std::cout << i << "\n"; }
    std::cout << "####" << std::endl;
    for(auto& i: s3) { std::cout << i << "\n"; }
}
</code>```

Results in:

```<code>1
2
3
4
####
0x7ffecf9d12e0
0x7ffecf9d12f0
####
1
2
3
4
</code>```

This seems to be related to "deduction guides", which are evaluated differently if used with {} or () syntax.

答:
Short answer

For s2, brace syntax is used, and {a.begin(), a.end()} is considered to be an initializer_list of std::array<int>::iterators. Therefore, s2 is a set of iterators.

For s3, parentheses syntax is used, and the iterator constructor is selected. s3 is a set of ints, and is initialized from the range [a.begin(), a.end()).

Long answer

Per [set.overview], we have two deduction guides relevant here:

```<code>template<class InputIterator,
         class Compare = less<typename iterator_traits<InputIterator>::value_type>,
         class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
  set(InputIterator, InputIterator,
      Compare = Compare(), Allocator = Allocator())
    -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;
</code>```

and

```<code>template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;
</code>```

Per [over.match.class.deduct]/1:

A set of functions and function templates is formed comprising:

[...]

(1.4) For each deduction-guide, a function or function template with the following properties:

The template parameters, if any, and function parameters are those of the deduction-guide.

The return type is the simple-template-id of the deduction-guide.

In this case, the synthesized functions and function templates for the aforementioned deduction guides are, respectively,

```<code>template<class InputIterator,
         class Compare = less<typename iterator_traits<InputIterator>::value_type>,
         class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
auto __func1(InputIterator, InputIterator,
            Compare = Compare(), Allocator = Allocator())
  -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;
</code>```

and

```<code>template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
auto __func2(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
  -> set<Key, Compare, Allocator>;
</code>```

(I used double underscores to signify that these names are synthesized, and are not otherwise accessible.)

Per [over.match.class.deduct]/2:

Initialization and overload resolution are performed as described in
  [dcl.init] and [over.match.ctor], [over.match.copy], or
  [over.match.list] (as appropriate for the type of initialization
  performed) for an object of a hypothetical class type, where the
  selected functions and function templates are considered to be the
  constructors of that class type for the purpose of forming an overload
  set, and the initializer is provided by the context in which class
  template argument deduction was performed. Each such notional
  constructor is considered to be explicit if the function or function
  template was generated from a constructor or deduction-guide that
  was declared explicit. All such notional constructors are considered
  to be public members of the hypothetical class type.

The hypothetical class type looks like:

```<code>class __hypothetical {
public:
  // ...

  // #1
  template<class InputIterator,
           class Compare = less<typename iterator_traits<InputIterator>::value_type>,
           class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
  __hypothetical(InputIterator, InputIterator,
                 Compare = Compare(), Allocator = Allocator())
    -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;

  // #2
  template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  __hypothetical(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;

  // ...
};
</code>```

For the declaration of s2,

```<code>std::set s2 {a.begin(), a.end()};
</code>```

The overload resolution is performed as if in

```<code>__hypothetical __hyp{a.begin(), a.end()}; // braces
</code>```

Thus, [over.match.list] comes in.

[...] overload resolution selects the constructor in two phases:

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list
  consists of the initializer list as a single argument.

[...]

Constructor #2 is an initializer-list constructor. Function template argument deduction gives

```<code>Key = std::array<int>::iterator
</code>```

So the deduced type of s2 is

```<code>std::set<std::array<int>::iterator>
</code>```

The declaration of s2 is equivalent to

```<code>std::set<std::array<int>::iterator> s2 {a.begin(), a.end()};
</code>```

Therefore, s2 is a set of iterators that consists of two elements: a.begin() and a.end(). In your case, std::array<int>::iterator is probably int*, and a.begin() and a.end() happen to be serialized as 0x7ffecf9d12e0 and 0x7ffecf9d12f0, respectively.

For s3, overload resolution is performed as if in

```<code>template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;
</code>```0

That's direct-initialization, and is under the scope of [pver.match.ctor]. The initializer_list constructor is irrelevant, and the Constructor #1 is selected instead. Function template argument deduction gives

```<code>template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;
</code>```1

So the deduced type of s3 is

```<code>template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;
</code>```2

Which is set<int>. Therefore, the declaration of s3 is equivalent to

```<code>std::set<int> s3 (a.begin(), a.end());
</code>```

s3 is a set of ints that is initialized from the range [a.begin(), a.end()) — four elements 1, 2, 3, 4, which explains the output.

Body:
I get different results if I try to use a uniform initializer for std::set.

Example:

int main()
{
    std::array a {1,2,3,4};
    std::set<int> s1 {a.begin(), a.end()};
    std::set      s2 {a.begin(), a.end()};
    std::set      s3 (a.begin(), a.end());

    for(auto& i: s1) { std::cout << i << "\n"; }
    std::cout << "####" << std::endl;
    for(auto& i: s2) { std::cout << i << "\n"; }
    std::cout << "####" << std::endl;
    for(auto& i: s3) { std::cout << i << "\n"; }
}

Results in:

1
2
3
4
####
0x7ffecf9d12e0
0x7ffecf9d12f0
####
1
2
3
4

This seems to be related to "deduction guides", which are evaluated differently if used with {} or () syntax.

Body:
Short answer

For s2, brace syntax is used, and {a.begin(), a.end()} is considered to be an initializer_list of std::array<int>::iterators. Therefore, s2 is a set of iterators.

For s3, parentheses syntax is used, and the iterator constructor is selected. s3 is a set of ints, and is initialized from the range [a.begin(), a.end()).

Long answer

Per [set.overview], we have two deduction guides relevant here:

template<class InputIterator,
         class Compare = less<typename iterator_traits<InputIterator>::value_type>,
         class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
  set(InputIterator, InputIterator,
      Compare = Compare(), Allocator = Allocator())
    -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;

and

template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  set(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;

Per [over.match.class.deduct]/1:

A set of functions and function templates is formed comprising:

[...]

(1.4) For each deduction-guide, a function or function template with the following properties:

The template parameters, if any, and function parameters are those of the deduction-guide.

The return type is the simple-template-id of the deduction-guide.

In this case, the synthesized functions and function templates for the aforementioned deduction guides are, respectively,

template<class InputIterator,
         class Compare = less<typename iterator_traits<InputIterator>::value_type>,
         class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
auto __func1(InputIterator, InputIterator,
            Compare = Compare(), Allocator = Allocator())
  -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;

and

template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
auto __func2(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
  -> set<Key, Compare, Allocator>;

(I used double underscores to signify that these names are synthesized, and are not otherwise accessible.)

Per [over.match.class.deduct]/2:

Initialization and overload resolution are performed as described in
  [dcl.init] and [over.match.ctor], [over.match.copy], or
  [over.match.list] (as appropriate for the type of initialization
  performed) for an object of a hypothetical class type, where the
  selected functions and function templates are considered to be the
  constructors of that class type for the purpose of forming an overload
  set, and the initializer is provided by the context in which class
  template argument deduction was performed. Each such notional
  constructor is considered to be explicit if the function or function
  template was generated from a constructor or deduction-guide that
  was declared explicit. All such notional constructors are considered
  to be public members of the hypothetical class type.

The hypothetical class type looks like:

class __hypothetical {
public:
  // ...

  // #1
  template<class InputIterator,
           class Compare = less<typename iterator_traits<InputIterator>::value_type>,
           class Allocator = allocator<typename iterator_traits<InputIterator>::value_type>>
  __hypothetical(InputIterator, InputIterator,
                 Compare = Compare(), Allocator = Allocator())
    -> set<typename iterator_traits<InputIterator>::value_type, Compare, Allocator>;

  // #2
  template<class Key, class Compare = less<Key>, class Allocator = allocator<Key>>
  __hypothetical(initializer_list<Key>, Compare = Compare(), Allocator = Allocator())
    -> set<Key, Compare, Allocator>;

  // ...
};

For the declaration of s2,

std::set s2 {a.begin(), a.end()};

The overload resolution is performed as if in

__hypothetical __hyp{a.begin(), a.end()}; // braces

Thus, [over.match.list] comes in.

[...] overload resolution selects the constructor in two phases:

Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list
  consists of the initializer list as a single argument.

[...]

Constructor #2 is an initializer-list constructor. Function template argument deduction gives

Key = std::array<int>::iterator

So the deduced type of s2 is

std::set<std::array<int>::iterator>

The declaration of s2 is equivalent to

std::set<std::array<int>::iterator> s2 {a.begin(), a.end()};

Therefore, s2 is a set of iterators that consists of two elements: a.begin() and a.end(). In your case, std::array<int>::iterator is probably int*, and a.begin() and a.end() happen to be serialized as 0x7ffecf9d12e0 and 0x7ffecf9d12f0, respectively.

For s3, overload resolution is performed as if in

__hypothetical __hyp(a.begin(), a.end()); // parentheses

That's direct-initialization, and is under the scope of [pver.match.ctor]. The initializer_list constructor is irrelevant, and the Constructor #1 is selected instead. Function template argument deduction gives

InputIterator = std::array<int>::iterator

So the deduced type of s3 is

set<iterator_traits<std::array<int>::iterator>::value_type>

Which is set<int>. Therefore, the declaration of s3 is equivalent to

std::set<int> s3 (a.begin(), a.end());

s3 is a set of ints that is initialized from the range [a.begin(), a.end()) — four elements 1, 2, 3, 4, which explains the output.


问:
How to force React to render same component instance
I am trying to get React render props.children base on the screen size. This code does work but React recreate new component instance of props.children. Is there a way to force React to keep the same component instance so I won't loose its state?

I tried both useMemo() memo(). I tried using key prop. None of them works.

```<code><Hidden mdUp>
  <Dialog open maxWidth="md" fullWidth>
    <DialogTitle>{props.header}</DialogTitle>
    <DialogContent>{props.children}</DialogContent>
    <DialogActions><Button onClick={props.onClose}>Close</Button></DialogActions>
  </Dialog>
</Hidden>
<Hidden mdDown>
  <Typography variant="h4" gutterBottom>{props.header}</Typography>
  {props.children}
</Hidden>
</code>```

答: Did you tried using shouldComponentUpdate() and return true? It will render your component either your props changed or not.

Body:
I am trying to get React render props.children base on the screen size. This code does work but React recreate new component instance of props.children. Is there a way to force React to keep the same component instance so I won't loose its state?

I tried both useMemo() memo(). I tried using key prop. None of them works.

<Hidden mdUp>
  <Dialog open maxWidth="md" fullWidth>
    <DialogTitle>{props.header}</DialogTitle>
    <DialogContent>{props.children}</DialogContent>
    <DialogActions><Button onClick={props.onClose}>Close</Button></DialogActions>
  </Dialog>
</Hidden>
<Hidden mdDown>
  <Typography variant="h4" gutterBottom>{props.header}</Typography>
  {props.children}
</Hidden>


问:
Why cannot compress all files with find and zip?
I have the following folder structure

```<code>.
├── 5.avi
├── a
│   ├── 1.avi
│   ├── b
│   │   └── 2.avi
│   └── c
│       └── 3.avi
└── b
    ├── 4.avi
    ├── l
    └── s
</code>```

I am using the following command to compress all avi files:

```<code>find .  -iname *avi | xargs zip videos.zip
</code>```

The problem is that find only returns 5.avi, but if the 5.avi doesn't exist, find returns the rest of the files.

How can solve it and comprime all avi files?

答:
The shell expands asterisks (*) before it passes the arguments to the command (find in your case). The actual command will look like

find . -iname 5.avi
```

<p>You can test that by prepending <code>echo</code> to your command, e.g.</p>

<pre class="lang-sh prettyprint-override"><code>echo find . -iname *avi
</code>```

What you want to do is passing *avi as-is to the command. For that, you must put the asterisk in quotes, or escape it with a backslash. Your command should be:

find . -iname '*.avi' | xargs zip videos.zip
```

Body:
I have the following folder structure

.
├── 5.avi
├── a
│   ├── 1.avi
│   ├── b
│   │   └── 2.avi
│   └── c
│       └── 3.avi
└── b
    ├── 4.avi
    ├── l
    └── s

I am using the following command to compress all avi files:

find .  -iname *avi | xargs zip videos.zip

The problem is that find only returns 5.avi, but if the 5.avi doesn't exist, find returns the rest of the files.

How can solve it and comprime all avi files?

Body:
The shell expands asterisks (*) before it passes the arguments to the command (find in your case). The actual command will look like

find . -iname 5.avi

You can test that by prepending echo to your command, e.g.

echo find . -iname *avi

What you want to do is passing *avi as-is to the command. For that, you must put the asterisk in quotes, or escape it with a backslash. Your command should be:

find . -iname '*.avi' | xargs zip videos.zip


问:
Resource leak during object creation
I have the following code for creation of a node inside a graph. I'm getting resource leak error when I run a static checking tool (coverity). I would appreciate if you can point out how to improve the code:

```<code>class node {
   public :
     explicit node(std::string& name) : m_name(name) { }
     void setlevel(int level)
     { m_level = level; }
   private :
     ...
 }
class graph {
   public :
      void populateGraph()
      {
         std::string nodeName = getNodeName();
         /* I get error saying variable from new not freed or pointed-to in function
            nc::node::node(const std::string...) */
         node* NodePtr = new node(nodeName);
         /* I get error saying variable NodePtr not freed or pointed-to in function
            nc::node::setLevel(int) */
         NodePtr->setLevel(-1);
         if (m_name2NodeMap.find(nodeName) == m_name2NodeMap.end())
             m_name2NodeMap[nodeName] = NodePtr;
         NodePtr = NULL;
      }
....
private :
  std::map< std::string, node*> m_name2NodeMap;
}
</code>```

I thought I needed to delete NodePtr in populateGraph, but then released it will call node desctructor (~node) and delete the node from the graph. So, I set NodePtr=NULL to see if it helps, but it is not.

答:
Others have already covered the issue of the leak. In fact there are leaks aplenty, so I won't even bother commenting on them all... (populateGraph, ~Graph, Graph(Graph const&) and Graph& operator=(Graph const&) at the very least...)

I prefer to offer a simple solution that works:

```<code>class Graph
{
public:
  void addNode(std::string name) {
    _nodes.insert(std::make_pair(name, Node(name));
  }

private:
  std::map<std::string, Node> _nodes;
};
</code>```

What's going on here ?

The dynamic memory allocation is unnecessary, the map can perfectly contain the Node by value, and you won't have any leak this way.

std::map::insert will only perform the insertion if no equivalent key is already present, no need to do a find + [] (which is twice as complicated since you compute twice the place where to store the element)

Title: Resource leak during object creation

Body:
I have the following code for creation of a node inside a graph. I'm getting resource leak error when I run a static checking tool (coverity). I would appreciate if you can point out how to improve the code:

class node {
   public :
     explicit node(std::string& name) : m_name(name) { }
     void setlevel(int level)
     { m_level = level; }
   private :
     ...
 }
class graph {
   public :
      void populateGraph()
      {
         std::string nodeName = getNodeName();
         /* I get error saying variable from new not freed or pointed-to in function
            nc::node::node(const std::string...) */
         node* NodePtr = new node(nodeName);
         /* I get error saying variable NodePtr not freed or pointed-to in function
            nc::node::setLevel(int) */
         NodePtr->setLevel(-1);
         if (m_name2NodeMap.find(nodeName) == m_name2NodeMap.end())
             m_name2NodeMap[nodeName] = NodePtr;
         NodePtr = NULL;
      }
....
private :
  std::map< std::string, node*> m_name2NodeMap;
}

I thought I needed to delete NodePtr in populateGraph, but then released it will call node desctructor (~node) and delete the node from the graph. So, I set NodePtr=NULL to see if it helps, but it is not.

Body:
Others have already covered the issue of the leak. In fact there are leaks aplenty, so I won't even bother commenting on them all... (populateGraph, ~Graph, Graph(Graph const&) and Graph& operator=(Graph const&) at the very least...)

I prefer to offer a simple solution that works:

class Graph
{
public:
  void addNode(std::string name) {
    _nodes.insert(std::make_pair(name, Node(name));
  }

private:
  std::map<std::string, Node> _nodes;
};

What's going on here ?

The dynamic memory allocation is unnecessary, the map can perfectly contain the Node by value, and you won't have any leak this way.

std::map::insert will only perform the insertion if no equivalent key is already present, no need to do a find + [] (which is twice as complicated since you compute twice the place where to store the element)


问:
React search and filter methods issue
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

```<code>        //////Searching works
        //////this.filter(this.state.searchInput);

         //Filtering works
         this.startFilter(this.state.searchInput);
</code>```

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
 state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  searchByGenre: false,
  list: [],

 }

 startFilter(input, filterByGenre) {
  this.setState({
   searchByGenre: true,
   searchInput: input,
   showDeleteButton: true
  });
  alert("startFilter  ")
  console.log(this.state.searchByGenre)
  /////////---------------------------------
  document.getElementById("searchField").disabled = false;
  document.getElementById('searchField').value = input
  document.getElementById('searchField').focus()
  // document.getElementById('searchField').blur()
  document.getElementById("searchField").disabled = true;

  console.log(input)
  this.filter(input);

 }

 //search
 startSearch(input) {
  alert("startSearch  ")
  console.log(this.state.searchByGenre)

  //komt uit render()
  if (!this.state.searchByGenre) {
   //check for input

   this.setState({
    searchInput: input.target.value,
    showDeleteButton: true,
   })

   //Searching works
   //this.filter(this.state.searchInput);

   //Filtering works
   this.startFilter(this.state.searchInput);

   // DOESNT WORK:
   // if (this.state.searchInput != "") {
   //  this.filter(this.state.searchInput);
   // } else {
   //  this.startFilter(this.state.searchInput);
   // }
  }

 }

 setAllLists(allLists) {
  console.log("setAllLists")
  console.log(this.state.searchByGenre)
  this.setState({ list: allLists })
  //document.body.style.backgroundColor = "red";
 }

 filter(input) {
  let corresondingGenre = [];
  let filteredLists = listData.filter(

   (item1) => {
    var test;
    if (this.state.searchByGenre) {
     alert("--this.state.searchByGenre")
     //filterByGenre
     //& item1.properties.genre == input

     for (var i = 0; i < item1.properties.genre.length; i++) {
      if (item1.properties.genre[i].includes(input)) {
       corresondingGenre.push(item1);
       test = item1.properties.genre[i].indexOf(input) !== -1;

       return test;
      }
      this.setState({ list: corresondingGenre })
     }

    } else {
     //searchByTitle
     alert("--default")
     test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
    }
    return test;
   })
  console.log("filterdLists:")
  console.log(filteredLists)
  console.log("corresondingGenre:")
  console.log(corresondingGenre)
  //alert(JSON.stringify(filteredLists))
  this.setState({ list: filteredLists })

 }

 removeInput() {
  console.log("removeInput    ")
  console.log(this.state.searchByGenre)
  this.setState({ searchInput: "", showDeleteButton: false, searchByGenre: false })
  document.getElementById("searchField").disabled = false;
  this.filter(this.state.searchInput)
 }

 render() {
  //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
  if (this.state.list === undefined || this.state.list.length == 0 && this.state.searchInput == "") {
   //init list
   console.log("render ")
   console.log(this.state.searchByGenre)
   this.filter(this.state.searchInput)
  }

  return (

    <input class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onBlur={this.startSearch.bind(this)} ></input>

    {
     this.state.searchByGenre ?

ja

      :

nee

    }
    {
     this.state.showDeleteButton ?
      <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
      : null
    }
    {
     this.state.list.map((item, index) => {
      return

{item.title}

     })
    }

  );
 }
}```

答:
SetState is an async operation that takes a callback function. I suspect that your second function runs before the first SetState is finished.

Also, you are modifying the DOM yourself. You need to let React do that for you just by modifying state. I don't have time to write up an example now, but hopefully this helps in the meantime.

Title: React search and filter methods issue

Body:
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

        //////Searching works
        //////this.filter(this.state.searchInput);

         //Filtering works
         this.startFilter(this.state.searchInput);

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
 state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  searchByGenre: false,
  list: [],

 }

 startFilter(input, filterByGenre) {
  this.setState({
   searchByGenre: true,
   searchInput: input,
   showDeleteButton: true
  });
  alert("startFilter  ")
  console.log(this.state.searchByGenre)
  /////////---------------------------------
  document.getElementById("searchField").disabled = false;
  document.getElementById('searchField').value = input
  document.getElementById('searchField').focus()
  // document.getElementById('searchField').blur()
  document.getElementById("searchField").disabled = true;

  console.log(input)
  this.filter(input);

 }

 //search
 startSearch(input) {
  alert("startSearch  ")
  console.log(this.state.searchByGenre)

  //komt uit render()
  if (!this.state.searchByGenre) {
   //check for input

   this.setState({
    searchInput: input.target.value,
    showDeleteButton: true,
   })

   //Searching works
   //this.filter(this.state.searchInput);

   //Filtering works
   this.startFilter(this.state.searchInput);

   // DOESNT WORK:
   // if (this.state.searchInput != "") {
   //  this.filter(this.state.searchInput);
   // } else {
   //  this.startFilter(this.state.searchInput);
   // }
  }

 }

 setAllLists(allLists) {
  console.log("setAllLists")
  console.log(this.state.searchByGenre)
  this.setState({ list: allLists })
  //document.body.style.backgroundColor = "red";
 }

 filter(input) {
  let corresondingGenre = [];
  let filteredLists = listData.filter(

   (item1) => {
    var test;
    if (this.state.searchByGenre) {
     alert("--this.state.searchByGenre")
     //filterByGenre
     //& item1.properties.genre == input

     for (var i = 0; i < item1.properties.genre.length; i++) {
      if (item1.properties.genre[i].includes(input)) {
       corresondingGenre.push(item1);
       test = item1.properties.genre[i].indexOf(input) !== -1;

       return test;
      }
      this.setState({ list: corresondingGenre })
     }

    } else {
     //searchByTitle
     alert("--default")
     test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
    }
    return test;
   })
  console.log("filterdLists:")
  console.log(filteredLists)
  console.log("corresondingGenre:")
  console.log(corresondingGenre)
  //alert(JSON.stringify(filteredLists))
  this.setState({ list: filteredLists })

 }

 removeInput() {
  console.log("removeInput    ")
  console.log(this.state.searchByGenre)
  this.setState({ searchInput: "", showDeleteButton: false, searchByGenre: false })
  document.getElementById("searchField").disabled = false;
  this.filter(this.state.searchInput)
 }

 render() {
  //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
  if (this.state.list === undefined || this.state.list.length == 0 && this.state.searchInput == "") {
   //init list
   console.log("render ")
   console.log(this.state.searchByGenre)
   this.filter(this.state.searchInput)
  }

  return (

    <input class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onBlur={this.startSearch.bind(this)} ></input>

    {
     this.state.searchByGenre ?

ja

      :

nee

    }
    {
     this.state.showDeleteButton ?
      <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
      : null
    }
    {
     this.state.list.map((item, index) => {
      return

{item.title}

     })
    }

  );
 }
}