问:
Collate data from multiple workbooks to a separate workbook based on column names
I have multiple workbooks in a folder and i need to copy paste data from some of them based on naming convention. I am copy pasting data based on column names to a master sheet as order of columns in source files is not the same. Code pasted below does the task but it looks for exact match in column names and as a result i am only able to capture 80% of the data as few column names in source files are not an exact match. For eg: A column in the Target file with header Premium is mentioned as Premium @ 25% in the Source file. This is just an example.

```<code>            Sub ImportExcelfiles()
               Dim strPath As String
               Dim strFile As String
               Dim wbSource As Workbook
               Dim wsSource As Worksheet
               Dim wsTarget As Worksheet
               Dim bookName As Worksheet

               Dim rowCountSource As Long
               Dim colCountSource As Long
               Dim rowOutputTarget As Long
               Dim colOutputTarget As Long

               Dim found1 As Range, found2 As Range, j As Long, Cr1 As String, srcRow As Range

               'Variables for Sheet - Workbook Name
               Dim nameCount As Long
               Dim fileName As String

              Application.DisplayAlerts = False
              Application.ScreenUpdating = False

               '====================================
               'SET THE PATH AND FILE TO THE FOLDER
               '====================================

               strPath = ThisWorkbook.Worksheets("Control").Range("C4")
               fileName = ThisWorkbook.Worksheets("Control").Range("C5")

               If Right(strPath, 1) <> "\" Then strPath = strPath & "\"

               'set the target worksheet
               Set wsTarget = ThisWorkbook.Worksheets("Master Data")
               Set bookName = ThisWorkbook.Worksheets("Workbook Name")

               'set the initial output row and column count for master data and workbook name
                  nameCount = 2
                  rowOutputTarget = wsTarget.Cells(Rows.Count, 1).End(xlUp).Row

               'get the first file
               strFile = Dir(strPath & "*.xlsx*")

               'loop throught the excel files in the folder
               Do While strFile <> ""

                  If InStr(strFile, fileName) > 0 Then

                     'open the workbook
                     Set wbSource = Workbooks.Open(strPath & strFile)
                     Set wsSource = wbSource.Worksheets("Details")

                     'get the row and column counts
                    With wsSource
                        colCountSource = .Cells(2, Columns.Count).End(xlToLeft).Column
                        For j = 1 To colCountSource
                            Cr1 = .Cells(2, j).Value
                            Set srcRow = .Range("A2", .Cells(1, colCountSource))
                            Set found1 = srcRow.Find(What:=Cr1, LookAt:=xlWhole, MatchCase:=True)

                            If Not found1 Is Nothing Then
                                colCountSource = wsTarget.Cells(1, Columns.Count).End(xlToLeft).Column

                                Set srcRow = wsTarget.Range("A1", wsTarget.Cells(1, colCountSource))
                                Set found2 = srcRow.Find(What:=Cr1, LookAt:=xlWhole, MatchCase:=F)

                                If Not found2 Is Nothing Then
                                    rowCountSource = .Cells(Rows.Count, found1.Column).End(xlUp).Row
                                    .Range(.Cells(3, found1.Column), .Cells(rowCountSource, found1.Column)).Copy
                                    found2.Offset(rowOutputTarget, 0).PasteSpecial Paste:=xlPasteValues

                                End If
                            End If
                        Next j
                    End With

                    bookName.Range("A" & nameCount).Value = wbSource.Name
                    'update output row  '2+12-1=13

                    nameCount = nameCount + 1
                    rowOutputTarget = rowOutputTarget + rowCountSource - 2

                    'close the opened workbook
                    wbSource.Close SaveChanges:=False
                  End If
                  'get the next file
                  strFile = Dir()
               Loop

                Application.ScreenUpdating = True

                MsgBox "Data imported.", vbInformation
            End Sub
</code>```

This code takes approximately 5 mins to copy paste data. Is there a way to optimise it and also solve my problem of missing 20% data.

答:
Because the target column name is the shorter you need to search the source column names for each target column name.

Option Explicit

Sub ImportExcelfiles()

    Dim strPath As String, strFile As String, fileName As String
    Dim wbSource As Workbook
    Dim wsSource As Worksheet, wsTarget As Worksheet
    Dim bookName As Worksheet

    Dim rowCountSource As Long, colCountSource As Long
    Dim colCountTarget As Long
    Dim rowOutputTarget As Long, colOutputTarget As Long

    Dim found1 As Range, found2 As Range, j As Long
    Dim Cr1 As String, srcRow As Range

    'Variables for Sheet - Workbook Name
    Dim nameCount As Long
    Dim t0 As Single: t0 = Timer

    strPath = ThisWorkbook.Worksheets("Control").Range("C4")
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"
    fileName = ThisWorkbook.Worksheets("Control").Range("C5")

    'set the target worksheet
    With ThisWorkbook
        Set wsTarget = .Sheets("Master Data")
        Set bookName = .Sheets("Workbook Name")
    End With

   'set the initial output row and column count
   'for master data and workbook name
    nameCount = 2
    Dim arTarget, rngSrc As Range, rngTarget As Range
    Dim lastrow As Long, n As Long
    With wsTarget
        rowOutputTarget = 1 + .Cells(.Rows.Count, 1).End(xlUp).Row
        ' array of target column names
        colCountTarget = .Cells(1, .Columns.Count).End(xlToLeft).Column
        arTarget = .Cells(1, 1).Resize(, colCountTarget)
    End With
   'get the first file
    strFile = Dir(strPath & "*.xlsx*")

    'loop throught the excel files in the folder
    Application.ScreenUpdating = False
    Do While strFile <> ""

        If InStr(strFile, fileName) > 0 Then

            'open the workbook
            Set wbSource = Workbooks.Open(strPath & strFile, ReadOnly:=True)
            Set wsSource = wbSource.Worksheets("Details")

            With wsSource
                'get the row and column counts'get the row and column counts
                colCountSource = .Cells(2, Columns.Count).End(xlToLeft).Column
                Set srcRow = .Range("A2", .Cells(1, colCountSource))
                ' loop through target columns
                For j = 1 To UBound(arTarget, 2)
                    Cr1 = arTarget(1, j)
                    Set found1 = srcRow.Find(What:=Cr1, LookAt:=xlPart, MatchCase:=True)
                    ' found
                    If Not found1 Is Nothing Then
                        rowCountSource = .Cells(.Rows.Count, found1.Column).End(xlUp).Row
                        n = rowCountSource - 2
                        Set rngSrc = .Range(.Cells(3, found1.Column), .Cells(rowCountSource, found1.Column))
                        Set rngTarget = wsTarget.Cells(rowOutputTarget, j)
                        rngTarget.Resize(n).Value2 = rngSrc.Value2

                        If lastrow < rowOutputTarget + n Then
                            lastrow = rowOutputTarget + n
                        End If

                    End If
                Next
            End With

            bookName.Range("A" & nameCount).Value = wbSource.Name
            'update output row  '2+12-1=13

            nameCount = nameCount + 1
            rowOutputTarget = lastrow

            'close the opened workbook
            wbSource.Close SaveChanges:=False
        End If
        'get the next file
        strFile = Dir()
    Loop
    Application.ScreenUpdating = True

    MsgBox "Data imported.", vbInformation, Format(Timer - t0, "0.0 secs")
End Sub
```

Body:
I have multiple workbooks in a folder and i need to copy paste data from some of them based on naming convention. I am copy pasting data based on column names to a master sheet as order of columns in source files is not the same. Code pasted below does the task but it looks for exact match in column names and as a result i am only able to capture 80% of the data as few column names in source files are not an exact match. For eg: A column in the Target file with header Premium is mentioned as Premium @ 25% in the Source file. This is just an example.

            Sub ImportExcelfiles()
               Dim strPath As String
               Dim strFile As String
               Dim wbSource As Workbook
               Dim wsSource As Worksheet
               Dim wsTarget As Worksheet
               Dim bookName As Worksheet

               Dim rowCountSource As Long
               Dim colCountSource As Long
               Dim rowOutputTarget As Long
               Dim colOutputTarget As Long

               Dim found1 As Range, found2 As Range, j As Long, Cr1 As String, srcRow As Range

               'Variables for Sheet - Workbook Name
               Dim nameCount As Long
               Dim fileName As String

              Application.DisplayAlerts = False
              Application.ScreenUpdating = False

               '====================================
               'SET THE PATH AND FILE TO THE FOLDER
               '====================================

               strPath = ThisWorkbook.Worksheets("Control").Range("C4")
               fileName = ThisWorkbook.Worksheets("Control").Range("C5")

               If Right(strPath, 1) <> "\" Then strPath = strPath & "\"

               'set the target worksheet
               Set wsTarget = ThisWorkbook.Worksheets("Master Data")
               Set bookName = ThisWorkbook.Worksheets("Workbook Name")

               'set the initial output row and column count for master data and workbook name
                  nameCount = 2
                  rowOutputTarget = wsTarget.Cells(Rows.Count, 1).End(xlUp).Row

               'get the first file
               strFile = Dir(strPath & "*.xlsx*")

               'loop throught the excel files in the folder
               Do While strFile <> ""

                  If InStr(strFile, fileName) > 0 Then

                     'open the workbook
                     Set wbSource = Workbooks.Open(strPath & strFile)
                     Set wsSource = wbSource.Worksheets("Details")

                     'get the row and column counts
                    With wsSource
                        colCountSource = .Cells(2, Columns.Count).End(xlToLeft).Column
                        For j = 1 To colCountSource
                            Cr1 = .Cells(2, j).Value
                            Set srcRow = .Range("A2", .Cells(1, colCountSource))
                            Set found1 = srcRow.Find(What:=Cr1, LookAt:=xlWhole, MatchCase:=True)

                            If Not found1 Is Nothing Then
                                colCountSource = wsTarget.Cells(1, Columns.Count).End(xlToLeft).Column

                                Set srcRow = wsTarget.Range("A1", wsTarget.Cells(1, colCountSource))
                                Set found2 = srcRow.Find(What:=Cr1, LookAt:=xlWhole, MatchCase:=F)

                                If Not found2 Is Nothing Then
                                    rowCountSource = .Cells(Rows.Count, found1.Column).End(xlUp).Row
                                    .Range(.Cells(3, found1.Column), .Cells(rowCountSource, found1.Column)).Copy
                                    found2.Offset(rowOutputTarget, 0).PasteSpecial Paste:=xlPasteValues

                                End If
                            End If
                        Next j
                    End With

                    bookName.Range("A" & nameCount).Value = wbSource.Name
                    'update output row  '2+12-1=13

                    nameCount = nameCount + 1
                    rowOutputTarget = rowOutputTarget + rowCountSource - 2

                    'close the opened workbook
                    wbSource.Close SaveChanges:=False
                  End If
                  'get the next file
                  strFile = Dir()
               Loop

                Application.ScreenUpdating = True

                MsgBox "Data imported.", vbInformation
            End Sub

This code takes approximately 5 mins to copy paste data. Is there a way to optimise it and also solve my problem of missing 20% data.


来源: stackexchange

问:
How do tell if a file is opened for reading/writing in Android?
Here is a code snippet where I am opening a file for writing with two FileOutputStreams at the same time.

```<code>FileOutputStream fis = null;
File openFile = new File("myfile");
try {
    fis = new FileOutputStream(openFile);
    Toast toast = Toast.makeText(getApplicationContext(), "Opened", Toast.LENGTH_SHORT);
    toast.show();
}
catch (FileNotFoundException e1) {
    Toast toast = Toast.makeText(getApplicationContext(), "FileNotFound", Toast.LENGTH_SHORT);
    toast.show();
}

