问:
How to solve the error A second operation started on this context before a previous operation completed
I'm implementing asp.net core project. In my controller class, create method, At first I insert a record in table APIApplicantHistory as a log history and then I do some calculation to get a value and after that I return back to the create method and and create a new record and insert it into APIApplicant table. For doing that, I wrote some code like below:

```<code> namespace CSDDashboard.Controllers
 {
   public class ApiapplicantsController : Controller
{
    private readonly CSSDDashboardContext _context;

    public ApiapplicantsController(CSSDDashboardContext context)
    {
        _context = context;
    }

   public async Task<IActionResult> Create([Bind("Id,ApiRequestDate,ApiRequestNo,Apiid,ApplicantId,GateId,LastRequestStatus,NocRequestDate,NocRequestNo,Url,Description,IsDeleted")] Apiapplicant apiapplicant)
    {
        ApiApplicantDto dto = new ApiApplicantDto();

        if (ModelState.IsValid)
        {
            //   Apiapplicant myapiapplicant = _context.Apiapplicant.LastOrDefault<Apiapplicant>();
            Apiapplicant myapiapplicant = _context.Apiapplicant.ToArray().Last();
            int temp = myapiapplicant.Id + 1;
            int calcApiApplicantHistoryId = APIApplicantHistoryLog(temp);

            var api = _context.Api.Single(p => p.Id == apiapplicant.Apiid);
            var gate = _context.Gate.Single(p => p.Id == apiapplicant.GateId);
            var applicant = _context.Applicant.Single(p => p.ApplicantId == apiapplicant.ApplicantId);
            //var apiapplicanthistory = _context.ApiApplicantHistory.Single(p => p.Id == apiapplicant.LastRequestStatus);

            dto.apiId = api.Id;
            dto.gateId = gate.Id;
            dto.applicantId = applicant.ApplicantId;

            using (var _context = new CSSDDashboardContext())
            {

                _context.Set<Apiapplicant>().Add(new Apiapplicant
                {

                    Apiid = dto.apiId,
                    GateId = dto.gateId,
                    ApplicantId = dto.applicantId,
                    LastRequestStatus = calcApiApplicantHistoryId,

                    ApiRequestDate = apiapplicant.ApiRequestDate,
                    ApiRequestNo = apiapplicant.ApiRequestNo,
                    NocRequestDate = apiapplicant.NocRequestDate,
                    NocRequestNo = apiapplicant.NocRequestNo,
                    Url = apiapplicant.Url,
                    Description = apiapplicant.Description,
                    IsDeleted = false
                });
                 await _context.SaveChangesAsync();
             };

            return RedirectToAction(nameof(Index));
        }
        ViewData["Apiid"] = new SelectList(_context.Api, "Id", "Name", apiapplicant.Apiid);
        ViewData["ApplicantId"] = new SelectList(_context.Applicant, "ApplicantId", "Name", apiapplicant.ApplicantId);
        ViewData["GateId"] = new SelectList(_context.Gate, "Id", "Name", apiapplicant.GateId);
        ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey=="sentResponseType").ToList(), "ID", "name", apiapplicant.LastRequestStatusNavigation.SentResponseType);
        ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.UnconfirmedReason);
        ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.LastReqStatus);
        return View(apiapplicant);
    }

   private  int APIApplicantHistoryLog(int myAPIApplicantId)
    {
        APIApplicantHistoryDto mydto = new APIApplicantHistoryDto();

      //  var apiapplicantt = _context.ApiApplicantHistory.Single(p => p.ApiApplicantId == myAPIApplicantId);
     //   mydto.APIApplicantHistoryId = apiapplicantt.Id;

        using (var _context = new CSSDDashboardContext())
        //     using (var transaction = _context.Database.BeginTransaction())
        {

            _context.Set<ApiApplicantHistory>().Add(new ApiApplicantHistory
            {

                //   ApiApplicantId = mydto.APIApplicantHistoryId,
                ApiApplicantId = myAPIApplicantId,
                Date = null,
                SentResponseType = 0,
                UnconfirmedReason = 0,
                LastReqStatus = 0,
                Description = "",
                IdDeleted = false   // This field should be totally omited from SQL server
            }) ;
             _context.SaveChangesAsync();

            var myArrayList = new List<int>();

            var result = from x in _context.ApiApplicantHistory where x.ApiApplicantId == myAPIApplicantId
                         select new { x.Id };

            foreach (var i in result)
                myArrayList.Add(i.Id);

            return myArrayList.Max(); ;

        }
    }
   }
</code>```

My problem is, after running the application and create a new record in APIApplicant, the below error is shown to me:

An unhandled exception occurred while processing the request.
  InvalidOperationException: A second operation started on this context
  before a previous operation completed. This is usually caused by
  different threads using the same instance of DbContext. For more
  information on how to avoid threading issues with DbContext, see
  https://go.microsoft.com/fwlink/?linkid=2097913.

I appreciate if any one tells me where do I make a mistake?

答:
If you click on the link from the exception message: https://go.microsoft.com/fwlink/?linkid=2097913 it seems straight forward:

Entity Framework Core does not support multiple parallel operations
  being run on the same DbContext instance. This includes both parallel
  execution of async queries and any explicit concurrent use from
  multiple threads. Therefore, always await async calls immediately, or
  use separate DbContext instances for operations that execute in
  parallel.

If you check your APIApplicantHistoryLog method you are not awaiting your _context.SaveChangesAsync(); method call.

Body:
I'm implementing asp.net core project. In my controller class, create method, At first I insert a record in table APIApplicantHistory as a log history and then I do some calculation to get a value and after that I return back to the create method and and create a new record and insert it into APIApplicant table. For doing that, I wrote some code like below:

 namespace CSDDashboard.Controllers
 {
   public class ApiapplicantsController : Controller
{
    private readonly CSSDDashboardContext _context;

    public ApiapplicantsController(CSSDDashboardContext context)
    {
        _context = context;
    }

   public async Task<IActionResult> Create([Bind("Id,ApiRequestDate,ApiRequestNo,Apiid,ApplicantId,GateId,LastRequestStatus,NocRequestDate,NocRequestNo,Url,Description,IsDeleted")] Apiapplicant apiapplicant)
    {
        ApiApplicantDto dto = new ApiApplicantDto();

        if (ModelState.IsValid)
        {
            //   Apiapplicant myapiapplicant = _context.Apiapplicant.LastOrDefault<Apiapplicant>();
            Apiapplicant myapiapplicant = _context.Apiapplicant.ToArray().Last();
            int temp = myapiapplicant.Id + 1;
            int calcApiApplicantHistoryId = APIApplicantHistoryLog(temp);

            var api = _context.Api.Single(p => p.Id == apiapplicant.Apiid);
            var gate = _context.Gate.Single(p => p.Id == apiapplicant.GateId);
            var applicant = _context.Applicant.Single(p => p.ApplicantId == apiapplicant.ApplicantId);
            //var apiapplicanthistory = _context.ApiApplicantHistory.Single(p => p.Id == apiapplicant.LastRequestStatus);

            dto.apiId = api.Id;
            dto.gateId = gate.Id;
            dto.applicantId = applicant.ApplicantId;

            using (var _context = new CSSDDashboardContext())
            {

                _context.Set<Apiapplicant>().Add(new Apiapplicant
                {

                    Apiid = dto.apiId,
                    GateId = dto.gateId,
                    ApplicantId = dto.applicantId,
                    LastRequestStatus = calcApiApplicantHistoryId,

                    ApiRequestDate = apiapplicant.ApiRequestDate,
                    ApiRequestNo = apiapplicant.ApiRequestNo,
                    NocRequestDate = apiapplicant.NocRequestDate,
                    NocRequestNo = apiapplicant.NocRequestNo,
                    Url = apiapplicant.Url,
                    Description = apiapplicant.Description,
                    IsDeleted = false
                });
                 await _context.SaveChangesAsync();
             };

            return RedirectToAction(nameof(Index));
        }
        ViewData["Apiid"] = new SelectList(_context.Api, "Id", "Name", apiapplicant.Apiid);
        ViewData["ApplicantId"] = new SelectList(_context.Applicant, "ApplicantId", "Name", apiapplicant.ApplicantId);
        ViewData["GateId"] = new SelectList(_context.Gate, "Id", "Name", apiapplicant.GateId);
        ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey=="sentResponseType").ToList(), "ID", "name", apiapplicant.LastRequestStatusNavigation.SentResponseType);
        ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.UnconfirmedReason);
        ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "Id", "name", apiapplicant.LastRequestStatusNavigation.LastReqStatus);
        return View(apiapplicant);
    }

   private  int APIApplicantHistoryLog(int myAPIApplicantId)
    {
        APIApplicantHistoryDto mydto = new APIApplicantHistoryDto();

      //  var apiapplicantt = _context.ApiApplicantHistory.Single(p => p.ApiApplicantId == myAPIApplicantId);
     //   mydto.APIApplicantHistoryId = apiapplicantt.Id;

        using (var _context = new CSSDDashboardContext())
        //     using (var transaction = _context.Database.BeginTransaction())
        {

            _context.Set<ApiApplicantHistory>().Add(new ApiApplicantHistory
            {

                //   ApiApplicantId = mydto.APIApplicantHistoryId,
                ApiApplicantId = myAPIApplicantId,
                Date = null,
                SentResponseType = 0,
                UnconfirmedReason = 0,
                LastReqStatus = 0,
                Description = "",
                IdDeleted = false   // This field should be totally omited from SQL server
            }) ;
             _context.SaveChangesAsync();

            var myArrayList = new List<int>();

            var result = from x in _context.ApiApplicantHistory where x.ApiApplicantId == myAPIApplicantId
                         select new { x.Id };

            foreach (var i in result)
                myArrayList.Add(i.Id);

            return myArrayList.Max(); ;

        }
    }
   }