// now try to open it again
FileOutputStream fis2 = null;
try {
    fis2 = new FileOutputStream(openFile);
    Toast toast = Toast.makeText(getApplicationContext(), "Opened2", Toast.LENGTH_SHORT);
    toast.show();
}
catch (Exception e1) {
    Toast toast = Toast.makeText(getApplicationContext(), "Exception: " + e1.getMessage(), Toast.LENGTH_SHORT);
    toast.show();
}
</code>```

I end up getting two Toast messages, "Opened" and "Opened2".

I need to make sure I don't open a file for reading/writing/deleting that is currently open for writing by another instance.  How to I ensure I do not modify a file that is currently open for writing?

答: FileObserver might help you.</p>

ContentLicense: CC BY-SA 3.0

Body:
Here is a code snippet where I am opening a file for writing with two FileOutputStreams at the same time.

FileOutputStream fis = null;
File openFile = new File("myfile");
try {
    fis = new FileOutputStream(openFile);
    Toast toast = Toast.makeText(getApplicationContext(), "Opened", Toast.LENGTH_SHORT);
    toast.show();
}
catch (FileNotFoundException e1) {
    Toast toast = Toast.makeText(getApplicationContext(), "FileNotFound", Toast.LENGTH_SHORT);
    toast.show();
}

// now try to open it again
FileOutputStream fis2 = null;
try {
    fis2 = new FileOutputStream(openFile);
    Toast toast = Toast.makeText(getApplicationContext(), "Opened2", Toast.LENGTH_SHORT);
    toast.show();
}
catch (Exception e1) {
    Toast toast = Toast.makeText(getApplicationContext(), "Exception: " + e1.getMessage(), Toast.LENGTH_SHORT);
    toast.show();
}

I end up getting two Toast messages, "Opened" and "Opened2".

I need to make sure I don't open a file for reading/writing/deleting that is currently open for writing by another instance.  How to I ensure I do not modify a file that is currently open for writing?

Body: FileObserver might help you.


问:
sqlite3 bulk update from temporary table (CTE)
I want to update a special column of every row that meets certain criteria.

This two answeres seemed very promising, but sqlite3 (v 3.24.0) throws an error.

Update multiple rows with different values in a single SQL query

How to use CTE's with update/delete on SQLite?

Here is what i do:

```<code>WITH tmp(md5, abs_path) AS (VALUES
            ('7dc108663732380b2596ec643f4f9122', '/path1'),
            ('80f81e1ebea9a77a336d5d0b29fe8772', '/path2'),
            /* here will be many more lines later... */
            ('f42f5c59786de8de804bf1c0d2017e95', '/path3')
                )
UPDATE files SET
    md5sum=(
        SELECT md5 FROM tmp
        WHERE
            files.absolute_path==tmp.abs_path
    )
WHERE
        files.last_seen_ts=1644002082
    AND
        files.volume_id=1111
    AND
        files.inum IN (SELECT inum FROM files WHERE files.absolute_path==tmp.abs_path)
;
</code>```

the error is:
Error: near line 1: no such column: tmp.abs_path

Can somebody help me with that?

Edit: Thanks for asking me to clarify.

The table "files" has the columns

absolute_path, md5sum, inum

and some others. When I insert the values, the md5 sum is not yet generated and there is only a placeholder. This is, because I have files with different paths but same inum (hard links). So to not unnecessarily calculate the same md5 hash multiple times, I exclude multiples of inums before the md5 calculation.

This md5 sums I have to UPDATE now for every entry in the table "files" that has the same inum as that one I calculated the md5 for and that's now in the "tmp" table to bulk update "files". To achieve this I have the WHERE condition to update all rows where the inum is the same as it is in absolute_path that must be the same path as in the tmp table with its md5 sum. So:

```<code>files.inum IN (
SELECT inum FROM files
WHERE files.absolute_path==tmp.abs_path
)
</code>```

I hope it's more clear now what I want.

答:
You should just use UPDATE FROM syntax...

https://www.sqlite.org/lang_update.html#upfrom

Something like...

```<code>WITH
    tmp(md5, abs_path)
AS
(
    VALUES
        ('7dc108663732380b2596ec643f4f9122', '/path1'),
        ('80f81e1ebea9a77a336d5d0b29fe8772', '/path2'),
        /* here will be many more lines later... */
        ('f42f5c59786de8de804bf1c0d2017e95', '/path3')
)
UPDATE
    files
SET
    md5sum = tmp.md5
FROM
    tmp
WHERE
        files.absolute_path = tmp.abs_path
    AND files.last_seen_ts  = 1644002082
    AND files.volume_id     = 1111
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to update a special column of every row that meets certain criteria.

This two answeres seemed very promising, but sqlite3 (v 3.24.0) throws an error.

Update multiple rows with different values in a single SQL query

How to use CTE's with update/delete on SQLite?

Here is what i do:

WITH tmp(md5, abs_path) AS (VALUES
            ('7dc108663732380b2596ec643f4f9122', '/path1'),
            ('80f81e1ebea9a77a336d5d0b29fe8772', '/path2'),
            /* here will be many more lines later... */
            ('f42f5c59786de8de804bf1c0d2017e95', '/path3')
                )
UPDATE files SET
    md5sum=(
        SELECT md5 FROM tmp
        WHERE
            files.absolute_path==tmp.abs_path
    )
WHERE
        files.last_seen_ts=1644002082
    AND
        files.volume_id=1111
    AND
        files.inum IN (SELECT inum FROM files WHERE files.absolute_path==tmp.abs_path)
;

the error is:
Error: near line 1: no such column: tmp.abs_path

Can somebody help me with that?

Edit: Thanks for asking me to clarify.

The table "files" has the columns

absolute_path, md5sum, inum

and some others. When I insert the values, the md5 sum is not yet generated and there is only a placeholder. This is, because I have files with different paths but same inum (hard links). So to not unnecessarily calculate the same md5 hash multiple times, I exclude multiples of inums before the md5 calculation.

This md5 sums I have to UPDATE now for every entry in the table "files" that has the same inum as that one I calculated the md5 for and that's now in the "tmp" table to bulk update "files". To achieve this I have the WHERE condition to update all rows where the inum is the same as it is in absolute_path that must be the same path as in the tmp table with its md5 sum. So:

files.inum IN (
SELECT inum FROM files
WHERE files.absolute_path==tmp.abs_path
)

I hope it's more clear now what I want.

Body:
You should just use UPDATE FROM syntax...

https://www.sqlite.org/lang_update.html#upfrom

Something like...

WITH
    tmp(md5, abs_path)
AS
(
    VALUES
        ('7dc108663732380b2596ec643f4f9122', '/path1'),
        ('80f81e1ebea9a77a336d5d0b29fe8772', '/path2'),
        /* here will be many more lines later... */
        ('f42f5c59786de8de804bf1c0d2017e95', '/path3')
)
UPDATE
    files
SET
    md5sum = tmp.md5
FROM
    tmp
WHERE
        files.absolute_path = tmp.abs_path
    AND files.last_seen_ts  = 1644002082
    AND files.volume_id     = 1111


问:
Using the "!" operator during file input/output operations in C++
I'm reviewing a project that does file input/output operations in C++. There are uses for the overloaded ! operator defined in std::ios that I have not encountered before. I know that the ! operator is used to check if a file has been opened. However, I did not understand why the author used the fstream object by using the ! operator after using the istream::seekg, istream::read, ostream::seekp, ostream::write methods in the project I was examining.

Below is a part of the add() function in the source code I've reviewed:

#include <fstream>
#include <iostream>