My problem is, after running the application and create a new record in APIApplicant, the below error is shown to me:

An unhandled exception occurred while processing the request.
  InvalidOperationException: A second operation started on this context
  before a previous operation completed. This is usually caused by
  different threads using the same instance of DbContext. For more
  information on how to avoid threading issues with DbContext, see
  https://go.microsoft.com/fwlink/?linkid=2097913.

I appreciate if any one tells me where do I make a mistake?


来源: stackexchange

问:
How to set up node socket.io
I'm attempting to complete this tutorial and I'm getting this error in the browser console.

```<code>index.js:16 Uncaught TypeError: this.io.on is not a function
    at index.js:16
</code>```

This is the full contents of my index.js.

```<code>navigator.getUserMedia(
    { video: true, audio: true },
    stream => {
      const localVideo = document.getElementById("local-video");
      if (localVideo) {
        localVideo.srcObject = stream;
      }
    },
    error => {
      console.warn(error.message);
    }
   );

   this.io.on("connection", socket => {
    const existingSocket = this.activeSockets.find(
      existingSocket => existingSocket === socket.id
    );

    if (!existingSocket) {
      this.activeSockets.push(socket.id);

      socket.emit("update-user-list", {
        users: this.activeSockets.filter(
          existingSocket => existingSocket !== socket.id
        )
      });

      socket.broadcast.emit("update-user-list", {
        users: [socket.id]
      });
    }
  })
</code>```

What am I missing? I know that 'this' should refer to some enclosing object but what?

答:
Checkout tutorial files list

The part you are referrring to is in socket-connection.ts file, not index.js as author refers.

Or it may be a typescript abrakadabra :)

P.S. and you should also remember that "this" construct is always inside a function (but not in arrow function).

ContentLicense: CC BY-SA 4.0

Title: How to set up node socket.io

Body:
I'm attempting to complete this tutorial and I'm getting this error in the browser console.

index.js:16 Uncaught TypeError: this.io.on is not a function
    at index.js:16

This is the full contents of my index.js.

navigator.getUserMedia(
    { video: true, audio: true },
    stream => {
      const localVideo = document.getElementById("local-video");
      if (localVideo) {
        localVideo.srcObject = stream;
      }
    },
    error => {
      console.warn(error.message);
    }
   );

   this.io.on("connection", socket => {
    const existingSocket = this.activeSockets.find(
      existingSocket => existingSocket === socket.id
    );

    if (!existingSocket) {
      this.activeSockets.push(socket.id);

      socket.emit("update-user-list", {
        users: this.activeSockets.filter(
          existingSocket => existingSocket !== socket.id
        )
      });

      socket.broadcast.emit("update-user-list", {
        users: [socket.id]
      });
    }
  })

What am I missing? I know that 'this' should refer to some enclosing object but what?


问:
Why is my program returning a garbage value when k == 0 in the for-loop?
This is a simple C++ program which computes f(x) using a formula for a fixed number of values between 2 given numbers.

There seems to be some problem when k = 0 in the for loop. It is returning a garbage value.

Can anyone tell me why?

Any help is highly appreciated. Thanks in advance.

```<code>#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main ()
{

  int const POINTS = 21;
  double const PI = 3.1416;
  double min, max, increment, dataPoints[21];

  cout << "Enter max value: ";
  cin >> max;

  cout << "Enter min value: ";
  cin >> min;

  increment = (max - min) / (POINTS - 1);

  cout << setw (20) << "X-Value" << "|";
  cout << setw (20) << "Y-Value" << endl;

  double k;
  int l;

  for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
    {
      dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1 / 64) * PI * cos (24.44 * k);
      cout << setw (20) << k << setw (20) << dataPoints[l] << endl;
    }

}

</code>```

Output:

```<code>Enter max value: 4
Enter min value: -4
             X-Value|             Y-Value
                  -4            0.164018
                -3.6          -0.0507715
                -3.2          -0.0881608
                -2.8            0.182492
                -2.4           -0.184497
                  -2           0.0931637
                -1.6           0.0453027
                -1.2            -0.16085
                -0.8            0.195021
                -0.4           -0.130529
       -5.55112e-016       -6.57901e-016
                 0.4            0.130529
                 0.8           -0.195021
                 1.2             0.16085
                 1.6          -0.0453027
                   2          -0.0931637
                 2.4            0.184497
                 2.8           -0.182492
                 3.2           0.0881608
                 3.6           0.0507715
                   4           -0.164018

Process returned 0 (0x0)   execution time : 3.634 s
Press any key to continue.
</code>```

答:
One problem problem lies in the code (1 / 64) ... because you have put this expression in brackets. It is, thus, integer division and, as such, will always have the value of zero.

Try this, instead:

    dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1.0 / 64) * PI * cos (24.44 * k);
```

<p>There is also a problem in the way you have expressed the 'test' condition in your <code>for</code> loop - the comma operator here will, effectively, ignore the first part of the expression:</p>

<pre class="lang-cpp prettyprint-override"><code>for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
</code>```

For safety, when you want both conditions to be tested, use the && operator:

for (k = min, l = 0; l < POINTS && k <= max; l++, k += increment) {
```

Lastly, your actual question:

There seems to be some problem when k = 0 in the for loop. It is
  returning a garbage value.

No, it's not! The floating-point operations you perform on the k variable (i.e. k += increment, on each loop) are not precise: what you think will be 0.4 + (-0.4) will actually be 'nearly' '0.4' - 'nearly' '0.4'; as such, the value you get (my system gives -5.55112e-16) is a 'reasonable approximation' to zero, given the ranges of the numbers that you've used (and the accumulated 'errors' in the previous loops).

Feel free to ask for further clarification and/or explanation.

Body:
This is a simple C++ program which computes f(x) using a formula for a fixed number of values between 2 given numbers.

There seems to be some problem when k = 0 in the for loop. It is returning a garbage value.

Can anyone tell me why?

Any help is highly appreciated. Thanks in advance.

#include<iostream>
#include<iomanip>
#include<cmath>

using namespace std;

int main ()
{

  int const POINTS = 21;
  double const PI = 3.1416;
  double min, max, increment, dataPoints[21];

  cout << "Enter max value: ";
  cin >> max;

  cout << "Enter min value: ";
  cin >> min;

  increment = (max - min) / (POINTS - 1);

  cout << setw (20) << "X-Value" << "|";
  cout << setw (20) << "Y-Value" << endl;

  double k;
  int l;

  for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)
    {
      dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1 / 64) * PI * cos (24.44 * k);
      cout << setw (20) << k << setw (20) << dataPoints[l] << endl;
    }

}

Output:

Enter max value: 4
Enter min value: -4
             X-Value|             Y-Value
                  -4            0.164018
                -3.6          -0.0507715
                -3.2          -0.0881608
                -2.8            0.182492
                -2.4           -0.184497
                  -2           0.0931637
                -1.6           0.0453027
                -1.2            -0.16085
                -0.8            0.195021
                -0.4           -0.130529
       -5.55112e-016       -6.57901e-016
                 0.4            0.130529
                 0.8           -0.195021
                 1.2             0.16085
                 1.6          -0.0453027
                   2          -0.0931637
                 2.4            0.184497
                 2.8           -0.182492
                 3.2           0.0881608
                 3.6           0.0507715
                   4           -0.164018

Process returned 0 (0x0)   execution time : 3.634 s
Press any key to continue.

Body:
One problem problem lies in the code (1 / 64) ... because you have put this expression in brackets. It is, thus, integer division and, as such, will always have the value of zero.

Try this, instead:

    dataPoints[l] = (PI / 16) * sin (6.036 * k) + (1.0 / 64) * PI * cos (24.44 * k);

There is also a problem in the way you have expressed the 'test' condition in your for loop - the comma operator here will, effectively, ignore the first part of the expression:

for (k = min, l = 0; l < POINTS, k <= max; l++, k += increment)

For safety, when you want both conditions to be tested, use the && operator:

for (k = min, l = 0; l < POINTS && k <= max; l++, k += increment) {

Lastly, your actual question:

There seems to be some problem when k = 0 in the for loop. It is
  returning a garbage value.

No, it's not! The floating-point operations you perform on the k variable (i.e. k += increment, on each loop) are not precise: what you think will be 0.4 + (-0.4) will actually be 'nearly' '0.4' - 'nearly' '0.4'; as such, the value you get (my system gives -5.55112e-16) is a 'reasonable approximation' to zero, given the ranges of the numbers that you've used (and the accumulated 'errors' in the previous loops).

Feel free to ask for further clarification and/or explanation.


问:
How to parse an Xml having two tags with same name
I am using SAX parser to get a data from XML. unfortunately i am having two tags with same name example <tags> <sametag>Abc</sametag> <sametag>Def</sametag ></tags>. so whenever i am parsing the file i only getting ABC the same tag which contains different data will never parse. if anyone having idea for to parse same name tags pls guide me to solve.

答: Maybe this post could help you http://codeofaninja.blogspot.com/2011/05/android-how-to-parse-xml-file-and.html</p>

ContentLicense: CC BY-SA 3.0


问:
cannot change the main title and x, y labels for plot() of boot() result
I am new to R but have had some practice labelling plots so I thought this would be the same for the result from a bootstrap using boot().

```<code>#question 7
library(boot)
# function to obtain mean of x
fc <- function(x, indices){
  dt <- x[indices]
  c(mean(dt))
}
set.seed(123)
mybootstrap <- boot(x, fc, R=1000)
head(mybootstrap)
plot(mybootstrap, index=1,main="Boostrap mean of x", xlab="mean", ylab="density")

</code>```

But actually it is giving me the generic "Histogram of t" and xlab of "t*" rather than what I wrote in the brackets to specify these things.  Why is this so?

答:
It's not easy to adjust the plot settings in boot.  Best is to pull out t and use plot with freq=F to get a density plot:

```<code> hist(mybootstrap$t, freq = FALSE, breaks = 50,
     main="Boostrap mean of x", xlab="mean", ylab="density")
</code>```

Body:
I am new to R but have had some practice labelling plots so I thought this would be the same for the result from a bootstrap using boot().

#question 7
library(boot)
# function to obtain mean of x
fc <- function(x, indices){
  dt <- x[indices]
  c(mean(dt))
}
set.seed(123)
mybootstrap <- boot(x, fc, R=1000)
head(mybootstrap)
plot(mybootstrap, index=1,main="Boostrap mean of x", xlab="mean", ylab="density")

But actually it is giving me the generic "Histogram of t" and xlab of "t*" rather than what I wrote in the brackets to specify these things.  Why is this so?

Body:
It's not easy to adjust the plot settings in boot.  Best is to pull out t and use plot with freq=F to get a density plot:

 hist(mybootstrap$t, freq = FALSE, breaks = 50,
     main="Boostrap mean of x", xlab="mean", ylab="density")


问:
Insert template without overriding childs in Thymeleaf (default head template)
I am used to th:insert and th:replace but I need a way to include a fragment in a header without overriding other tags inside head.

I tried this, but the home.css head gets completely overwritten:

home.html:

```<code><head th:include="fragments/head :: genericHead">
    <link rel="stylesheet" href="home.css">
</head>
</code>```

Head template:

```<code><head th:fragment="genericHead">
    <link rel="stylesheet" href="common.css">
</head>
</code>```

I want some way to do a th:add or similar in order to have both links as childs of head and which results in something like this:

```<code><head>
    <link rel="stylesheet" href="common.css">
    <link rel="stylesheet" href="home.css">
</head>
</code>```

答:
You can use the th:block together with th:include / th:replace

Your home.html would look like:

```<code><head>
    <th:block th:include="fragments/head :: genericHead"></th:block>
    <link rel="stylesheet" href="../static/home.css">
</head>
</code>```

And the fragment would look exactly the same:

```<code><head th:fragment="genericHead">
    <link rel="stylesheet" href="common.css">
</head >
</code>```

The th:block will execute the include and then it will desappear (so it can be a include or also a replace, it doesn't matter after all) leaving us with the content of the fragment tag.

Body:
I am used to th:insert and th:replace but I need a way to include a fragment in a header without overriding other tags inside head.

I tried this, but the home.css head gets completely overwritten:

home.html:

    <link rel="stylesheet" href="home.css">

Head template:

    <link rel="stylesheet" href="common.css">

I want some way to do a th:add or similar in order to have both links as childs of head and which results in something like this:

    <link rel="stylesheet" href="common.css">
    <link rel="stylesheet" href="home.css">

Body:
You can use the th:block together with th:include / th:replace

Your home.html would look like:

<head>
    <th:block th:include="fragments/head :: genericHead"></th:block>
    <link rel="stylesheet" href="../static/home.css">
</head>

And the fragment would look exactly the same:

<head th:fragment="genericHead">
    <link rel="stylesheet" href="common.css">
</head >

The th:block will execute the include and then it will desappear (so it can be a include or also a replace, it doesn't matter after all) leaving us with the content of the fragment tag.


问:
Split Wav File in VB6
I need help to fix the attached VB6 code which is supposed to take an audio file and split it into 5 equal parts.

This is the way this code should work:

The first part starts from the beginning of Track.wav file.
The second part starts from where the first split part ended.
The third part starts from where the second split part ended.
The fourth part starts from where the third split part ended.
The fifth part starts from where the fourth split part ended.

Essentially each of the file parts is a continuation of the previous part of file split. After the split I have 1.wav, 2.wav, 3.wav. 4.wav and 5.wav all derived from a Track.wav file. The code attached already splits the file into five equal parts but the problem is that all the audio parts are the same as the first part instead of a continuation.

I need help to get this fixed to work as it should in VB6 (not .NET). I'd be grateful for your assistance with this.

```<code>Dim Wavlength As Integer

Private Sub Command1_Click()

On Error Resume Next

DoFirstWav

Me.SetFocus

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

FirstWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FirstWav & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim SecondWav As Integer

SecondWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, SecondWav & "0000")
Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ThirdWav As Integer

ThirdWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, ThirdWav & "0000")
Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FourthWav As Integer

FourthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FourthWav & "0000")
Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FifthWav As Integer

FifthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FifthWav & "0000")
Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

MsgBox "Wav Split Successfully", vbInformation

End

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt
Close #1

Wavlength = FileSize / (SampleRate * BytesPerSample)

End Sub
</code>```

答:
This is the working code. I'm sure someone may need something like this in future, si thought I'd post it here.</p>

```<code>
Dim Wavlength As Long
Dim PartLength As Integer
Dim WavHeader() As Byte

Private Sub Command1_Click()

On Error Resume Next

WavHeader = ReadFile(App.Path & "\Track.wav", 1, 320)

PartLength = Wavlength / 6 - 2

DoFirstWav

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