bool add(std::fstream &file, std::istream &input)
{
    file.seekg((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.read(reinterpret_cast<char *>(&temp), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.seekp((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.write(reinterpret_cast<const char*>(&person), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }
}
```

Do the above uses of the operator! operator make any sense?

答:
The ! operator is overloaded for classes derived from std::basic_ios (such as std::fstream) to indicate whether or not an error has occurred following an operation, or that has not been cleared after an earlier operation.

From cppreference:

Returns true if an error has occurred on the associated stream.
Specifically, returns true if badbit or failbit is set in rdstate().

In the code sample you have shown, the ! operator is called after every attempted operation on the stream and, if an error is detected, the function aborts and returns a false signal. (Note that any of those seek/read/write operations could potentially fail.)

So:

Do the above uses of the operator! operator make any sense?

Yes, they do. That's good, exemplary code, which should be commended in any review.

Body:
I'm reviewing a project that does file input/output operations in C++. There are uses for the overloaded ! operator defined in std::ios that I have not encountered before. I know that the ! operator is used to check if a file has been opened. However, I did not understand why the author used the fstream object by using the ! operator after using the istream::seekg, istream::read, ostream::seekp, ostream::write methods in the project I was examining.

Below is a part of the add() function in the source code I've reviewed:

#include <fstream>
#include <iostream>

bool add(std::fstream &file, std::istream &input)
{
    file.seekg((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.read(reinterpret_cast<char *>(&temp), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.seekp((id - 1) * sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }

    file.write(reinterpret_cast<const char*>(&person), sizeof(Person));
    /* What is the purpose of using the "operator!" below? */
    if(!file){ return false; }
}

Do the above uses of the operator! operator make any sense?


问:
ViewBag selectlist to return Year using GroupBy to eliminate multiple years of the same year
I am having some issues creating a viewbag selectlist. I am grabbing from a table where there are multiple records with the same date - Year. The Goal is to create a dropdown of years to select from. I think my controller is good but not sure and the view is definitely not correct.

Here is what I have:

Controller:

```<code>    public ActionResult MilesReport(long? Year)
    {
        long Years = Year ?? db.ExpenseReportsDetails.FirstOrDefault().CreatedDate.Year;
        var list = db.ExpenseReportsDetails.GroupBy(i => i.CreatedDate.Year).ToList();
        ViewBag.Year = new SelectList(list, "CreatedDate.Year", "CreatedDate.Year", Years);

        //var miles = db.ExpenseReportsDetails.Where(x => x.Miles > 0 && x.CreatedDate.Year == Year);

        return View();
    }
</code>```

And here is the View:

@Html.DropDownList("Year", "--Select--")

The controller while in debug gets a count of 2 which is correct there is only 2021 and 2022.

I get this error on the view Dropdown:

```<code>DataBinding: 'System.Data.Entity.Core.Objects.ELinq.InitializerMetadata+Grouping`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[BestenEquipment.GeneralDTO.Entities.ExpenseReportsDetails, BestenEquipment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'CreatedDate'.
</code>```

I am not sure why it says there is not a CreatedDate when there is.

Thanks for your help!

答:
I did not have to use this on the above. However I did use it for another page. Below is what I found to work with the help of the answer by Serge. It did not work the way he had it but I was able to reconstruct it so it did. Here is what the solution ended up being.

```<code> AccountingEntities acct = new AccountingEntities();
 var list = acct.Transaction.Select(s => s.TransactionDate.Year).Distinct().Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() });
 ViewBag.Year = list.Select(x => new SelectListItem
                                 {
                                    Value = x.Text,
                                    Text = x.Text
                                 }).ToList();
</code>```

Then in the View I added this:

```<code> @Html.DropDownList("Year", " -Select- ")
</code>```

This does seem redundant to me but it works, and did not work with the var list to just a .ToList. Meaning on the Viewbag.Year when putting Value = x. and Text = x. It did not know what Text & Value was.

Body:
I am having some issues creating a viewbag selectlist. I am grabbing from a table where there are multiple records with the same date - Year. The Goal is to create a dropdown of years to select from. I think my controller is good but not sure and the view is definitely not correct.

Here is what I have:

Controller:

    public ActionResult MilesReport(long? Year)
    {
        long Years = Year ?? db.ExpenseReportsDetails.FirstOrDefault().CreatedDate.Year;
        var list = db.ExpenseReportsDetails.GroupBy(i => i.CreatedDate.Year).ToList();
        ViewBag.Year = new SelectList(list, "CreatedDate.Year", "CreatedDate.Year", Years);

        //var miles = db.ExpenseReportsDetails.Where(x => x.Miles > 0 && x.CreatedDate.Year == Year);

        return View();
    }

And here is the View:

@Html.DropDownList("Year", "--Select--")

The controller while in debug gets a count of 2 which is correct there is only 2021 and 2022.

I get this error on the view Dropdown:

DataBinding: 'System.Data.Entity.Core.Objects.ELinq.InitializerMetadata+Grouping`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[BestenEquipment.GeneralDTO.Entities.ExpenseReportsDetails, BestenEquipment, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' does not contain a property with the name 'CreatedDate'.

I am not sure why it says there is not a CreatedDate when there is.

Thanks for your help!

Body:
I did not have to use this on the above. However I did use it for another page. Below is what I found to work with the help of the answer by Serge. It did not work the way he had it but I was able to reconstruct it so it did. Here is what the solution ended up being.

 AccountingEntities acct = new AccountingEntities();
 var list = acct.Transaction.Select(s => s.TransactionDate.Year).Distinct().Select(i => new SelectListItem { Value = i.ToString(), Text = i.ToString() });
 ViewBag.Year = list.Select(x => new SelectListItem
                                 {
                                    Value = x.Text,
                                    Text = x.Text
                                 }).ToList();

Then in the View I added this:

 @Html.DropDownList("Year", " -Select- ")

This does seem redundant to me but it works, and did not work with the var list to just a .ToList. Meaning on the Viewbag.Year when putting Value = x. and Text = x. It did not know what Text & Value was.


问:
Using two time values in while loop. The while loop doesn't stop when condition no longer 1. C++
My while loop isn't stopping even though one of the values becomes 'greater than' and the condition changes from 1 to 0.

Before the while loops starts I set the time now in milliseconds. milliseconds_now

I also set a time five seconds in the future. milliseconds_then

I have (milliseconds_now < milliseconds_then) in the while loop. It should only be 1 for five seconds. I also print out (milliseconds_now < milliseconds_then) within the loop and it goes from printing '1' to printing '0' after five seconds.

I expect the loop to stop after five seconds. Instead it continues.

This is what I have in the terminal when I run the program at five seconds. It just keeps looping.

```<code>1644097691885 1644097692070
1
1644097691935 1644097692070
1
1644097691986 1644097692070
1
1644097692036 1644097692070
1
1644097692086 1644097692070
0
1644097692136 1644097692070
0
1644097692186 1644097692070
0
1644097692236 1644097692070
0
1644097692287 1644097692070
0
1644097692337 1644097692070
0
1644097692387 1644097692070
0
1644097692437 1644097692070
</code>```

The code.

```<code>#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace std::chrono;

auto now = high_resolution_clock::now();
auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

auto milliseconds_then = milliseconds_now + 5000;

int main() {
    while (milliseconds_now < milliseconds_then) {

        auto now = high_resolution_clock::now();
        auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

        cout << milliseconds_now << " " << milliseconds_then << "\n";
        cout << (milliseconds_now < milliseconds_then) << "\n";

        usleep(50000);
    };
};
</code>```

答:
the milliseconds_now inside the loop is not the same milliseconds_now being tested in the while loop. Change it to

```<code>while (milliseconds_now < milliseconds_then) {

    auto now = high_resolution_clock::now();
    milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

    cout << milliseconds_now << " " << milliseconds_then << "\n";
    cout << (milliseconds_now < milliseconds_then) << "\n";

    usleep(50000);
};
</code>```

why? you are declaring a new variable inside the loop, often the compiler will warn you about it.

Body:
My while loop isn't stopping even though one of the values becomes 'greater than' and the condition changes from 1 to 0.

Before the while loops starts I set the time now in milliseconds. milliseconds_now

I also set a time five seconds in the future. milliseconds_then

I have (milliseconds_now < milliseconds_then) in the while loop. It should only be 1 for five seconds. I also print out (milliseconds_now < milliseconds_then) within the loop and it goes from printing '1' to printing '0' after five seconds.

I expect the loop to stop after five seconds. Instead it continues.

This is what I have in the terminal when I run the program at five seconds. It just keeps looping.

1644097691885 1644097692070
1
1644097691935 1644097692070
1
1644097691986 1644097692070
1
1644097692036 1644097692070
1
1644097692086 1644097692070
0
1644097692136 1644097692070
0
1644097692186 1644097692070
0
1644097692236 1644097692070
0
1644097692287 1644097692070
0
1644097692337 1644097692070
0
1644097692387 1644097692070
0
1644097692437 1644097692070

The code.

#include <iostream>
#include <chrono>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
using namespace std::chrono;

auto now = high_resolution_clock::now();
auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

auto milliseconds_then = milliseconds_now + 5000;

int main() {
    while (milliseconds_now < milliseconds_then) {

        auto now = high_resolution_clock::now();
        auto milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

        cout << milliseconds_now << " " << milliseconds_then << "\n";
        cout << (milliseconds_now < milliseconds_then) << "\n";

        usleep(50000);
    };
};

Body:
the milliseconds_now inside the loop is not the same milliseconds_now being tested in the while loop. Change it to

while (milliseconds_now < milliseconds_then) {

    auto now = high_resolution_clock::now();
    milliseconds_now = duration_cast<milliseconds>(now.time_since_epoch()).count();

    cout << milliseconds_now << " " << milliseconds_then << "\n";
    cout << (milliseconds_now < milliseconds_then) << "\n";

    usleep(50000);
};

why? you are declaring a new variable inside the loop, often the compiler will warn you about it.


问:
Sql developer problem. No ocijdbc21 in java.library.path
So I downloaded Oracle 19c DBMS. Then I downloaded Sql Developer. When I try to add a new connection, I get the message

How do I get past this. I have seen some other threads on this but none of the solutions that I understand seem to fix it. I need to keep the connection type as local. Is there somewhere I can go and just adjust this path?

EDIT
I used just a basic connection and the name database name in the service name box and it worked. The initial setup instructions I had were dated and not set up for 19c. One of the comments in the answer below suggested this.

答:
In my case, the DB connection changed from Network Alias to Connect Identifier post a company pushed update, simple fix after hours /days of trouble shooting.

enter image description here


问:
TraceBack Cannot connect to host api.telegram.org:443
I wrote a telegram bot on the aiogram framework. The bot worked fine for over a week, with no problems. The customer started complaining about the bot freezing. I downloaded the log file and saw a bunch of different TraceBacks. This situation has been happening for two days now. List of 3 TraceBacks, for example:

First

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 986, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "/usr/lib/python3.7/asyncio/base_events.py", line 959, in create_connection
    raise exceptions[0]
  File "/usr/lib/python3.7/asyncio/base_events.py", line 946, in create_connection
    await self.sock_connect(sock, address)
  File "/usr/lib/python3.7/asyncio/selector_events.py", line 464, in sock_connect
    return await fut
  File "/usr/lib/python3.7/asyncio/selector_events.py", line 469, in _sock_connect
    sock.connect(address)
OSError: [Errno 101] Network is unreachable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 139, in make_request
    async with session.post(url, data=req, **kwargs) as response:
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/client.py", line 536, in _request
    req, traces=traces, timeout=real_timeout
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 542, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 907, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 1187, in _create_direct_connection
    client_error=client_error,
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 992, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 385, in start_polling
    allowed_updates=allowed_updates
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
    result = await self.request(api.Methods.GET_UPDATES, payload)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 142, in make_request
    raise exceptions.NetworkError(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]
</code>```

Second

```<code>future: <Task finished coro=<Dispatcher._process_polling_updates() done, defined at /usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py:407> exception=TelegramAPIError('Gateway Timeout')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/koval_pavlo03/TokenSaleBot/handlers/admin_commands.py", line 152, in do_adm
    await message.answer_document(open('logs.txt', 'rb'))
  File "/usr/local/lib/python3.7/dist-packages/aiogram/types/message.py", line 733, in answer_document
    reply_markup=reply_markup,
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 708, in send_document
    result = await self.request(api.Methods.SEND_DOCUMENT, payload, files)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 128, in check_result
    raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Gateway Timeout
</code>```

Third

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 385, in start_polling
    allowed_updates=allowed_updates
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
    result = await self.request(api.Methods.GET_UPDATES, payload)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 119, in check_result
    exceptions.ConflictError.detect(description)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/utils/exceptions.py", line 140, in detect
    raise err(cls.text or description)
aiogram.utils.exceptions.TerminatedByOtherGetUpdates: Terminated by other getupdates request; make sure that only one bot instance is running
01/21/2022 19:57:14 SSL error in data received
protocol: <asyncio.sslproto.SSLProtocol object at 0x7feef4858278>
transport: <_SelectorSocketTransport fd=9 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "/usr/lib/python3.7/asyncio/sslproto.py", line 526, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "/usr/lib/python3.7/asyncio/sslproto.py", line 207, in feed_ssldata
    self._sslobj.unwrap()
  File "/usr/lib/python3.7/ssl.py", line 767, in unwrap
    return self._sslobj.shutdown()
</code>```

On my computer everything works fine. The bot is hosted on Google Cloud Platform (Compute engine). I have already tried restarting the bot and the host machine - it did not help; the problem appeared again today. I also changed the bot token, also did not work. For the sake of completeness, below is a list of versions:

```<code>$ python3 --version
Python 3.7.3

$ python3 -m pip show aiogram
Name: aiogram
Version: 2.18
Summary: Is a pretty simple and fully asynchronous framework for Telegram Bot API
Home-page: https://github.com/aiogram/aiogram
Author: Alex Root Junior
Author-email: jroot.junior@gmail.com
License: MIT
Location: /usr/local/lib/python3.7/dist-packages
Requires: aiohttp, Babel, certifi
Required-by:

$ python3 -m pip show aiohttp
Name: aiohttp
Version: 3.8.1
Summary: Async http client/server framework (asyncio)
Home-page: https://github.com/aio-libs/aiohttp
Author:
Author-email:
License: Apache 2
Location: /usr/local/lib/python3.7/dist-packages
Requires: aiosignal, async-timeout, asynctest, attrs, charset-normalizer, frozenlist, multidict, typing-extensions, yarl
Required-by: aiogram
</code>```

UPD

Here you can see log file (Google Drive)

答:
The problem is that time on your host machine is different from world time.

I have noticed that Google Cloud compute engine doesn't have any time synchronization services. That explains why the bot works well for some time, and then he starts catching tracebacks.

Body:
I wrote a telegram bot on the aiogram framework. The bot worked fine for over a week, with no problems. The customer started complaining about the bot freezing. I downloaded the log file and saw a bunch of different TraceBacks. This situation has been happening for two days now. List of 3 TraceBacks, for example:

First

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 986, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "/usr/lib/python3.7/asyncio/base_events.py", line 959, in create_connection
    raise exceptions[0]
  File "/usr/lib/python3.7/asyncio/base_events.py", line 946, in create_connection
    await self.sock_connect(sock, address)
  File "/usr/lib/python3.7/asyncio/selector_events.py", line 464, in sock_connect
    return await fut
  File "/usr/lib/python3.7/asyncio/selector_events.py", line 469, in _sock_connect
    sock.connect(address)
OSError: [Errno 101] Network is unreachable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 139, in make_request
    async with session.post(url, data=req, **kwargs) as response:
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/client.py", line 1138, in __aenter__
    self._resp = await self._coro
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/client.py", line 536, in _request
    req, traces=traces, timeout=real_timeout
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 542, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 907, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 1206, in _create_direct_connection
    raise last_exc
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 1187, in _create_direct_connection
    client_error=client_error,
  File "/usr/local/lib/python3.7/dist-packages/aiohttp/connector.py", line 992, in _wrap_create_connection
    raise client_error(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 385, in start_polling
    allowed_updates=allowed_updates
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
    result = await self.request(api.Methods.GET_UPDATES, payload)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 142, in make_request
    raise exceptions.NetworkError(f"aiohttp client throws an error: {e.__class__.__name__}: {e}")
aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]

Second

future: <Task finished coro=<Dispatcher._process_polling_updates() done, defined at /usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py:407> exception=TelegramAPIError('Gateway Timeout')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 415, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 235, in process_updates
    return await asyncio.gather(*tasks)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 256, in process_update
    return await self.message_handlers.notify(update.message)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "/home/koval_pavlo03/TokenSaleBot/handlers/admin_commands.py", line 152, in do_adm
    await message.answer_document(open('logs.txt', 'rb'))
  File "/usr/local/lib/python3.7/dist-packages/aiogram/types/message.py", line 733, in answer_document
    reply_markup=reply_markup,
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 708, in send_document
    result = await self.request(api.Methods.SEND_DOCUMENT, payload, files)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 128, in check_result
    raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Gateway Timeout

Third

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/dist-packages/aiogram/dispatcher/dispatcher.py", line 385, in start_polling
    allowed_updates=allowed_updates
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
    result = await self.request(api.Methods.GET_UPDATES, payload)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/base.py", line 232, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, timeout=self.timeout, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 140, in make_request
    return check_result(method, response.content_type, response.status, await response.text())
  File "/usr/local/lib/python3.7/dist-packages/aiogram/bot/api.py", line 119, in check_result
    exceptions.ConflictError.detect(description)
  File "/usr/local/lib/python3.7/dist-packages/aiogram/utils/exceptions.py", line 140, in detect
    raise err(cls.text or description)
aiogram.utils.exceptions.TerminatedByOtherGetUpdates: Terminated by other getupdates request; make sure that only one bot instance is running
01/21/2022 19:57:14 SSL error in data received
protocol: <asyncio.sslproto.SSLProtocol object at 0x7feef4858278>
transport: <_SelectorSocketTransport fd=9 read=polling write=<idle, bufsize=0>>
Traceback (most recent call last):
  File "/usr/lib/python3.7/asyncio/sslproto.py", line 526, in data_received
    ssldata, appdata = self._sslpipe.feed_ssldata(data)
  File "/usr/lib/python3.7/asyncio/sslproto.py", line 207, in feed_ssldata
    self._sslobj.unwrap()
  File "/usr/lib/python3.7/ssl.py", line 767, in unwrap
    return self._sslobj.shutdown()

On my computer everything works fine. The bot is hosted on Google Cloud Platform (Compute engine). I have already tried restarting the bot and the host machine - it did not help; the problem appeared again today. I also changed the bot token, also did not work. For the sake of completeness, below is a list of versions:

$ python3 --version
Python 3.7.3

$ python3 -m pip show aiogram
Name: aiogram
Version: 2.18
Summary: Is a pretty simple and fully asynchronous framework for Telegram Bot API
Home-page: https://github.com/aiogram/aiogram
Author: Alex Root Junior
Author-email: jroot.junior@gmail.com
License: MIT
Location: /usr/local/lib/python3.7/dist-packages
Requires: aiohttp, Babel, certifi
Required-by:

$ python3 -m pip show aiohttp
Name: aiohttp
Version: 3.8.1
Summary: Async http client/server framework (asyncio)
Home-page: https://github.com/aio-libs/aiohttp
Author:
Author-email:
License: Apache 2
Location: /usr/local/lib/python3.7/dist-packages
Requires: aiosignal, async-timeout, asynctest, attrs, charset-normalizer, frozenlist, multidict, typing-extensions, yarl
Required-by: aiogram

UPD

Here you can see log file (Google Drive)


问:
Do languages like JS with a copying GC ever store anything on the cpu registers?
I am learning about GC's and I know there's a thing called HandleScope which 'protects' your local variables from the GC and updates them if a gc heap copy happens. For example, if I have a routine which adds togother 2 values and I call it, it may invoke the garbage collector which will copy the Object that my value is pointing to (or the GC will not even know that the Object the value is pointing to is referenced). A really minimal example:

#include <vector>

Value addValues(Value a, Value b);
std::vector<Value*> gc_vals_with_protection;

Value func(Value a, Value b)
{
    vars.push_back(&a); // set protection for a
    gc_vals_with_protection.push_back(&b); // set protection for b
    Value res = addValues(a, b); // do calcuations
    gc_vals_with_protection.pop_back(); // remove protection for b
    gc_vals_with_protection.pop_back(); // remove protection for a
    return res;
}
```

But this has got me thinking, it will mean that a and b will NEVER be on the physical CPU registers because you have taken their addresses (and CPU registers don't have addresses) which will make calcuations on them inefficient. Also, at the beggining of every function, you would have to push back twice to the vector (https://godbolt.org/z/dc6vY1Yc5 for assembly).

I think I may be missing something, as this must be not optimal. Is there any other trick I am missing?

答:
(V8 developer here.)

Do languages like JS with a copying GC ever store anything on the cpu registers?

Yes, of course. Pretty much anything at all that a CPU does involves its registers.

That said, JavaScript objects are generally allocated on the heap anyway, for at least the following reasons:

(1) They are bigger than a register. So registers typically hold pointers to objects on the heap. It's these pointers, not the objects themselves, that Handles are needed for (both to update them, and to inform the GC that there are references to the object in question, so the object must not be freed).

(2) They tend to be much longer-lived than the typical amount of time you can hold something in a register, which is only a couple of machine instructions: since the set of registers is so small, they are reused for something else all the time (regardless of JavaScript or GC etc), so whatever they held before will either be spilled (usually though not necessarily to the stack), or re-read from wherever it originally came from next time it's needed.

(3) They have "pointer identity": JavaScript code like obj1 === obj2 (for objects, not primitives) only works correctly when there is exactly one location where an object is stored. Trying to store objects in registers would imply copying them around, which would break this.

There is certainly some cost to creating Handles; it's faster than adding something to a std::vector though.

Also, when passing Handles from one function to another, the called function doesn't have to re-register anything: Handles can be passed around without having to create new entries in the HandleScope's backing store.

A very important observation is that JavaScript functions don't need Handles for their locals. When executing JavaScript, V8 carefully keeps track of the contents of the stack (i.e. spilled contents of registers), and can walk and update the stack directly. HandleScopes are only needed for C++ code dealing with JS objects, because this technique isn't possible for C++ stack frames (which are controlled by the C++ compiler). Such C++ code is typically not the most critical performance bottleneck of an app; so while its performance certainly matters, some amount of overhead is acceptable.

(Side note: one can "blindly" (i.e. without knowledge about their contents) scan C++ stack frames and do so-called "conservative" (instead of "precise") garbage collection; this comes with its own pros and cons, in particular it makes a moving GC impossible, so is not directly relevant to your question.)

Taking this one step further: sufficiently "hot" functions will get compiled to optimized machine code; this code is the result of careful analysis and hence can be quite aggressive about keeping values (primarily numbers) in registers as long as possible, for example for chains of calculations before the final result is eventually stored in some property of some object.

For completeness, I'll also mention that sometimes, entire objects can be held in registers: this is when the optimizing compiler successfully performs "escape analysis" and can prove that the object never "escapes" to the outside world. A simple example would be:

```<code>function silly(a, b) {
  let vector = {x: a, y: b};
  return vector.x + vector.y;
}
</code>```

When this function gets optimized, the compiler can prove that vector never escapes, so it can skip the allocation and keep a and b in registers (or at least as "standalone values", they might still get spilled to the stack if the function is bigger and needs those registers for something else).

Body:
I am learning about GC's and I know there's a thing called HandleScope which 'protects' your local variables from the GC and updates them if a gc heap copy happens. For example, if I have a routine which adds togother 2 values and I call it, it may invoke the garbage collector which will copy the Object that my value is pointing to (or the GC will not even know that the Object the value is pointing to is referenced). A really minimal example:

#include <vector>

Value addValues(Value a, Value b);
std::vector<Value*> gc_vals_with_protection;

Value func(Value a, Value b)
{
    vars.push_back(&a); // set protection for a
    gc_vals_with_protection.push_back(&b); // set protection for b
    Value res = addValues(a, b); // do calcuations
    gc_vals_with_protection.pop_back(); // remove protection for b
    gc_vals_with_protection.pop_back(); // remove protection for a
    return res;
}

But this has got me thinking, it will mean that a and b will NEVER be on the physical CPU registers because you have taken their addresses (and CPU registers don't have addresses) which will make calcuations on them inefficient. Also, at the beggining of every function, you would have to push back twice to the vector (https://godbolt.org/z/dc6vY1Yc5 for assembly).

I think I may be missing something, as this must be not optimal. Is there any other trick I am missing?

Body:
(V8 developer here.)

Do languages like JS with a copying GC ever store anything on the cpu registers?

Yes, of course. Pretty much anything at all that a CPU does involves its registers.

That said, JavaScript objects are generally allocated on the heap anyway, for at least the following reasons:

(1) They are bigger than a register. So registers typically hold pointers to objects on the heap. It's these pointers, not the objects themselves, that Handles are needed for (both to update them, and to inform the GC that there are references to the object in question, so the object must not be freed).

(2) They tend to be much longer-lived than the typical amount of time you can hold something in a register, which is only a couple of machine instructions: since the set of registers is so small, they are reused for something else all the time (regardless of JavaScript or GC etc), so whatever they held before will either be spilled (usually though not necessarily to the stack), or re-read from wherever it originally came from next time it's needed.

(3) They have "pointer identity": JavaScript code like obj1 === obj2 (for objects, not primitives) only works correctly when there is exactly one location where an object is stored. Trying to store objects in registers would imply copying them around, which would break this.

There is certainly some cost to creating Handles; it's faster than adding something to a std::vector though.

Also, when passing Handles from one function to another, the called function doesn't have to re-register anything: Handles can be passed around without having to create new entries in the HandleScope's backing store.

A very important observation is that JavaScript functions don't need Handles for their locals. When executing JavaScript, V8 carefully keeps track of the contents of the stack (i.e. spilled contents of registers), and can walk and update the stack directly. HandleScopes are only needed for C++ code dealing with JS objects, because this technique isn't possible for C++ stack frames (which are controlled by the C++ compiler). Such C++ code is typically not the most critical performance bottleneck of an app; so while its performance certainly matters, some amount of overhead is acceptable.

(Side note: one can "blindly" (i.e. without knowledge about their contents) scan C++ stack frames and do so-called "conservative" (instead of "precise") garbage collection; this comes with its own pros and cons, in particular it makes a moving GC impossible, so is not directly relevant to your question.)

Taking this one step further: sufficiently "hot" functions will get compiled to optimized machine code; this code is the result of careful analysis and hence can be quite aggressive about keeping values (primarily numbers) in registers as long as possible, for example for chains of calculations before the final result is eventually stored in some property of some object.

For completeness, I'll also mention that sometimes, entire objects can be held in registers: this is when the optimizing compiler successfully performs "escape analysis" and can prove that the object never "escapes" to the outside world. A simple example would be:

function silly(a, b) {
  let vector = {x: a, y: b};
  return vector.x + vector.y;
}

When this function gets optimized, the compiler can prove that vector never escapes, so it can skip the allocation and keep a and b in registers (or at least as "standalone values", they might still get spilled to the stack if the function is bigger and needs those registers for something else).


问:
Jest not finding my function and complains of a TypeError
I created a Node.js application which exports a validate function. When I use the validator in a Jest test. Jest complains the validate is not a function. the function is clearly exported and when I click on it in VS Code, it goes right to the function.  Here is the validate function exported in a file called validator.js:

```<code>          // validator.js
             module.exports = {
               validate: (req) => {
               let policyType = req.body.policy_type;
               let length = req.body.term_length;

               if (!policyType) {
                return false;
               }
                if (!length) {
                 return false;
                }
                return  true;
               }
              };
</code>```

I then pull in the function in the Jest test as follows:

```<code>        const validate = require("./validator.js");
        describe(“Validator Test", ()=> {
        test('Ensure expected return ', ()=>{
        const req = {};
        req.body.policy_type= '';
        req.body.term_length= '';

        //TypeError: validate is not a function
         expect(validate(req)).toEqual(expectedOut);

       })
</code>```

Jest complains that validate is not a function. I simply don't know why it is complaining about not finding the function which can be found in other functions in the node application.  I searched online but could not find a use case like mine. As I am quite new to Jest, I would appreciate any help in resolving this. Thank you.

答: The module.exports works fine. The problem was related to another import which wasn't resolved in the validator.</p>

Body:
I created a Node.js application which exports a validate function. When I use the validator in a Jest test. Jest complains the validate is not a function. the function is clearly exported and when I click on it in VS Code, it goes right to the function.  Here is the validate function exported in a file called validator.js:

          // validator.js
             module.exports = {
               validate: (req) => {
               let policyType = req.body.policy_type;
               let length = req.body.term_length;

               if (!policyType) {
                return false;
               }
                if (!length) {
                 return false;
                }
                return  true;
               }
              };

I then pull in the function in the Jest test as follows:

        const validate = require("./validator.js");
        describe(“Validator Test", ()=> {
        test('Ensure expected return ', ()=>{
        const req = {};
        req.body.policy_type= '';
        req.body.term_length= '';

        //TypeError: validate is not a function
         expect(validate(req)).toEqual(expectedOut);

       })

Jest complains that validate is not a function. I simply don't know why it is complaining about not finding the function which can be found in other functions in the node application.  I searched online but could not find a use case like mine. As I am quite new to Jest, I would appreciate any help in resolving this. Thank you.


问:
Disabling Nagle's Algorithm Client Side/JavaScript
Does Nagle's Algorithm need to be disabled client side as well? If this is the case, I have not found a way to disable Nagle's algorithm through JavaScript alone.

I am trying to stream data across a websocket, from a PHP CLI server hosted on Raspbian OS (have also hosted on Windows 7 and Ubuntu with same results). This server has successfully created the socket and accepts multiple connections, and has set the TCP_NODELAY flag (verified with socket_get_option only).

```<code>$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
socket_set_option($sock, SOL_SOCKET, TCP_NODELAY, 1);
</code>```

On most platforms, regardless of this TCP_NODELAY flag being set, the data will stream without clumping. However, on Windows 7 Chrome and Firefox, the data arrives in chunks (with a telltale 0.2s delay). On Windows 8, Linux, iOS, and Windows 7's Internet Explorer 11: I don't see this problem at all.

http://www.13willows.com/hovelme/script/serverControl.php
Here is the test website, click "Connect", then click "View Game" and you should see a Current Packet steadily incrementing from 1 to 20, every 50ms. However, on some clients, it jumps 4 at a time approx every 200ms.

Any ideas to get this to stop? Will using node.js / socket.io fix something like this and still allow me to run code from a user's browser?

答:
At least Chrome seems to disable Nagle algorithm for all WebSocket sockets:

Worth noting that Chrome also disables the Nagle algorithm on all of its TCP sockets.

But it seems like NODELAY option should be enabled on both sides to guarantee low latency:

We already disable Nagle on all platforms, using just such a method, but that doesn't disable delaying ACKs (Or at least it doesn't on Windows, it's certainly possible it does elsewhere).

source

Chromium source code seems to proof this (but I'm not a Chromium developer, so I'm just guessing that the following code is called on all TCP sockets as one of commentators above said):

void TCPSocketPosix::SetDefaultOptionsForClient() {
  DCHECK(socket_);

  // This mirrors the behaviour on Windows. See the comment in
  // tcp_socket_win.cc after searching for "NODELAY".
  // If SetTCPNoDelay fails, we don't care.
  SetTCPNoDelay(socket_->socket_fd(), true);

  // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
  // enable it there. It's useful to prevent TCP middleboxes from timing out
  // connection mappings. Packets for timed out connection mappings at
  // middleboxes will either lead to:
  // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
  // and retry. The HTTP network transaction code does this.
  // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
  // stack retransmitting packets per TCP stack retransmission timeouts, which
  // are very high (on the order of seconds). Given the number of
  // retransmissions required before killing the connection, this can lead to
  // tens of seconds or even minutes of delay, depending on OS.
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  const int kTCPKeepAliveSeconds = 45;

  SetTCPKeepAlive(socket_->socket_fd(), true, kTCPKeepAliveSeconds);
#endif
}
```

link to source line

See also this possible workaround idea - https://stackoverflow.com/a/13406438/3167374

Body:
Does Nagle's Algorithm need to be disabled client side as well? If this is the case, I have not found a way to disable Nagle's algorithm through JavaScript alone.

I am trying to stream data across a websocket, from a PHP CLI server hosted on Raspbian OS (have also hosted on Windows 7 and Ubuntu with same results). This server has successfully created the socket and accepts multiple connections, and has set the TCP_NODELAY flag (verified with socket_get_option only).

$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)
socket_set_option($sock, SOL_SOCKET, TCP_NODELAY, 1);

On most platforms, regardless of this TCP_NODELAY flag being set, the data will stream without clumping. However, on Windows 7 Chrome and Firefox, the data arrives in chunks (with a telltale 0.2s delay). On Windows 8, Linux, iOS, and Windows 7's Internet Explorer 11: I don't see this problem at all.

http://www.13willows.com/hovelme/script/serverControl.php
Here is the test website, click "Connect", then click "View Game" and you should see a Current Packet steadily incrementing from 1 to 20, every 50ms. However, on some clients, it jumps 4 at a time approx every 200ms.

Any ideas to get this to stop? Will using node.js / socket.io fix something like this and still allow me to run code from a user's browser?

Body:
At least Chrome seems to disable Nagle algorithm for all WebSocket sockets:

Worth noting that Chrome also disables the Nagle algorithm on all of its TCP sockets.

But it seems like NODELAY option should be enabled on both sides to guarantee low latency:

We already disable Nagle on all platforms, using just such a method, but that doesn't disable delaying ACKs (Or at least it doesn't on Windows, it's certainly possible it does elsewhere).

source

Chromium source code seems to proof this (but I'm not a Chromium developer, so I'm just guessing that the following code is called on all TCP sockets as one of commentators above said):

void TCPSocketPosix::SetDefaultOptionsForClient() {
  DCHECK(socket_);

  // This mirrors the behaviour on Windows. See the comment in
  // tcp_socket_win.cc after searching for "NODELAY".
  // If SetTCPNoDelay fails, we don't care.
  SetTCPNoDelay(socket_->socket_fd(), true);

  // TCP keep alive wakes up the radio, which is expensive on mobile. Do not
  // enable it there. It's useful to prevent TCP middleboxes from timing out
  // connection mappings. Packets for timed out connection mappings at
  // middleboxes will either lead to:
  // a) Middleboxes sending TCP RSTs. It's up to higher layers to check for this
  // and retry. The HTTP network transaction code does this.
  // b) Middleboxes just drop the unrecognized TCP packet. This leads to the TCP
  // stack retransmitting packets per TCP stack retransmission timeouts, which
  // are very high (on the order of seconds). Given the number of
  // retransmissions required before killing the connection, this can lead to
  // tens of seconds or even minutes of delay, depending on OS.
#if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_IOS)
  const int kTCPKeepAliveSeconds = 45;

  SetTCPKeepAlive(socket_->socket_fd(), true, kTCPKeepAliveSeconds);
#endif
}

link to source line

See also this possible workaround idea - https://stackoverflow.com/a/13406438/3167374


问:
How do I get a parent div to resize when the children do?
I'm running into this problem with a program I'm working on and I can't figure out the solution. Basically I have a webapp, on initial render the entire page is height X. There is a background color, and that color covers the full height of the page.

Moments after the initial render, data is fetched asynchronously and added to the page. The data causes the total height of the page to get larger. Unfortunately, only the original height of the page shows the background color, below that the background becomes white.

On further investigation, I've discovered this is due to a parent div not resizing when the child div does. Basically, the div getting elements added to it by the asynchronous data loading grows in height, but the parent wrapping around it (and the one that has the background color) does not.

During my investigation, I have found a partial solution: set the "height" to "auto". The problem with this solution is when the page initially loads, the background color is only applied to the part of the page with actual content, rather than filling the screen. So if I have the height at "auto", the color is screwed up when the page first loads before correcting itself after the items are added, and if the height is "100%" then the color is screwed up after the items are added.

I've put together a barebones HTML file that re-creates the issue:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>
</code>```

答: You could set min-height: 100vh; on the #root element CSS so that it is always at least the height of the viewport.

Body:
I'm running into this problem with a program I'm working on and I can't figure out the solution. Basically I have a webapp, on initial render the entire page is height X. There is a background color, and that color covers the full height of the page.

Moments after the initial render, data is fetched asynchronously and added to the page. The data causes the total height of the page to get larger. Unfortunately, only the original height of the page shows the background color, below that the background becomes white.

On further investigation, I've discovered this is due to a parent div not resizing when the child div does. Basically, the div getting elements added to it by the asynchronous data loading grows in height, but the parent wrapping around it (and the one that has the background color) does not.

During my investigation, I have found a partial solution: set the "height" to "auto". The problem with this solution is when the page initially loads, the background color is only applied to the part of the page with actual content, rather than filling the screen. So if I have the height at "auto", the color is screwed up when the page first loads before correcting itself after the items are added, and if the height is "100%" then the color is screwed up after the items are added.

I've put together a barebones HTML file that re-creates the issue:

<!DOCTYPE html>

    <title>Layout Test</title>

Layout Test


问:
How to specify multiple author(s) / email(s) in setup.py
We wrote a small wrapper to a twitter app and published this information to http://pypi.python.org. But setup.py just contained a single field for specifying email / name of the author. How do I specify multiple contributors / email list, to the following fields since we would like this package to be listed under our names, much similar to how it shows up in http://rubygems.org.</p>
```<code>author='foo',
author_email='foo.bar@gmail.com',
</code>```

答:
Consider using flit to build the package, as this build system supports multiple authors and maintainers. Store this metadata in pyproject.toml as follows:

```<code>[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"

[project]
...
authors = [
    {name = "First1 Last1", email = "name1@foo.bar"},
    {name = "First2 Last2", email = "name2@foo.bar"},
]
maintainers = [
    {name = "First1 Last1", email = "name1@foo.bar"},
    {name = "First2 Last2", email = "name2@foo.bar"},
]
</code>```

Body:
We wrote a small wrapper to a twitter app and published this information to http://pypi.python.org. But setup.py just contained a single field for specifying email / name of the author. How do I specify multiple contributors / email list, to the following fields since we would like this package to be listed under our names, much similar to how it shows up in http://rubygems.org.

author='foo',
author_email='foo.bar@gmail.com',

Body:
Consider using flit to build the package, as this build system supports multiple authors and maintainers. Store this metadata in pyproject.toml as follows:

[build-system]
requires = ["flit_core >=3.2,<4"]
build-backend = "flit_core.buildapi"

[project]
...
authors = [
    {name = "First1 Last1", email = "name1@foo.bar"},
    {name = "First2 Last2", email = "name2@foo.bar"},
]
maintainers = [
    {name = "First1 Last1", email = "name1@foo.bar"},
    {name = "First2 Last2", email = "name2@foo.bar"},
]


问:
Pulumi and Pulumi Azure Native not recognised in VS Code
Problem

VS Code doesn't seem to have recognised either of the following python libraries + no intellisense.

import pulumi
from pulumi_azure_native import resources
from pulumi_azure_native import storage
...
```
<p>VS Code highlights them with the <strong>Import <library> could not be resolved</strong> message. Also no suggestions are shown.</p>
<p><strong>Story</strong></p>
<p>I have started creating a Pulumi dev stack and I am wanting to do this in Python. I have initialised a Pulumi project which gives me the following hierarchy:</p>
<pre class="lang-sh prettyprint-override"><code>my-project
   ├─ venv
   ├─ __main.py__
   ├─ .gitignore
   ├─ Pulumi.dev.yaml
   ├─ Pulumi.yaml
   └─ requirements.txt
</code>```

The modules already installed are pulumi and pulumi-azure-native as shown in the requirements.txt file:

```<code>pulumi>=3.0.0,<4.0.0
pulumi-azure-native>=1.0.0,<2.0.0
</code>```

I have activated the virtual environment in which the above libraries are installed.

答:
the only way I did it work was adding extraPaths to on my settings.json:

```<code>{

  "python.analysis.extraPaths": ["/Users/bcarvalho/my-pulumi-project/infrastructure/venv/lib/python3.10/site-packages"]

}
</code>```

Body:
Problem

VS Code doesn't seem to have recognised either of the following python libraries + no intellisense.

import pulumi
from pulumi_azure_native import resources
from pulumi_azure_native import storage
...

VS Code highlights them with the Import <library> could not be resolved message. Also no suggestions are shown.

Story

I have started creating a Pulumi dev stack and I am wanting to do this in Python. I have initialised a Pulumi project which gives me the following hierarchy:

my-project
   ├─ venv
   ├─ __main.py__
   ├─ .gitignore
   ├─ Pulumi.dev.yaml
   ├─ Pulumi.yaml
   └─ requirements.txt

The modules already installed are pulumi and pulumi-azure-native as shown in the requirements.txt file:

pulumi>=3.0.0,<4.0.0
pulumi-azure-native>=1.0.0,<2.0.0

I have activated the virtual environment in which the above libraries are installed.

Body:
the only way I did it work was adding extraPaths to on my settings.json:

{

  "python.analysis.extraPaths": ["/Users/bcarvalho/my-pulumi-project/infrastructure/venv/lib/python3.10/site-packages"]

}


答:
Setting the a min-height of 100% on the #root, instead of a height, seems to do the trick:</p>
```<code><!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            min-height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>
</code>```

Title: How do I get a parent div to resize when the children do?

Body:
Setting the a min-height of 100% on the #root, instead of a height, seems to do the trick:

<!DOCTYPE html>
<html>
<head>
    <title>Layout Test</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        html {
            height: 100%;
            margin: 0;
            padding: 0;
        }
        body {
            margin: 0;
            padding: 0;
            height: 100%;
        }
        #root {
            background-color: cyan;
            min-height: 100%;
        }

        #root > h1 {
            text-align: center;
        }
    </style>
</head>
<body>
    <div id="root">
        <h1>Layout Test</h1>
        <div id="container"></div>
    </div>
    <script>
        setTimeout(() => {
            const container = document.querySelector('#container');
            for (let i = 0; i < 100; i++) {
                const h1 = document.createElement('h1');
                h1.textContent = 'Hello';
                container.appendChild(h1);
            }
        }, 1000);
    </script>
</body>
</html>


问:
Getting a segmentation fault in C with unsigned long long int?
Im trying to code a decimal to binary converter in C. I have to use unsigned long long int because the largest number I have to be able to calculate is 18,446,744,073,709,551,615. On the Linux server my professor has us use, it says there is a segmentation fault, and on CLion debugger it says "Exception = EXC_BAD_ACCESS (code=2, address=0x7ff7bc694ff8)" and claims i = {unsigned long long} 18446744073708503289, which isn't right. It does this no matter what number userInput is.

What I currently have:

```<code>#include <stdio.h>

int main(void)
{
  unsigned long long int userInput;
  unsigned long long int i;
  unsigned long long int binary[] = {};

  printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
  scanf("%lld", &userInput);

  printf("\nThe binary value of %lld is: ", userInput);

  if (userInput == 0)
  {
      printf("0");
  }
  else
  {
    for (i = 0; userInput > 0; i++)
    {
        binary[i] = userInput%2;
        userInput = userInput/2;
    }
    for (i -= 1; i >= 0; i--)
    {
        printf("%lld", binary[i]);
    }
  }

  printf("\n");

  return 0;
}
</code>```

答:
One issue is that one of these loops can never terminate:

  unsigned long long int i;
  // ...
  for (i -= 1; i >= 0; i--)
  {
    printf("%lld", binary[i]);
  }
```

The variable i is unsigned and can never be negative. Therefore i >= 0 will always be true, and it will loop forever, reading memory until it reaches something that memory segmentation does not allow it to read.

Body:
Im trying to code a decimal to binary converter in C. I have to use unsigned long long int because the largest number I have to be able to calculate is 18,446,744,073,709,551,615. On the Linux server my professor has us use, it says there is a segmentation fault, and on CLion debugger it says "Exception = EXC_BAD_ACCESS (code=2, address=0x7ff7bc694ff8)" and claims i = {unsigned long long} 18446744073708503289, which isn't right. It does this no matter what number userInput is.

What I currently have:

#include <stdio.h>

int main(void)
{
  unsigned long long int userInput;
  unsigned long long int i;
  unsigned long long int binary[] = {};

  printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
  scanf("%lld", &userInput);

  printf("\nThe binary value of %lld is: ", userInput);

  if (userInput == 0)
  {
      printf("0");
  }
  else
  {
    for (i = 0; userInput > 0; i++)
    {
        binary[i] = userInput%2;
        userInput = userInput/2;
    }
    for (i -= 1; i >= 0; i--)
    {
        printf("%lld", binary[i]);
    }
  }

  printf("\n");

  return 0;
}

Body:
One issue is that one of these loops can never terminate:

  unsigned long long int i;
  // ...
  for (i -= 1; i >= 0; i--)
  {
    printf("%lld", binary[i]);
  }

The variable i is unsigned and can never be negative. Therefore i >= 0 will always be true, and it will loop forever, reading memory until it reaches something that memory segmentation does not allow it to read.


问:
Why is Core Data losing one of my values?
Inside my user object I have the following code to generate a new 'session' or continue the existing session if one exists.

Strangely it will keep other properties but just loses the 'user' property... user is in a one to many relationship with session, 1 user can have many sessions. (or will do, for the following test I am simply checking for any previous session and using it if it exists)

```<code>-(void)setupSessionStuff
{
// Create new Core Data request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];

// Create Sort Descriptors for request
NSSortDescriptor *startTimeSort = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:NO selector:nil];
[request setSortDescriptors:[NSArray arrayWithObjects:startTimeSort, nil]];
[startTimeSort release];

[request setFetchLimit:1]; // Only get the most recent session

// Execute request
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:&error];
if (results == nil) {
    // Something went horribly wrong...
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    exit(-1);
}
[request release];

Session *theSession = nil;

if ([results count] == 1) {
    NSLog(@"existing session");
    // Use existing Session
    theSession = [results objectAtIndex:0];

    NSLog(@"session.user: %@", [theSession valueForKey:@"user"]); // this is always null!

} else {
    NSLog(@"new session");
    // Create new Sesson
    theSession = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:[self managedObjectContext]];

    // Add the Session to the User
    NSLog(@"before: session.user: %@", theSession.user); // null
    theSession.user = self;
    NSLog(@"after: session.user: %@", theSession.user); // looks good
}

...

NSLog(@"before.save: session.user: %@", theSession.user); // good

// Save everything
error = nil;
if (![[self managedObjectContext] save:&error]) {
    // Something went horribly wrong...
    NSLog(@"Unresolved error: %@, %@, %@", error, [error userInfo],[error localizedDescription]);
    exit(-1);
}

NSLog(@"after.save: session.user: %@", theSession.user); // still there..
}
</code>```

Additionally I have opened up the Core Data sqlite file and examined with SQLite Manager. It looks like the relationship has been correctly saved, as I can see the userID stored in the session table.

-

Just added this at the start of my method as another test.

```<code>NSSet *set = self.session;

for(Session *sess in set) {
    NSLog(@"startTime %@", sess.startTime);
    NSLog(@"user %@", sess.user);

}
</code>```

Strangely enough the user is set in this case!? So set here then not set a few lines later when I do the fetch request... ?

-

In response to feedback below

Have added this code after assigning session.user = self and both return the expected output. So it does look like the problem is with the subsequent fetch.

```<code>NSLog(@"self.session: %@", self.session);
NSLog(@"self.session: %@", [self valueForKey:@"session"]);
</code>```

Also I agree that accessing my session's through self.session will let me work around my issue, but it doesn't solve what is going on here.
In other places I surely won't be able to walk from one entity to the other so need to confidence the fetch is going to pull everything in correctly.

答:
Well I found the problem and solved my issue...

After examining the memory address of my session entity I noticing that it was changing between runs. Investigating further I discovered that where I had been testing some code earlier in another class, creating a new session entity, but not saving it, well, it was being saved after all - when I issued the save in my code above!

Body:
Inside my user object I have the following code to generate a new 'session' or continue the existing session if one exists.

Strangely it will keep other properties but just loses the 'user' property... user is in a one to many relationship with session, 1 user can have many sessions. (or will do, for the following test I am simply checking for any previous session and using it if it exists)

-(void)setupSessionStuff
{
// Create new Core Data request
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Session" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];

// Create Sort Descriptors for request
NSSortDescriptor *startTimeSort = [[NSSortDescriptor alloc] initWithKey:@"startTime" ascending:NO selector:nil];
[request setSortDescriptors:[NSArray arrayWithObjects:startTimeSort, nil]];
[startTimeSort release];

[request setFetchLimit:1]; // Only get the most recent session

// Execute request
NSError *error = nil;
NSArray *results = [[self managedObjectContext] executeFetchRequest:request error:&error];
if (results == nil) {
    // Something went horribly wrong...
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    exit(-1);
}
[request release];

Session *theSession = nil;

if ([results count] == 1) {
    NSLog(@"existing session");
    // Use existing Session
    theSession = [results objectAtIndex:0];

    NSLog(@"session.user: %@", [theSession valueForKey:@"user"]); // this is always null!

} else {
    NSLog(@"new session");
    // Create new Sesson
    theSession = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:[self managedObjectContext]];

    // Add the Session to the User
    NSLog(@"before: session.user: %@", theSession.user); // null
    theSession.user = self;
    NSLog(@"after: session.user: %@", theSession.user); // looks good
}

...

NSLog(@"before.save: session.user: %@", theSession.user); // good

// Save everything
error = nil;
if (![[self managedObjectContext] save:&error]) {
    // Something went horribly wrong...
    NSLog(@"Unresolved error: %@, %@, %@", error, [error userInfo],[error localizedDescription]);
    exit(-1);
}

NSLog(@"after.save: session.user: %@", theSession.user); // still there..
}

Additionally I have opened up the Core Data sqlite file and examined with SQLite Manager. It looks like the relationship has been correctly saved, as I can see the userID stored in the session table.

-

Just added this at the start of my method as another test.

NSSet *set = self.session;

for(Session *sess in set) {
    NSLog(@"startTime %@", sess.startTime);
    NSLog(@"user %@", sess.user);

}

Strangely enough the user is set in this case!? So set here then not set a few lines later when I do the fetch request... ?

-

In response to feedback below

Have added this code after assigning session.user = self and both return the expected output. So it does look like the problem is with the subsequent fetch.

NSLog(@"self.session: %@", self.session);
NSLog(@"self.session: %@", [self valueForKey:@"session"]);

Also I agree that accessing my session's through self.session will let me work around my issue, but it doesn't solve what is going on here.
In other places I surely won't be able to walk from one entity to the other so need to confidence the fetch is going to pull everything in correctly.


问:
port 5432 is already in use postgres mac
When installing Postgresql 11 I got an error. I did the lesson right. Searched Google but didn’t find. I'm not trying to run different versions of postgresql, I'm just trying to install it.

答:
```<code>$ sudo lsof -i :5432
$ sudo pkill -u postgres
</code>```

This is what fixed it for me, the lsof -i :5432 didn't show me anything, but after running the second command, I could finally use port 5432.

Body:
$ sudo lsof -i :5432
$ sudo pkill -u postgres

This is what fixed it for me, the lsof -i :5432 didn't show me anything, but after running the second command, I could finally use port 5432.


问:
Can I import a mysql dump to a laravel migration?
I have a complete database and need to create migration. I guess there must be a way to do it from a dump but not sure. Is there any way automatically or at least easier to do this task?</p>

答:
If you can dump to a CSV:
An alternative for some generic data tables (Countries, States, Postal Codes), not via migrations but via seeders. Although you could do it the same way in a migration file.

In your seeder file:

```<code>    public function run()
    {
        $this->insertFromCsvFile('countries', 'path/to/countries.csv');
        $this->insertFromCsvFile('states', 'path/to/states.csv');
        $this->insertFromCsvFile('postal_codes', 'path/to/postal_codes.csv');
    }

    private function insertFromCsvFile($tableName, $filePath)
    {
        if( !file_exists($filePath) ){
            echo 'File Not Found: '.$filePath."\r\n";
            return;
        }
        $headers = $rows = [];
        $file = fopen( $filePath, 'r' );
        while( ( $line = fgetcsv( $file ) ) !== false ){

            // The first row should be header values that match column names.
            if( empty( $headers ) ){
                $headers = explode( ',', implode( ',', $line ) );
                continue;
            }

            $row = array_combine( $headers, $line );
            foreach( $row as &$val ) if( $val === 'NULL' ) $val = null;
            $rows[] = $row;

            // Adjust based on memory constraints.
            if( count($rows) === 500 ){
                DB::table( $tableName )->insert($rows);
                $rows = [];
            }
        }
        fclose( $filePath );

        if( count($rows) ) DB::table( $tableName )->insert($rows);
    }
</code>```

Run the seeder: php artisan db:seed --class=GenericTableSeeder

Body:
If you can dump to a CSV:
An alternative for some generic data tables (Countries, States, Postal Codes), not via migrations but via seeders. Although you could do it the same way in a migration file.

In your seeder file:

    public function run()
    {
        $this->insertFromCsvFile('countries', 'path/to/countries.csv');
        $this->insertFromCsvFile('states', 'path/to/states.csv');
        $this->insertFromCsvFile('postal_codes', 'path/to/postal_codes.csv');
    }

    private function insertFromCsvFile($tableName, $filePath)
    {
        if( !file_exists($filePath) ){
            echo 'File Not Found: '.$filePath."\r\n";
            return;
        }
        $headers = $rows = [];
        $file = fopen( $filePath, 'r' );
        while( ( $line = fgetcsv( $file ) ) !== false ){

            // The first row should be header values that match column names.
            if( empty( $headers ) ){
                $headers = explode( ',', implode( ',', $line ) );
                continue;
            }

            $row = array_combine( $headers, $line );
            foreach( $row as &$val ) if( $val === 'NULL' ) $val = null;
            $rows[] = $row;

            // Adjust based on memory constraints.
            if( count($rows) === 500 ){
                DB::table( $tableName )->insert($rows);
                $rows = [];
            }
        }
        fclose( $filePath );

        if( count($rows) ) DB::table( $tableName )->insert($rows);
    }

Run the seeder: php artisan db:seed --class=GenericTableSeeder


问:
Remove Everything Except Specific Words From Text
I'm working with twitter data using R. I have a large data frame where I need to remove everything from the text except from specific information. Specifically, I want to remove everything except from statistical information. So basically, I want to keep numbers as well as words such as "half", "quarter", "third". Also is there a way to also keep symbols such as "£", "%", "$"?

I have been using "gsub" to try and do this:

df$text <- as.numeric(gsub(".*?([0-9]+).*", "\\1", df$text))

This code removes everything except from numbers, however information regarding any words was gone. I'm struggling to figure out how I would be able to keep specific words within the text as well as the numbers.

Here's a mock data frame:

text <- c("here is some text with stuff inside that i dont need but also some that i do, here is a word half and quarter also 99 is too old for lego", "heres another one with numbers 132 1244 5950 303 2022 and one and a half", "plz help me with code i am struggling")

df <- data.frame(text)

I would like to be be able to end up with data frame outputting:

Also, I've included a N/A table in the picture because some of my observations will have neither a number or the specific words. The goal of this code is really just to be able to say that these observations contain some form of statistical language and these other observations do not.

Any help would be massively appreciate and I'll do my best to answer any Q's!

答:
You can capture what you need to keep and then match and consume any character to replace with a backreference to the group value:

text <- c("here is some text with stuff inside that i dont need but also some that i do, here is a word half and quarter also 99 is too old for lego", "heres another one with numbers 132 1244 5950 303 2022 and one and a half", "plz help me with code i am struggling")
gsub("(half|quarter|third|\\d+)|.", "\\1", text)
```
<p>See the regex demo. <em>Details</em>:</p>
<ul>
<li><code>(half|quarter|third|\d+)</code> - a <code>half</code>, <code>quarter</code> or <code>third</code> word, or one or more digits</li>
<li><code>|</code> - or</li>
<li><code>.</code> - any single char.</li>
</ul>
<p>The <code>\1</code> in the replacement pattern puts the captured vaue back into the resulting string.</p>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>[1] "halfquarter99"          "132124459503032022half" ""
</code>```

Body:
You can capture what you need to keep and then match and consume any character to replace with a backreference to the group value:

text <- c("here is some text with stuff inside that i dont need but also some that i do, here is a word half and quarter also 99 is too old for lego", "heres another one with numbers 132 1244 5950 303 2022 and one and a half", "plz help me with code i am struggling")
gsub("(half|quarter|third|\\d+)|.", "\\1", text)

See the regex demo. Details:

(half|quarter|third|\d+) - a half, quarter or third word, or one or more digits

| - or

. - any single char.

The \1 in the replacement pattern puts the captured vaue back into the resulting string.

Output:

[1] "halfquarter99"          "132124459503032022half" ""