ByteData = ReadFile(App.Path & "\Track.wav", 1, PartLength & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim SecondWav As Integer

SecondWav = PartLength

ByteRead = ReadFile(App.Path & "\Track.wav", SecondWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim ThirdWav As Integer

ThirdWav = PartLength * 2 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", ThirdWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim FourthWav As Integer

FourthWav = PartLength * 3 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", FourthWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim FifthWav As Integer

FifthWav = PartLength * 4 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", FifthWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt

Close #1

Wavlength = FileSize \ (SampleRate * BytesPerSample)

Debug.Print "Wavlength"; Wavlength

End Sub
</code>```

Title: Split Wav File in VB6

Body:
I need help to fix the attached VB6 code which is supposed to take an audio file and split it into 5 equal parts.

This is the way this code should work:

The first part starts from the beginning of Track.wav file.
The second part starts from where the first split part ended.
The third part starts from where the second split part ended.
The fourth part starts from where the third split part ended.
The fifth part starts from where the fourth split part ended.

Essentially each of the file parts is a continuation of the previous part of file split. After the split I have 1.wav, 2.wav, 3.wav. 4.wav and 5.wav all derived from a Track.wav file. The code attached already splits the file into five equal parts but the problem is that all the audio parts are the same as the first part instead of a continuation.

I need help to get this fixed to work as it should in VB6 (not .NET). I'd be grateful for your assistance with this.

Dim Wavlength As Integer

Private Sub Command1_Click()

On Error Resume Next

DoFirstWav

Me.SetFocus

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

FirstWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FirstWav & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim SecondWav As Integer

SecondWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, SecondWav & "0000")
Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ThirdWav As Integer

ThirdWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, ThirdWav & "0000")
Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FourthWav As Integer

FourthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FourthWav & "0000")
Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FifthWav As Integer

FifthWav = Wavlength / 5

ByteData = ReadFile(App.Path & "\Track.wav", 1, FifthWav & "0000")
Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

MsgBox "Wav Split Successfully", vbInformation

End

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt
Close #1

Wavlength = FileSize / (SampleRate * BytesPerSample)

End Sub

Body:
This is the working code. I'm sure someone may need something like this in future, si thought I'd post it here.

Dim Wavlength As Long
Dim PartLength As Integer
Dim WavHeader() As Byte

Private Sub Command1_Click()

On Error Resume Next

WavHeader = ReadFile(App.Path & "\Track.wav", 1, 320)

PartLength = Wavlength / 6 - 2

DoFirstWav

End Sub

Private Sub DoFirstWav()

On Error Resume Next

Dim ByteData() As Byte
Dim FirstWav As Integer

ByteData = ReadFile(App.Path & "\Track.wav", 1, PartLength & "0000")
Call WriteFile(App.Path & "\Segments\1.wav", ByteData)

DoSecondWav

End Sub

Private Sub DoSecondWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim SecondWav As Integer

SecondWav = PartLength

ByteRead = ReadFile(App.Path & "\Track.wav", SecondWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\2.wav", ByteData)

DoThirdWav

End Sub

Private Sub DoThirdWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim ThirdWav As Integer

ThirdWav = PartLength * 2 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", ThirdWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\3.wav", ByteData)

DoFourthWav

End Sub

Private Sub DoFourthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim FourthWav As Integer

FourthWav = PartLength * 3 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", FourthWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\4.wav", ByteData)

DoFifthWav

End Sub

Private Sub DoFifthWav()

On Error Resume Next

Dim ByteData() As Byte
Dim ByteRead() As Byte
Dim FifthWav As Integer

FifthWav = PartLength * 4 + 1

ByteRead = ReadFile(App.Path & "\Track.wav", FifthWav & "0000", PartLength & "0000")

ReDim ByteData(UBound(WavHeader) + UBound(ByteRead)) As Byte

For i = 0 To UBound(WavHeader)
    ByteData(i) = WavHeader(i)
Next i

For i = 0 To UBound(ByteRead)
    ByteData(UBound(WavHeader) + i) = ByteRead(i)
Next i

Call WriteFile(App.Path & "\Segments\5.wav", ByteData)

End Sub

Private Function ReadFile(ByVal strFileName As String, Optional ByVal lngStartPos As Long = 1, Optional ByVal lngFileSize As Long = -1) As Byte()

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

Open strFileName For Binary As #FilNum
    If lngFileSize = -1 Then
        ReDim ReadFile(LOF(FilNum) - lngStartPos)
        Else
        ReDim ReadFile(lngFileSize - 1)
    End If
    Get #FilNum, lngStartPos, ReadFile
Close #FilNum

End Function

Private Function WriteFile(ByVal strFileName As String, ByteData() As Byte, Optional ByVal lngStartPos As Long = -1, Optional ByVal OverWrite As Boolean = True)

On Error Resume Next

Dim FilNum As Integer

FilNum = FreeFile

If OverWrite = True And Dir(strFileName) <> "" Then
    Kill strFileName
End If

Open strFileName For Binary As #FilNum
    If lngStartPos = -1 Then
        Put #FilNum, LOF(FilNum) + 1, ByteData
        Else
        Put #FilNum, l, ByteData
    End If
Close #FilNum

End Function

Private Sub Form_Load()

On Error Resume Next

Dim MyInt As Integer
Dim MyByte As Byte
Dim MyStr As String * 4
Dim MyLong As Long
Dim SampleRate, BytesPerSample, FileSize As Long

Open App.Path & "\Track.wav" For Binary Access Read Lock Read As #1
    Get #1, , MyStr:    Debug.Print "Riff = "; MyStr
    Get #1, , MyLong:   Debug.Print "File size = "; MyLong
    FileSize = MyLong
    Get #1, , MyStr:    Debug.Print "Wave = "; MyStr
    Get #1, , MyStr:    Debug.Print "Format = "; MyStr
    Get #1, , MyLong:   Debug.Print "Any = "; MyLong
    Get #1, , MyInt:    Debug.Print "formatTag = "; MyInt
    Get #1, , MyInt:    Debug.Print "Channels = "; MyInt
    Get #1, , MyLong:   Debug.Print "Samples per Sec = "; MyLong
    SampleRate = MyLong
    Get #1, , MyInt:    Debug.Print "Bytes per Sec = "; MyInt
    Get #1, , MyInt:    Debug.Print "BlockAlign = "; MyInt
    Get #1, , MyInt:    Debug.Print "Bytes per Sample = "; MyInt
    BytesPerSample = MyInt

Close #1

Wavlength = FileSize \ (SampleRate * BytesPerSample)

Debug.Print "Wavlength"; Wavlength

End Sub


问:
EF Core: The LINQ expression could not be translated
I am trying to implement a query in EF Core in which I need to get data where any name in  a string array is contained by the name of the data object. Here is the code sample:

```<code>            var searchKeys = search.Split(' ');
            var objects = _db.Objects
                .Where(o => searchKeys.Any(k => o.name.Contains(k))))
                .OrderBy(o => o.Name)
                .Select o
</code>```

But the query cannot be translated resulting in the following error:

The LINQ expression 'DbSet
          .Where(o => __searchKeys_1
              .Any(k => __Functions_2
                  .Contains(
                      _: o.Name,
                      propertyReference: k)))' could not be translated. Either rewrite the query in a form that can be translated, or switch
  to client evaluation explicitly by inserting a call to either
  AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See
  https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

How can I contruct the query to fix the error?

答:
This works for me:</p>

```<code> var searchKeys = search.Split(' ');
 var objects = _db.Objects
     .Where(o => searchKeys.Any(k => o.Name.Contains(k)))
     .OrderBy(o => o.Name)
     .Select(o => o);
</code>```

Body:
I am trying to implement a query in EF Core in which I need to get data where any name in  a string array is contained by the name of the data object. Here is the code sample:

            var searchKeys = search.Split(' ');
            var objects = _db.Objects
                .Where(o => searchKeys.Any(k => o.name.Contains(k))))
                .OrderBy(o => o.Name)
                .Select o

But the query cannot be translated resulting in the following error:

The LINQ expression 'DbSet
          .Where(o => __searchKeys_1
              .Any(k => __Functions_2
                  .Contains(
                      _: o.Name,
                      propertyReference: k)))' could not be translated. Either rewrite the query in a form that can be translated, or switch
  to client evaluation explicitly by inserting a call to either
  AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See
  https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

How can I contruct the query to fix the error?

Body:
This works for me:

 var searchKeys = search.Split(' ');
 var objects = _db.Objects
     .Where(o => searchKeys.Any(k => o.Name.Contains(k)))
     .OrderBy(o => o.Name)
     .Select(o => o);


问:
Confusion with HTTP
I am new to web development and came across the term HTTP. I have done some research and wanted to ensure that I correctly understood the term. So, is it true that HTTP, in simple words, a letter containing information in the language that both client and server can understand. Then, that letter is sent to the server thanks to TCP/IP which serves as a car that takes that letter to the server. Then, after the letter is delivered to the server, the server reads the content of the letter and if it is GET request, the server takes the necessary data and ATTACHES that data to the letter and sends back to the client via again TCP/IP. But if it was POST request then the client ATTACHES the DATA to the letter and sends it to the server so that it saves that data in the database. Is that true?</p>

答:
HTTP is a text protocol, where the client (usually a browser) sends a request, which is just a properly formatted text. Then the server sends a response, which is also a properly formatted text. TCP/IP is only used to send bytes, which are interpreted as this text by the browser and the web server.

Both GET and POST methods send text requests and responses. The most significant difference between those two is that with POST method, a request can have a body.
It would look like this:

```<code>> POST /post HTTP/1.1
> Host: example.com
> Content-Length: 19
> Content-Type: application/x-www-form-urlencoded
>
> foo1=bar1&foo2=bar2        <- this is request's body, this is how it would look like if a form was submitted. GET method doesn't have this part.
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Mon, 17 Feb 2020 22:24:29 GMT
< Content-Length: 27
<
< {"response":{"text": "OK"}}  <- this is a response's body
</code>```

(> means a request, a text sent to the server, < means a response, a text sent back to the user. Those characters are not sent, it's just for us now to distinguish between those two)

You may say, that images are sent over HTTP too, but it's not text. This is true, but as we all know, for computers everything is just bytes. It's only how we interpret them that makes a distinction between text and image. This is why you can open an image file in Notepad and you will see ... text. Weirdly formatted and impossible to understand, but still text.

Title: Confusion with HTTP

Body:
HTTP is a text protocol, where the client (usually a browser) sends a request, which is just a properly formatted text. Then the server sends a response, which is also a properly formatted text. TCP/IP is only used to send bytes, which are interpreted as this text by the browser and the web server.

Both GET and POST methods send text requests and responses. The most significant difference between those two is that with POST method, a request can have a body.
It would look like this:

> POST /post HTTP/1.1
> Host: example.com
> Content-Length: 19
> Content-Type: application/x-www-form-urlencoded
>
> foo1=bar1&foo2=bar2        <- this is request's body, this is how it would look like if a form was submitted. GET method doesn't have this part.
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Mon, 17 Feb 2020 22:24:29 GMT
< Content-Length: 27
<
< {"response":{"text": "OK"}}  <- this is a response's body

(> means a request, a text sent to the server, < means a response, a text sent back to the user. Those characters are not sent, it's just for us now to distinguish between those two)

You may say, that images are sent over HTTP too, but it's not text. This is true, but as we all know, for computers everything is just bytes. It's only how we interpret them that makes a distinction between text and image. This is why you can open an image file in Notepad and you will see ... text. Weirdly formatted and impossible to understand, but still text.


问:
How to Validate JSON with Jackson JSON
I am trying to use Jackson JSON take a string and determine if it is valid JSON.  Can anyone suggest a code sample to use (Java)?</p>

答:
```<code>private boolean isValidJson(String json) {
    try {
        objectMapper.readTree(json);
    } catch (JsonProcessingException e) {
        return false;
    }
    return true;
}
</code>```

Title: How to Validate JSON with Jackson JSON


问:
JavaScript: How to check if a array object contain specific values
I have this array:

[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
]
```

<p>And some data like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "domain": "agency one",
    "url": "https://....",
    "title": "some title",
    "img": "https://.....jpg",
    "tag": "some tag",
}
</code>```

How can I check if agancy is active show data?

答:
Final answer to the question:

let agenciesList =
[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
];

let allActiveAgencies = agenciesList.filter(item => item.active);

let newArray = allActiveAgencies.map(item => item.name);

console.log(newArray); // ["agency one","agency three"]
console.log(newArray.includes("agency one")); // true
```

Body:
I have this array:

[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
]

And some data like this:

{
    "domain": "agency one",
    "url": "https://....",
    "title": "some title",
    "img": "https://.....jpg",
    "tag": "some tag",
}

How can I check if agancy is active show data?


问:
DataPlaneRequests partitionID in CosmosDB diagnostic logs always seems to be empty
I have enabled diagnostic logging of a Cosmos Account (SQL interface). The diagnostic log data is being sent to a storage account - and I can see that there is a new DataPlaneRequests blob created every 5 minutes.
So far, so good.

I'm performing CRUD requests against a collection in the Cosmos account. I can see entries within the DataPlaneRequest logs that look like this ('*' used to protect the innocent)...

{ "time": "2020-01-28T03:04:59.2606375Z", "resourceId": "/SUBSCRIPTIONS/****/RESOURCEGROUPS/****/PROVIDERS/MICROSOFT.DOCUMENTDB/DATABASEACCOUNTS/**********", "category": "DataPlaneRequests", "operationName": "Query", "properties": {"activityId": "38f497ee-7e37-435f-8b4a-a2f0d8d65d12","requestResourceType": "DocumentFeed","requestResourceId": "/dbs/****/colls/****/docs","collectionRid": "","databaseRid": "","statusCode": "200","duration": "4.588500","userAgent": "Windows/10.0.14393 documentdb-netcore-sdk/2.8.1","clientIpAddress": "52...***","requestCharge": "4.160000","requestLength": "278","responseLength": "5727","resourceTokenUserRid": "","region": "West US 2","partitionId": ""}}

Every entry in the DataPlaneRequests log has an empty partitionId property value.
(The operationName property value in the log is either "Create" or "Query").

So my question is - why is this property empty?

Here is the documentation for DataPlaneRequests

What I'm actually trying to accomplish, is to obtain information about the load being placed on the physical partitions of a collection.
e.g. I'd like to know that during the past 10 minutes, 10k Create operations were performed in physical-partition "1", while 55k operations were performed in physical-partition "3".
That will allow me to have much more insight into why a collection is experiencing throttling, etc.

答:
When you connect to Cosmos, there are two connection modes available: Gateway and Direct. It turns out that only Direct mode, causes the partitionId to be included in the logs. (If you read up about how these two modes work (differently), then that makes sense).

Anyway, it turns out that the partitionId in the logs is not a reference to a physical partition of a collection. So I'm unable to use that data to solve the problem, I was attempting to solve.

There is a physical partition id available in the logs - but it's also of limited use - since it's only tracked for the 3 largest (logical) PartitionKey values, of each physical partition, only if the key-value contains >=1Gb of documents.


问:
How to delete values from JSON object array in php?
I have a PHP code and JSON as shown below:

PHP Code:

```<code><?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
      $output = array();
      $output['en_desc']=$_POST['en_desc'];
      $output['code']=$_POST['code'];

      $fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
      fwrite($fp, json_encode($output));
      fclose($fp);
   }
   if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
       $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
   }
?>
<?php if($data) { ?>
    <form method="post" id="myform" style="text-align:left;">
      <input type="hidden" id="savechanges" name="savechanges" value="1">
       <div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
         <button type="submit">Save</button>
       </div>
        <?php foreach ($data->code as $key => $value) { ?>
        <div class="house-senate-committee" style="text-align:center; margin-top:15px;">
            <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
            <input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
            <input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
        </div>
        <?php } ?>
    </form>
<?php } else { echo 'Cannot read JSON settings file'; }?>
</code>```

JSON:

```<code>{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}
</code>```

The following DOM is generated through the PHP/JSON code above:

DOM (HTML):

```<code><div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
  <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">
</div>

<div class="house-senate-committee" style="text-align:center; margin-top:15px;">
  <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
  <input type="text" name="en_desc[]" value="Agriculture and Forestry">
</div>
</code>```

The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.

JS code:

```<code><script>
function removeRow(el) {
  el.parentNode.remove();
}
</script>
</code>```

Problem Statement:

The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.

I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.

Step 1: User delete the row from the DOM on click of a delete button.

Step 2: On saving the form and rendering the page, that deleted row should not be present.

I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.

```<code>unset($data->code);
unset($data->en_desc);
</code>```

答:
You have a typo here:

```<code>   $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
</code>```

it should be

```<code>       $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
</code>```

Look at the "s" :)

Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:

```<code><?php

if (isset($_POST['submit'])) {
  $output = array();
  $output['en_desc'] = $_POST['en_desc'];
  $output['code'] = $_POST['code'];

  $fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
  fwrite($fp, json_encode($output));
  fclose($fp);
}

if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
  $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}

?>
<?php if ($data) { ?>
  <form method="post" id="myform" style="text-align:left;">
    <div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
      <button type="submit" name="submit">Save</button>
    </div>
    <?php foreach ($data->code as $key => $value) { ?>
      <div class="house-senate-committee" style="text-align:center; margin-top:15px;">
        <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
        <input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
        <input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
      </div>
    <?php } ?>
  </form>
<?php } else {
  echo 'Cannot read JSON settings file';
} ?>

<script>
  function removeRow(el) {
    el.parentNode.remove();
  }
</script>
</code>```

Body:
I have a PHP code and JSON as shown below:

PHP Code:

<?php if (!empty($_POST) && isset($_POST['savechanges']) && $_POST['savechanges'] == 1 && isset($_SESSION['pageadmin'])) {
      $output = array();
      $output['en_desc']=$_POST['en_desc'];
      $output['code']=$_POST['code'];

      $fp = fopen('../feeds/ptp-ess_landing_scommittees.json', 'w');
      fwrite($fp, json_encode($output));
      fclose($fp);
   }
   if(file_exists('../feeds/ptp-ess_landing_scommittees.json')){
       $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));
   }
?>
<?php if($data) { ?>
    <form method="post" id="myform" style="text-align:left;">
      <input type="hidden" id="savechanges" name="savechanges" value="1">

         <button type="submit">Save</button>

        <?php foreach ($data->code as $key => $value) { ?>

            <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
            <input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
            <input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">

        <?php } ?>
    </form>
<?php } else { echo 'Cannot read JSON settings file'; }?>

JSON:

{"code":["AEFA","AGFO"], "en_desc":["Foreign Affairs and International Trade","Agriculture and Forestry"]}

The following DOM is generated through the PHP/JSON code above:

DOM (HTML):

  <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AEFA">
  <input type="text" name="en_desc[]" value="Foreign Affairs and International Trade">

  <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
  <input type="text" name="code[]" style="margin-right:10px;" value="AGFO">
  <input type="text" name="en_desc[]" value="Agriculture and Forestry">

The following JS code deletes a row from the DOM on click of a delete button. On refreshing the page,
the deleted row comes back again as everything is rendered through JSON.

JS code:

Problem Statement:

The above JS code is deleting the row (on click of a delete button) from the DOM but on refresing the page, everything is rendered again.

I am wondering what PHP code I need to add so that it delete the values from the JSON on saving the form when row is deleted from DOM through JS.

Step 1: User delete the row from the DOM on click of a delete button.

Step 2: On saving the form and rendering the page, that deleted row should not be present.

I know I have to use unset function in order to remove the values from the JSON but I am not sure how I can integrate it in the form.

unset($data->code);
unset($data->en_desc);

Body:
You have a typo here:

   $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_scommittees.json'));

it should be

       $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));

Look at the "s" :)

Edit: you also were saving the new file without actually checking if there is a post happening, here is the full code:

<?php

if (isset($_POST['submit'])) {
  $output = array();
  $output['en_desc'] = $_POST['en_desc'];
  $output['code'] = $_POST['code'];

  $fp = fopen('../feeds/ptp-ess_landing_committees.json', 'w');
  fwrite($fp, json_encode($output));
  fclose($fp);
}

if (file_exists('../feeds/ptp-ess_landing_committees.json')) {
  $data = json_decode(file_get_contents('../feeds/ptp-ess_landing_committees.json'));
}

?>
<?php if ($data) { ?>
  <form method="post" id="myform" style="text-align:left;">
    <div style="text-align:center; margin-right:9px; margin-bottom:24.703px;">
      <button type="submit" name="submit">Save</button>
    </div>
    <?php foreach ($data->code as $key => $value) { ?>
      <div class="house-senate-committee" style="text-align:center; margin-top:15px;">
        <button type="button" onclick="removeRow(this)" style="margin-right:10px;">Delete</button>
        <input type="text" name="code[]" style="margin-right:10px;" value="<?= $data->code[$key] ?>">
        <input type="text" name="en_desc[]" value="<?= $data->en_desc[$key] ?>">
      </div>
    <?php } ?>
  </form>
<?php } else {
  echo 'Cannot read JSON settings file';
} ?>

<script>
  function removeRow(el) {
    el.parentNode.remove();
  }
</script>


问:
Initialize unordered_map in the initializer list
I'm trying to find a solution to what may be a very trivial problem. I would like to initialize my const unordered_map in the class initializer list. However I'm yet to find the syntax that the compiler (GCC 6.2.0) will accept. A code link is here.

```<code>#include <unordered_map>

class test {
 public:
    test()
      : map_({23, 1345}, {43, -8745}) {}

 private:
   const std::unordered_map<long, long> map_;
 };
</code>```

Error:

```<code>main.cpp: In constructor 'test::test()':
main.cpp:6:36: error: no matching function for call to 'std::unordered_map<long int, long int>::unordered_map(<brace-enclosed initializer list>, <brace-enclosed initializer list>)'
  : map_({23, 1345}, {43, -8745}) {}
                                ^
</code>```

Are the complex constants not allowed to be initialized in the initializer list? Or the syntax has to be different?

答:
Use curly braces instead of the parentheses because if you use parentheses it's calling the constructor that best matches your arguments instead of the overloaded constructor with a parameter of type initializer_list.

Using parentheses and curly braces have the same effect until there's an overloaded constructor taking initializer_list type as a parameter. Then when you use curly braces, the compiler is going to bend over backwards to try to call that overloaded constructor.

for example:

```<code>Foo( 3 ) is calling Foo( int x ) constructor;
Foo{ 3 } is calling Foo( initializer_list<int> x ) constructor;

but if there's no Foo( initializer_list<int> x ) constructor

then Foo( 3 ) and Foo{ 3 } are both calling Foo( int x ) constructor.
</code>```

Body:
I'm trying to find a solution to what may be a very trivial problem. I would like to initialize my const unordered_map in the class initializer list. However I'm yet to find the syntax that the compiler (GCC 6.2.0) will accept. A code link is here.

#include <unordered_map>

class test {
 public:
    test()
      : map_({23, 1345}, {43, -8745}) {}

 private:
   const std::unordered_map<long, long> map_;
 };

Error:

main.cpp: In constructor 'test::test()':
main.cpp:6:36: error: no matching function for call to 'std::unordered_map<long int, long int>::unordered_map(<brace-enclosed initializer list>, <brace-enclosed initializer list>)'
  : map_({23, 1345}, {43, -8745}) {}
                                ^

Are the complex constants not allowed to be initialized in the initializer list? Or the syntax has to be different?

Body:
Use curly braces instead of the parentheses because if you use parentheses it's calling the constructor that best matches your arguments instead of the overloaded constructor with a parameter of type initializer_list.

Using parentheses and curly braces have the same effect until there's an overloaded constructor taking initializer_list type as a parameter. Then when you use curly braces, the compiler is going to bend over backwards to try to call that overloaded constructor.

for example:

Foo( 3 ) is calling Foo( int x ) constructor;
Foo{ 3 } is calling Foo( initializer_list<int> x ) constructor;

but if there's no Foo( initializer_list<int> x ) constructor

then Foo( 3 ) and Foo{ 3 } are both calling Foo( int x ) constructor.


问:
Are you intended to use NativeStorage and LocalStorage at the same time?
I'm working in the app of my company made in Ionic 3, and I see this many times:

```<code>if (this.platform.is('cordova')) {
  // store content using NativeStorage
else {
  // do the same but using LocalStorage
}
</code>```

People also talk about IonicStorage in forums...

I want to understand why they (my company) do this because something tells me this is not the way it should be done.

I mean, is there any better way to manage both scenarios (when the platform is 'cordova' and when it's not)? Is this why IonicStorage exists?

答:
Native storage only works in devices while LocalStorage can use it on the browser, for example when you are debugging or testing.

Also you can check this question to see the differences between IonicStorage and  NativeStorage.

Body:
I'm working in the app of my company made in Ionic 3, and I see this many times:

if (this.platform.is('cordova')) {
  // store content using NativeStorage
else {
  // do the same but using LocalStorage
}

People also talk about IonicStorage in forums...

I want to understand why they (my company) do this because something tells me this is not the way it should be done.

I mean, is there any better way to manage both scenarios (when the platform is 'cordova' and when it's not)? Is this why IonicStorage exists?


问:
XML Structure in SQL Server
I have the following code which works fine and returns the expected results:

```<code>DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)
</code>```

However, it also accept when I provide it with the following structure and returns the ssame results:

```<code>SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'
</code>```

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky

答:
Root element is one and only one time. So in your example:

```<code>; With c as(
SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('//Tx') X(Y))
    SELECT COUNT(*) from c
</code>```

In first case you will get 1, in second 2.

Title: XML Structure in SQL Server

Body:
I have the following code which works fine and returns the expected results:

DECLARE @xmlList xml
SET @xmlList = '<Tx><T>1</T><T>2</T><T>3</T></Tx>'

SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('/Tx/T') X(Y)

However, it also accept when I provide it with the following structure and returns the ssame results:

SET @xmlList = '<Tx><T>1</T></Tx><Tx><T>2</T><T>3</T></Tx>'

Notice how I don't have a root element.

My question is, what do I need to change to make the code accept the first structure as valid and reject the other?

Thanks,

TheBlueSky

Body:
Root element is one and only one time. So in your example:

; With c as(
SELECT
        X.Y.value('.', 'varchar(10)') AS [ID], 'OK' AS [Status]
    FROM @xmlList.nodes('//Tx') X(Y))
    SELECT COUNT(*) from c

In first case you will get 1, in second 2.


问:
How to handle Python subprocess call error & wait
I am calling a python script (script B) from script A and script B calling another python script script C.

Script A --> Script B --> Script C

Is there a way to make below process to wait for script B & C completion ?

```<code>import subprocess

cmd = subprocess.call(['python script_A.py'], shell=True)
if cmd != 0:
    print "\nscript_A.py failed with exit code %s\n" % cmd
    sys.exit(1)
</code>```

答:
Don't use shell=True with a list, and don't use a list that contains a single string you expect the shell to parse. Just pass a list consisting of the command name and its arguments.

```<code>result = subprocess.call(['python', 'script_A.py'])
if result != 0:
    ...
</code>```

Body:
I am calling a python script (script B) from script A and script B calling another python script script C.

Script A --> Script B --> Script C

Is there a way to make below process to wait for script B & C completion ?

import subprocess

cmd = subprocess.call(['python script_A.py'], shell=True)
if cmd != 0:
    print "\nscript_A.py failed with exit code %s\n" % cmd
    sys.exit(1)

Body:
Don't use shell=True with a list, and don't use a list that contains a single string you expect the shell to parse. Just pass a list consisting of the command name and its arguments.

result = subprocess.call(['python', 'script_A.py'])
if result != 0:
    ...


问:
Problem skipping line whilst iterating using previous line and current line comparison
I have a list of sorted data arranged so that each item in the list is a csv line to be written to file.

The final step of the script checks the contents of each field and if all but the last field match then it will copy the current line's last field onto the previous line's last field.

I would like to as I've found and processed one of these matches skip the current line where the field was copied from thus only leaving one of the lines.

Here's an example set of data

```<code>field1,field2,field3,field4,something
field1,field2,field3,field4,else
</code>```

Desired output

```<code>field1,field2,field3,field4,something else
</code>```

This is what I have so far

```<code>output_csv = ['field1,field2,field3,field4,something',
              'field1,field2,field3,field4,else']

# run through the output
# open and create a csv file to save output
with open('output_table.csv', 'w') as f:

    previous_line = None
    part_duplicate_line = None
    part_duplicate_flag = False

    for line in output_csv:
        part_duplicate_flag = False

        if previous_line is not None:
            previous = previous_line.split(',')
            current = line.split(',')

            if (previous[0] == current[0]
                and previous[1] == current[1]
                and previous[2] == current[2]
                and previous[3] == current[3]):
                print(previous[0], current[0])
                previous[4] = previous[4].replace('\n', '') + ' ' + current[4]
                part_duplicate_line = ','.join(previous)
                part_duplicate_flag = True
                f.write(part_duplicate_line)

            if part_duplicate_flag is False:
                f.write(previous_line)

        previous_line = line
</code>```

ATM script adds the line but doesn't skip the next line, I've tried various renditions of continue statements after part_duplicate_line is written to file but to no avail.

答:
I propose to encapsulate what you want to do in a function where the important part obeys this logic:

either join the new info to the old record

or output the old record and forget it

of course at the end of the loop we have in any case a dangling old record to output

```<code>def join(inp_fname, out_fname):
    '''Input file contains sorted records, when two (or more) records differ
only in the last field, we join the last fields with a space
and output only once, otherwise output the record as-is.'''
    ######################### Prepare for action ##########################
    from csv import reader, writer
    with open(inp_fname) as finp, open(out_fname, 'w') as fout:
        r, w = reader(finp), writer(fout)
        ######################### Important Part starts here ##############
        old = next(r)
        for new in r:
            if old[:-1] == new[:-1]:
                old[-1] += ' '+new[-1]
            else:
                w.writerow(old)
                old = new
        w.writerow(old)
</code>```

To check what I've proposed you can use these two snippets (note that these records are shorter than yours, but it's an example and it doesn't matter because we use only -1 to index our records).

The 1st one has a "regular" last record

```<code>open('a0.csv', 'w').write('1,1,2\n1,1,3\n1,2,0\n1,3,1\n1,3,2\n3,3,0\n')
join('a0.csv', 'a1.csv')
</code>```

while the 2nd has a last record that must be joined to the previous one.

```<code>open('b0.csv', 'w').write('1,1,2\n1,1,3\n1,2,0\n1,3,1\n1,3,2\n')
join('b0.csv', 'b1.csv')
</code>```

If you run the snippets, as I have done before posting, in the environment where you have defined join you should get what you want.

Body:
I have a list of sorted data arranged so that each item in the list is a csv line to be written to file.

The final step of the script checks the contents of each field and if all but the last field match then it will copy the current line's last field onto the previous line's last field.

I would like to as I've found and processed one of these matches skip the current line where the field was copied from thus only leaving one of the lines.

Here's an example set of data

field1,field2,field3,field4,something
field1,field2,field3,field4,else

Desired output

field1,field2,field3,field4,something else

This is what I have so far

output_csv = ['field1,field2,field3,field4,something',
              'field1,field2,field3,field4,else']

# run through the output
# open and create a csv file to save output
with open('output_table.csv', 'w') as f:

    previous_line = None
    part_duplicate_line = None
    part_duplicate_flag = False

    for line in output_csv:
        part_duplicate_flag = False

        if previous_line is not None:
            previous = previous_line.split(',')
            current = line.split(',')

            if (previous[0] == current[0]
                and previous[1] == current[1]
                and previous[2] == current[2]
                and previous[3] == current[3]):
                print(previous[0], current[0])
                previous[4] = previous[4].replace('\n', '') + ' ' + current[4]
                part_duplicate_line = ','.join(previous)
                part_duplicate_flag = True
                f.write(part_duplicate_line)

            if part_duplicate_flag is False:
                f.write(previous_line)

        previous_line = line

ATM script adds the line but doesn't skip the next line, I've tried various renditions of continue statements after part_duplicate_line is written to file but to no avail.

Body:
I propose to encapsulate what you want to do in a function where the important part obeys this logic:

either join the new info to the old record

or output the old record and forget it

of course at the end of the loop we have in any case a dangling old record to output

def join(inp_fname, out_fname):
    '''Input file contains sorted records, when two (or more) records differ
only in the last field, we join the last fields with a space
and output only once, otherwise output the record as-is.'''
    ######################### Prepare for action ##########################
    from csv import reader, writer
    with open(inp_fname) as finp, open(out_fname, 'w') as fout:
        r, w = reader(finp), writer(fout)
        ######################### Important Part starts here ##############
        old = next(r)
        for new in r:
            if old[:-1] == new[:-1]:
                old[-1] += ' '+new[-1]
            else:
                w.writerow(old)
                old = new
        w.writerow(old)

To check what I've proposed you can use these two snippets (note that these records are shorter than yours, but it's an example and it doesn't matter because we use only -1 to index our records).

The 1st one has a "regular" last record

open('a0.csv', 'w').write('1,1,2\n1,1,3\n1,2,0\n1,3,1\n1,3,2\n3,3,0\n')
join('a0.csv', 'a1.csv')

while the 2nd has a last record that must be joined to the previous one.

open('b0.csv', 'w').write('1,1,2\n1,1,3\n1,2,0\n1,3,1\n1,3,2\n')
join('b0.csv', 'b1.csv')

If you run the snippets, as I have done before posting, in the environment where you have defined join you should get what you want.


问:
Pre load background images in jQuery
I'm having trouble pre loading background images. This is my attempt but still seems to not be working - ie. there is still a delay seeing the image when i call showAjaxLoader("#mytarget"). Does anybody have any suggestions?

CSS:

```<code>div.entryform-ajax-loader {
    background-image:url(../images/preloader-entry-form.gif);
}
</code>```

Script:

```<code>var ajax_loader = $('<div />').attr('class', 'entryform-ajax-loader');

function showAjaxLoader(target)
{
    $(target).append(ajax_loader);
}

function hideAjaxLoader(target)
{
    ajax_loader.remove();
</code>```

答:
As an altermative solution, you may add this script to your file,

```<code>$(function() {
$(document.body).append($("<img />").attr("src", "../images/preloader-entry-form.gif").hide())
});
</code>```

which will load the image at the beginning of page load. As a result when the function showAjaxLoader will be executed, the image will be loaded without any delay.

Title: Pre load background images in jQuery

Body:
I'm having trouble pre loading background images. This is my attempt but still seems to not be working - ie. there is still a delay seeing the image when i call showAjaxLoader("#mytarget"). Does anybody have any suggestions?

CSS:

div.entryform-ajax-loader {
    background-image:url(../images/preloader-entry-form.gif);
}

Script:

var ajax_loader = $('
').attr('class', 'entryform-ajax-loader');

function showAjaxLoader(target)
{
    $(target).append(ajax_loader);
}

function hideAjaxLoader(target)
{
    ajax_loader.remove();

Body:
As an altermative solution, you may add this script to your file,

$(function() {
$(document.body).append($("<img />").attr("src", "../images/preloader-entry-form.gif").hide())
});

which will load the image at the beginning of page load. As a result when the function showAjaxLoader will be executed, the image will be loaded without any delay.


问:
Is there a better dependency injection pattern in golang?
Given this code:

```<code>package main

import (
    "fmt"
)

type datstr string

type Guy interface {
   SomeDumbGuy() string
}

func (d *datstr) SomeDumbGuy() string {
  return "some guy"
}

func someConsumer(g Guy) {
  fmt.Println("Hello, " + g.SomeDumbGuy())
}

func main() {
    var d datstr
    someConsumer(&d)
}
</code>```

Is the wiring of components together that's done in main the right way to wire a dependency together?  It seems like I'm over using this a bit in my code.  Is there a common pattern better than this, or am I overthinking it?

答: The best practice is not to use a DI library. Go is meant to be a simple language that is easy to follow. A DI library/framework will abstract that away from you (and to some extent make DI magical).

Body:
Given this code:

package main

import (
    "fmt"
)

type datstr string

type Guy interface {
   SomeDumbGuy() string
}

func (d *datstr) SomeDumbGuy() string {
  return "some guy"
}

func someConsumer(g Guy) {
  fmt.Println("Hello, " + g.SomeDumbGuy())
}

func main() {
    var d datstr
    someConsumer(&d)
}

Is the wiring of components together that's done in main the right way to wire a dependency together?  It seems like I'm over using this a bit in my code.  Is there a common pattern better than this, or am I overthinking it?


问:
swift - how call app's code from another app and return data
I need to implement next scheme:

1) App1 has some UI like signin/signup, and user's profile. But main functionality is creating specific http request to get/update token.

2)when tapping button at App2 - App2 calls App1, then App1 execute only http request, and return token to App2, like callback. And this actions should be invisible for user, maybe like empty screen with spinner

What is the best way to make it real? Is it possible for iOS?

To share data between apps I suppose use App Group and shared UserDefaults, but how to call some class/function?

答:
iOS is extremely strict as far as inter-app communication. While this is for the safety of their users, it can be extremely annoying for developers.

I'd recommend using x-callback-url for this, if you own both of the apps you're trying to communicate with.

x-callback-url website: http://x-callback-url.com/

Apple Developer website: https://developer.apple.com/documentation/uikit/inter-process_communication/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app

Unfortunately for your uses, this will throw your user into the other app, which will be visible to the user for a short amount of time.

That's the only way to directly interface with other apps on the system.


问:
Count on enum C++ automatic
I've come to a pattern when writing enums in C++. It is like this:

```<code>class Player
{
public:
    class State
    {
    public:
        typedef enum
        {
            Stopped,
            Playing,
            Paused
        }PossibleValues;

        static const int Count() {return Paused+1;};
        static const PossibleValues Default() {return Stopped;};
    };

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

This solves a some of the usual issues with enums, like pollution of outside namespaces, etc. But there is still a thing I don't like: The Count() is done manually. There are only two ways I know how to do it: this one is calculated from Last+1; or write plain hardcoded.

Question is: Is there some way, like using preprocessor macros, that automatically gets the count, to put it after in the Count() method? Attention: I don't want to have a last fake element called Count inside the enum, polluting it!

Thanks in advance!

UPDATE 1:

There is an interesting discussion on Implementation of N4428 enum reflection in standard C++11 (partial) for a proposal of more advanced enums.

UPDATE 2:

Interesting document N4451- Static reflection (rev. 3) on its sections 3.16, 3.17, A.7, A.8 about MetaEnums and MetaEnumClasses.

UPDATE 3:

I came to another interesting pattern using an enum class, after I've seen https://bytes.com/topic/c/answers/127908-numeric_limits-specialization#post444962. If the enum class's enumerator list is continuously integer, by defining its maximum and its minimum, we can check whether a value belongs to it or not.

If the purpose of using the Count() method on the Player::State was to check if a value was in the enum, that purpose has also been achieved with the numeric_limits approach, and is even superior, as it is not required the enumerator list begins with a ZERO valued item!

```<code>enum class Drink
{
    Water,
    Beer,
    Wine,
    Juice,
};

#pragma push_macro("min")
#undef min

#pragma push_macro("max")
#undef max

namespace std
{
    template <> class numeric_limits < Drink >
    {
    public:
        static const/*expr*/ bool is_specialized = true;

        static const/*expr*/ Drink min() /*noexcept*/ { return Drink::Water; }
        static const/*expr*/ Drink max() /*noexcept*/ { return Drink::Juice; }

        static const/*expr*/ Drink lowest() /*noexcept*/ { return Drink::Water; }

        static const/*expr*/ Drink default() /*noexcept*/ { return Drink::Beer; }
    };
}

#pragma pop_macro("min")
#pragma pop_macro("max")
</code>```

CASES OF USE:

A variable from the application:

```<code>Drink m_drink;
</code>```

which in constructor is initialized with:

```<code>m_drink = numeric_limits<Drink>::default();
</code>```

On the initialization of a form, I can do:

```<code>pComboDrink->SetCurSel(static_cast<int>(theApp.m_drink));
</code>```

On it, for adapting the interface to changes done by the user, I can do a switch with scoped enum class values:

```<code>switch (static_cast<Drink>(pComboDrink->GetCurSel()))
{
case Drink::Water:
case Drink::Juice:
    pAlcohoolDegreesControl->Hide();
break;

case Drink::Beer:
case Drink::Wine:
    pAlcohoolDegreesControl->Show();
break;

default:
    break;
}
</code>```

And on the dialog's confirmation procedure (OnOK), I can check if the value is out of boundaries, before saving it to the respective app var:

```<code>int ix= pComboDrink->GetCurSel();

if (ix == -1)
    return FALSE;

#pragma push_macro("min")
#undef min

#pragma push_macro("max")
#undef max

if (ix < static_cast<int> (std::numeric_limits<Drink>::min()) ||  ix > static_cast<int> (std::numeric_limits<Drink>::max()) )
    return FALSE;

#pragma pop_macro("min")
#pragma pop_macro("max")

theApp.m_drink= static_cast<Drink>(ix);
</code>```

NOTES:

The keywords constexpr (I commented /*expr*/, leaving it as const ) and noexcept are commented only because the compiler I am using (Visual C++ 2013) does not support them yet at the current version.

Maybe you do not need the logic to temporary undefine the min and max macros.

I know that the default() does not fit on a "numeric limits" scope; but it seemed an handy place to put it on; even it coincides with the default word that in some contexts is a keyword!

答:
The solution from https://stackoverflow.com/a/60216003/12894563 can be improved. We can  save enums expressions in a static vector and iterate, obtain min/max and etc

Usage:

```<code>#include <type_traits>
#include <algorithm>
#include <vector>
#include <iostream>

#define make_enum(Name, Type,  ...)                                              \
    struct Name {                                                                \
        enum : Type {                                                            \
            __VA_ARGS__                                                          \
        };                                                                       \
        static auto count() { return values.size(); }                            \
                                                                                \
        static inline const std::vector<Type> values = [] {                      \
            static Type __VA_ARGS__; return std::vector<Type>({__VA_ARGS__});    \
        }();                                                                     \
        static Type min()                                                        \
        {                                                                        \
            static const Type result = *std::min_element(values.begin(), values.end()); \
            return result;                                                       \
        }                                                                        \
        static Type max()                                                        \
        {                                                                        \
            static const Type result = *std::max_element(values.begin(), values.end()); \
            return result;                                                       \
        }                                                                        \
}

make_enum(FakeEnum, int, A = 1, B = 0, C = 2, D);

int main(int argc, char *argv[])
{
    std::cout << FakeEnum::A     << std::endl
              << FakeEnum::min() << std::endl
              << FakeEnum::max() << std::endl
              << FakeEnum::count() << std::endl;
    return 0;
}
</code>```

Title: Count on enum C++ automatic

Body:
I've come to a pattern when writing enums in C++. It is like this:

class Player
{
public:
    class State
    {
    public:
        typedef enum
        {
            Stopped,
            Playing,
            Paused
        }PossibleValues;

        static const int Count() {return Paused+1;};
        static const PossibleValues Default() {return Stopped;};
    };

    //...
}

This solves a some of the usual issues with enums, like pollution of outside namespaces, etc. But there is still a thing I don't like: The Count() is done manually. There are only two ways I know how to do it: this one is calculated from Last+1; or write plain hardcoded.

Question is: Is there some way, like using preprocessor macros, that automatically gets the count, to put it after in the Count() method? Attention: I don't want to have a last fake element called Count inside the enum, polluting it!

Thanks in advance!

UPDATE 1:

There is an interesting discussion on Implementation of N4428 enum reflection in standard C++11 (partial) for a proposal of more advanced enums.

UPDATE 2:

Interesting document N4451- Static reflection (rev. 3) on its sections 3.16, 3.17, A.7, A.8 about MetaEnums and MetaEnumClasses.

UPDATE 3:

I came to another interesting pattern using an enum class, after I've seen https://bytes.com/topic/c/answers/127908-numeric_limits-specialization#post444962. If the enum class's enumerator list is continuously integer, by defining its maximum and its minimum, we can check whether a value belongs to it or not.

If the purpose of using the Count() method on the Player::State was to check if a value was in the enum, that purpose has also been achieved with the numeric_limits approach, and is even superior, as it is not required the enumerator list begins with a ZERO valued item!

enum class Drink
{
    Water,
    Beer,
    Wine,
    Juice,
};

#pragma push_macro("min")
#undef min

#pragma push_macro("max")
#undef max

namespace std
{
    template <> class numeric_limits < Drink >
    {
    public:
        static const/*expr*/ bool is_specialized = true;

        static const/*expr*/ Drink min() /*noexcept*/ { return Drink::Water; }
        static const/*expr*/ Drink max() /*noexcept*/ { return Drink::Juice; }

        static const/*expr*/ Drink lowest() /*noexcept*/ { return Drink::Water; }

        static const/*expr*/ Drink default() /*noexcept*/ { return Drink::Beer; }
    };
}

#pragma pop_macro("min")
#pragma pop_macro("max")

CASES OF USE:

A variable from the application:

Drink m_drink;

which in constructor is initialized with:

m_drink = numeric_limits<Drink>::default();

On the initialization of a form, I can do:

pComboDrink->SetCurSel(static_cast<int>(theApp.m_drink));

On it, for adapting the interface to changes done by the user, I can do a switch with scoped enum class values:

switch (static_cast<Drink>(pComboDrink->GetCurSel()))
{
case Drink::Water:
case Drink::Juice:
    pAlcohoolDegreesControl->Hide();
break;

case Drink::Beer:
case Drink::Wine:
    pAlcohoolDegreesControl->Show();
break;

default:
    break;
}

And on the dialog's confirmation procedure (OnOK), I can check if the value is out of boundaries, before saving it to the respective app var:

int ix= pComboDrink->GetCurSel();

if (ix == -1)
    return FALSE;

#pragma push_macro("min")
#undef min

#pragma push_macro("max")
#undef max

if (ix < static_cast<int> (std::numeric_limits<Drink>::min()) ||  ix > static_cast<int> (std::numeric_limits<Drink>::max()) )
    return FALSE;

#pragma pop_macro("min")
#pragma pop_macro("max")

theApp.m_drink= static_cast<Drink>(ix);

NOTES:

The keywords constexpr (I commented /*expr*/, leaving it as const ) and noexcept are commented only because the compiler I am using (Visual C++ 2013) does not support them yet at the current version.

Maybe you do not need the logic to temporary undefine the min and max macros.

I know that the default() does not fit on a "numeric limits" scope; but it seemed an handy place to put it on; even it coincides with the default word that in some contexts is a keyword!

Body:
The solution from https://stackoverflow.com/a/60216003/12894563 can be improved. We can  save enums expressions in a static vector and iterate, obtain min/max and etc

Usage:

#include <type_traits>
#include <algorithm>
#include <vector>
#include <iostream>

#define make_enum(Name, Type,  ...)                                              \
    struct Name {                                                                \
        enum : Type {                                                            \
            __VA_ARGS__                                                          \
        };                                                                       \
        static auto count() { return values.size(); }                            \
                                                                                \
        static inline const std::vector<Type> values = [] {                      \
            static Type __VA_ARGS__; return std::vector<Type>({__VA_ARGS__});    \
        }();                                                                     \
        static Type min()                                                        \
        {                                                                        \
            static const Type result = *std::min_element(values.begin(), values.end()); \
            return result;                                                       \
        }                                                                        \
        static Type max()                                                        \
        {                                                                        \
            static const Type result = *std::max_element(values.begin(), values.end()); \
            return result;                                                       \
        }                                                                        \
}

make_enum(FakeEnum, int, A = 1, B = 0, C = 2, D);

int main(int argc, char *argv[])
{
    std::cout << FakeEnum::A     << std::endl
              << FakeEnum::min() << std::endl
              << FakeEnum::max() << std::endl
              << FakeEnum::count() << std::endl;
    return 0;
}


问:
Firebase and Unity: Unable to find command line tool error
After following tutorials on how to correctly install firebase into unity for an authentication system, I encountered an error that was:

Unable to find command line tool C:\The E-Learning System\Assets\Firebase\Editor\generate_xml_from_google_services_json.py required for Firebase Android resource generation.

From understnading it can not find either the google services file I imported into the assets folder or it could not find the generate_xml_from_google_services_json.py file. I looked online for people with similar problems could not find a clear answer to fix this.

答:
This is a tool that ships with the SDK to support debugging your game in the Unity Editor. One minor caveat is that an exe actually ships on Windows (I assume that this is your operating system from the C:/). You should make sure that generate_xml_from_google_services_json.exe exists in that same directory (.exe's are typically ignored in many standard .gitignore as a catchall for build files). If it's missing, you can simply re-add the Firebase SDK and double check that this file gets included in your source repository.

If both generate_xml_from_google_services_json.py and generate_xml_from_google_services_json.exe exist under Assets/Firebase/Editor, you may also want to install Python for Windows (especially if you're still running Windows 7 or 8). This is due to a recent patch (as of 6.10.0) that fixes some incompatibilities with generate_xml_from_google_services_json.exe and older Windows variants. If that doesn't help, it would be awesome if you could file an issue or reach out to support directly. If there's a bug in that fallback, it would be helpful to surface that ASAP.

Let me know if that helps!

--Patrick