问:
mongo db query get documents befor and after
If I have the ObjectID of a document, how can I get the documents, that are before and after that document something like</p>
```<code>db.getCollection('example').find({})
</code>```

答:
Mongo's ObjectId is mostly monotonically increasing, on very rare occasions it's not like if you insert 2 documents at the exact same millisecond the "random" bit value added to it could technically break this. but this situation is very very rare.

So now you can query documents based this quality. for example this is how you'd fetch the x previous documents:

```<code>const id = ObjectId('xyz');
const documentsBefore = await db.getCollection('example').find(
    { _id: { $lt: id } })
    .sort({ _id: -1 }).limit(x).toArray();
</code>```

Or documents after (he sort order and the query needs to change )

```<code>const id = ObjectId('xyz');
const documentsAfter = await db.getCollection('example').find(
    { _id: { $gt: id } })
    .sort({ _id: 1 }).limit(x).toArray();
</code>```

Body:
If I have the ObjectID of a document, how can I get the documents, that are before and after that document something like

db.getCollection('example').find({})

Body:
Mongo's ObjectId is mostly monotonically increasing, on very rare occasions it's not like if you insert 2 documents at the exact same millisecond the "random" bit value added to it could technically break this. but this situation is very very rare.

So now you can query documents based this quality. for example this is how you'd fetch the x previous documents:

const id = ObjectId('xyz');
const documentsBefore = await db.getCollection('example').find(
    { _id: { $lt: id } })
    .sort({ _id: -1 }).limit(x).toArray();

Or documents after (he sort order and the query needs to change )

const id = ObjectId('xyz');
const documentsAfter = await db.getCollection('example').find(
    { _id: { $gt: id } })
    .sort({ _id: 1 }).limit(x).toArray();


来源: stackexchange

问:
Are C# events synchronous?
There are two parts to this question:

Does raising an event block the thread, or does it start execution of EventHandlers asynchronously and the thread goes continues on at the same time?

Are the individual EventHandlers (subscribed to the event) run synchronously one after another, or are they run asynchronously with no guarantee that others aren't running at the same time?

答:
The delegates subscribed to the event are invoked synchronously in the order they were added. If one of the delegates throws an exception, the ones following will not be called.

Since events are defined with multicast delegates, you can write your own firing mechanism using

```<code>Delegate.GetInvocationList();
</code>```

and invoking the delegates asynchronously;

ContentLicense: CC BY-SA 4.0

Title: Are C# events synchronous?

Body:
The delegates subscribed to the event are invoked synchronously in the order they were added. If one of the delegates throws an exception, the ones following will not be called.

Since events are defined with multicast delegates, you can write your own firing mechanism using

Delegate.GetInvocationList();

and invoking the delegates asynchronously;

ContentLicense: CC BY-SA 3.0


问:
continue is not working in Parallel.Foreach method
I was using foreah loop for some conditions and now I need to use Parallel.Foreach loop for perrformance improvement.I have list of data in studentdetails which is coming from mongo db collectio .Using foreach loop consumes lot of time to return final data based on some logic.
I am not doing any transactional operations in code.
Below are the samples of my code;

```<code>       **Code**

    **var studentdetails = await _mongoRepo.GetAsync(filter,projection,StudentCollection);

    foreach (var student in studentdetails)

         if (getsection.studenttab =null)
    {
        _logger.log("something");

    continue;
    }

    some other busiess logic
    }
   return abc;**

    After using Parallel.Foreach
    *****************************

    **Parallel.Foreach(studentdetails , resource =>
    {
         if (getsection.studenttab =null)
    {
        _logger.log("something");

         continue;
    }

    some other busiess logic

    });
return abc;

</code>```

But I am getting this error: no enclosing loop out of which is break or continue.
and Metadata projectname.dll could not be found
What should I do here?

答: Use return instead of continue.

Body:
I was using foreah loop for some conditions and now I need to use Parallel.Foreach loop for perrformance improvement.I have list of data in studentdetails which is coming from mongo db collectio .Using foreach loop consumes lot of time to return final data based on some logic.
I am not doing any transactional operations in code.
Below are the samples of my code;

       **Code**

    **var studentdetails = await _mongoRepo.GetAsync(filter,projection,StudentCollection);

    foreach (var student in studentdetails)

         if (getsection.studenttab =null)
    {
        _logger.log("something");

    continue;
    }

    some other busiess logic
    }
   return abc;**

    After using Parallel.Foreach
    *****************************

    **Parallel.Foreach(studentdetails , resource =>
    {
         if (getsection.studenttab =null)
    {
        _logger.log("something");

         continue;
    }

    some other busiess logic

    });
return abc;

But I am getting this error: no enclosing loop out of which is break or continue.
and Metadata projectname.dll could not be found
What should I do here?

Body: Use return instead of continue.


问:
How to rename and save files which are already on the list
my app has a function to read file names and display them in the first column one by one in the DataGridView. What I want to do is, if users type in new names in the second column next to its original name, and then press the 'save as' button, files get saved consequently as newly typed in names, according to the order of the list.

I didn't bind it with DB or something like that.

My guess is that if users click save as button, it calls the code of each newly named block, and bring that code to 'save as' function. But I have no idea how I could realize it. Maybe my guess is totally wrong; you could give some advice so that I can find a right way!

I kindly ask for you help!

Here's my code

```<code> private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
            ofd.Multiselect = true;
            string ndn = "";//neue Dateinamen
            bool umlaut, pdf, wasserzeichen;
            int kopien;

                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    string[] selectedFiles = ofd.SafeFileNames;
                    for (int i = 0; i < ofd.FileNames.Count() - 1; i++)
                    {
                        dataGridView1.Rows.Add(selectedFiles[i]);
                        dataGridView1.Rows[i].Cells["Dateinamen"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Neue Dateinamen"].Value.ToString();  // Here I tried to save values of new names
                        dataGridView1.Rows[i].Cells["Kopien"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Wasserzeichen"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Umlaut"].Value.ToString();
                        dataGridView1.Rows[i].Cells["PDF"].Value.ToString();

                    }
                }

 private void button7_Click(object sender, EventArgs e) //Save as
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.CheckFileExists = true;
            saveFileDialog1.CheckPathExists = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                }

            }
        }

        }
</code>```

答:
Try the following code for the save button

```<code>private void SaveWithName_Click(object sender, EventArgs e)
    {
        int row = dataGridView1.CurrentCell.RowIndex;
        string OldName = Path.Combine(FilesPath, dataGridView1.Rows[row].Cells[0].Value.ToString());
        string NewName = Path.Combine(FilesPath, dataGridView1.Rows[row].Cells[1].Value.ToString()) ;
        System.IO.File.Copy(OldName, NewName);
    }
</code>```

The variable FilesPath is a public string. This variable will contain the directory name where your selected files are. Look an example of the code for the button that reads the file list

```<code>if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string[] selectedFiles = ofd.SafeFileNames;
            FilesPath = Path.GetDirectoryName(ofd.FileName);

            label1.Text = FilesPath;
            for (int i = 0; i < ofd.FileNames.Count(); i++)
            {
                dataGridView1.Rows.Add(selectedFiles[i]);
            }
        }
</code>```

There you can see the line where the variable FilesPath is filled.

Body:
my app has a function to read file names and display them in the first column one by one in the DataGridView. What I want to do is, if users type in new names in the second column next to its original name, and then press the 'save as' button, files get saved consequently as newly typed in names, according to the order of the list.

I didn't bind it with DB or something like that.

My guess is that if users click save as button, it calls the code of each newly named block, and bring that code to 'save as' function. But I have no idea how I could realize it. Maybe my guess is totally wrong; you could give some advice so that I can find a right way!

I kindly ask for you help!

Here's my code

 private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
            ofd.Multiselect = true;
            string ndn = "";//neue Dateinamen
            bool umlaut, pdf, wasserzeichen;
            int kopien;

                if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {

                    string[] selectedFiles = ofd.SafeFileNames;
                    for (int i = 0; i < ofd.FileNames.Count() - 1; i++)
                    {
                        dataGridView1.Rows.Add(selectedFiles[i]);
                        dataGridView1.Rows[i].Cells["Dateinamen"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Neue Dateinamen"].Value.ToString();  // Here I tried to save values of new names
                        dataGridView1.Rows[i].Cells["Kopien"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Wasserzeichen"].Value.ToString();
                        dataGridView1.Rows[i].Cells["Umlaut"].Value.ToString();
                        dataGridView1.Rows[i].Cells["PDF"].Value.ToString();

                    }
                }

 private void button7_Click(object sender, EventArgs e) //Save as
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Word(*.docx)| *.docx|PPT(*.pptx)|*.pptx|PDF(*.pdf)|*.pdf|Alle Dateien(*.*)|*.*";
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.CheckFileExists = true;
            saveFileDialog1.CheckPathExists = true;
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {

                }

            }
        }

        }

Body:
Try the following code for the save button

private void SaveWithName_Click(object sender, EventArgs e)
    {
        int row = dataGridView1.CurrentCell.RowIndex;
        string OldName = Path.Combine(FilesPath, dataGridView1.Rows[row].Cells[0].Value.ToString());
        string NewName = Path.Combine(FilesPath, dataGridView1.Rows[row].Cells[1].Value.ToString()) ;
        System.IO.File.Copy(OldName, NewName);
    }

The variable FilesPath is a public string. This variable will contain the directory name where your selected files are. Look an example of the code for the button that reads the file list

if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string[] selectedFiles = ofd.SafeFileNames;
            FilesPath = Path.GetDirectoryName(ofd.FileName);

            label1.Text = FilesPath;
            for (int i = 0; i < ofd.FileNames.Count(); i++)
            {
                dataGridView1.Rows.Add(selectedFiles[i]);
            }
        }

There you can see the line where the variable FilesPath is filled.


问:
Spring Integration Gateway Without Reply in DSL
My question is very similar to this Stackoverflow Question in that I want to send to JMS and then carry on with my integration flow.

The response is totally asynchronous and is therefore handled on a separate Jms.messageDrivenChannelAdapter. So, I basically want to "fire and forget".

My code is this (Spring 5.3.14);

```<code>.enrichHeaders(
    h -> h.headerFunction("JMSCorrelationID", m -> m.getHeaders().get(MessageHeaders.ID))
)
.handle(
   Jms
      .outboundGateway(connectionFactory)
      .requestDestination(queueName)
   )
.handle(p -> System.err.println("Do something else with ... " + p))
.get();
</code>```

And I get this;

org.springframework.integration.MessageTimeoutException: failed to receive JMS response within timeout of: 5000ms,

The referenced answer to me implies that I need to listen to a dummy queue, which I don't want to have to do. So what do I need to fix in my code above?

Edit; final code using the solution below tested with/without "queue PUT inhibit" in order cause an exception.

```<code>.publishSubscribeChannel(s -> s
  .subscribe(f -> f.handle(
    Jms
      .outboundAdapter(connectionFactory)
      .destination(queueName)
  ))
  .subscribe(f -> f.handle(
    p -> System.err.println("Do something else with ... " + p)
  ))
)
</code>```

答: You need to use Jms.outboundChannelAdapter() instead. And together with that next handle() wrap them into a publishSubscribeChannel() as two subscribers sub-flows. This way they are going to be called one after other, but in parallel and their individual flows.

Body:
My question is very similar to this Stackoverflow Question in that I want to send to JMS and then carry on with my integration flow.

The response is totally asynchronous and is therefore handled on a separate Jms.messageDrivenChannelAdapter. So, I basically want to "fire and forget".

My code is this (Spring 5.3.14);

.enrichHeaders(
    h -> h.headerFunction("JMSCorrelationID", m -> m.getHeaders().get(MessageHeaders.ID))
)
.handle(
   Jms
      .outboundGateway(connectionFactory)
      .requestDestination(queueName)
   )
.handle(p -> System.err.println("Do something else with ... " + p))
.get();

And I get this;

org.springframework.integration.MessageTimeoutException: failed to receive JMS response within timeout of: 5000ms,

The referenced answer to me implies that I need to listen to a dummy queue, which I don't want to have to do. So what do I need to fix in my code above?

Edit; final code using the solution below tested with/without "queue PUT inhibit" in order cause an exception.

.publishSubscribeChannel(s -> s
  .subscribe(f -> f.handle(
    Jms
      .outboundAdapter(connectionFactory)
      .destination(queueName)
  ))
  .subscribe(f -> f.handle(
    p -> System.err.println("Do something else with ... " + p)
  ))
)


问:
Play audio html
how can i  play audio like its a notification.

as soon as the page is opened the notification audio starts beeping.

and it has to beep every 3 seconds

```<code><!DOCTYPE html>
<html>
    <head>
       <script>
     var aSound = document.createElement('audio');
     aSound.setAttribute('src', '/path/beep.wav');
     aSound.play();
 </script>
    </head>
    <body>
        <p>hello world</p>
    </body>
</html>
</code>```

答:
The main problem of your code is, that the audio element is never added to the DOM. By calling document.createElement you just create the element, but it is never added to your page.

To do so, you could use the following code line:

    document.getElementsByTagName('body')[0].appendChild(aSound);
```
<p>This will add the audio element to the end of the <code>body</code> element. However, you can only do this after the DOM has been created. Currently, your code is executed before any element exists at all. The code must wait until after the page is fully loaded.</p>
<p>To play the sound repeatedly, you can simply use <code>window.setInterval</code> if the audio file is less than three seconds long.</p>
<p>Below is a full example:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
       <script>
            // Execute the code inside, after the page was loaded
            window.addEventListener("load", () => {
                var aSound = document.createElement('audio');
                aSound.setAttribute('src', '/path/beep.wav');
                // Append element to the DOM
                document.getElementsByTagName('body')[0].appendChild(aSound);
                aSound.play()
                // Execute the code inside every 3 seconds
                window.setInterval(() => {
                    aSound.play()
                }, 3000);
            })

        </script>
    </head>
    <body>
        <p>hello world</p>
    </body>
</html>
</code>```

Keep in mind, that many browsers these days block autoplaying audio and video content. I had to allow this in Firefox for my test page, so this is not suitable for public pages.

Title: Play audio html

Body:
how can i  play audio like its a notification.

as soon as the page is opened the notification audio starts beeping.

and it has to beep every 3 seconds

<!DOCTYPE html>

hello world

Body:
The main problem of your code is, that the audio element is never added to the DOM. By calling document.createElement you just create the element, but it is never added to your page.

To do so, you could use the following code line:

    document.getElementsByTagName('body')[0].appendChild(aSound);

This will add the audio element to the end of the body element. However, you can only do this after the DOM has been created. Currently, your code is executed before any element exists at all. The code must wait until after the page is fully loaded.

To play the sound repeatedly, you can simply use window.setInterval if the audio file is less than three seconds long.

Below is a full example:

<!DOCTYPE html>
<html>
    <head>
       <script>
            // Execute the code inside, after the page was loaded
            window.addEventListener("load", () => {
                var aSound = document.createElement('audio');
                aSound.setAttribute('src', '/path/beep.wav');
                // Append element to the DOM
                document.getElementsByTagName('body')[0].appendChild(aSound);
                aSound.play()
                // Execute the code inside every 3 seconds
                window.setInterval(() => {
                    aSound.play()
                }, 3000);
            })

        </script>
    </head>
    <body>
        <p>hello world</p>
    </body>
</html>

Keep in mind, that many browsers these days block autoplaying audio and video content. I had to allow this in Firefox for my test page, so this is not suitable for public pages.


问:
datetime parameter between 3 datetime columns
I need to get my @from and @to to be between SalesPos.startdate,SalesPosDamageH.CreatedTime,SalesPosReturnH.CreatedTime
and I don't know how to write my where clause in that case.

I have tried multiple ways with no success.

This is my current attempt:

ALTER PROC rpt_Item_salesanalysis --rpt_Item_salesanalysis '2021-01-05 22:14:20.613','2022-02-02 12:05:38.183',null
    @from datetime = NULL,
    @to datetime = NULL,
    @barcode nvarchar(50) = NULL
AS
    SELECT GrpItm.nname AS GrpName,
           SalesPos_Dtls.ItemCode,
           SalesPos_Dtls.ItemName,
           SalesPos_Dtls.TotalPrice AS DtlsAfterDiscountDtls,
           SalesPos_Dtls.NTotalPriceWithoutTax AS DtlsBFDiscountDtls,
           SalesPos_Dtls.OrderId AS countOrderID,
           SalesPosReturnD.ReturnPrice AS TotalReturnDtls,
           SalesPosReturnD.ItemID AS ReturnItemIDCount,
           SalesPosDamageD.ReturnPrice AS DamageTotalDTLs,
           SalesPosDamageD.ItemID AS CountFromDmg
    FROM GrpItm
         LEFT JOIN Itms ON Itms.nparent = GrpItm.nodeid
         LEFT JOIN SalesPos_Dtls ON SalesPos_Dtls.ItemId = Itms.nodeid
         INNER JOIN SalesPos ON SalesPos_Dtls.OrderId = SalesPos.ID
         LEFT JOIN SalesPosReturnH ON SalesPosReturnH.SalesPosID = SalesPos.ID
         LEFT JOIN SalesPosReturnD ON SalesPosReturnH.ID = SalesPosReturnD.SalesPosReturnID
                                  AND SalesPos_Dtls.ItemId = SalesPosReturnD.ItemID
         LEFT JOIN SalesPosDamageH ON SalesPosDamageH.SalesPosID = SalesPos.ID
         LEFT JOIN SalesPosDamageD ON SalesPosDamageD.SalesPosReturnID = SalesPosDamageH.ID
                                  AND SalesPos_Dtls.ItemId = SalesPosDamageD.ItemID
    WHERE ((@from <= SalesPos.startdate
        AND @from <= SalesPosDamageH.CreatedTime
        AND @from <= SalesPosReturnH.CreatedTime
         OR @from IS NULL)
       AND (@to >= SalesPos.startdate
        AND @to >= SalesPosDamageH.CreatedTime
        AND @to >= SalesPosReturnH.CreatedTime
         OR @to IS NULL))
      AND (@barcode = SalesPos_Dtls.ItemCode
        OR @barcode IS NULL);
```

答:
When using LEFT JOIN one needs to watch out what's put in the WHERE clause.

Because it could make a LEFT JOIN behave like an INNER JOIN.

For example:

```<code>select *
from TableA a
left join TableB b ON b.a_id = a.a_id
where b.code = '42'
</code>```

Will return exactly the same as:

```<code>select *
from TableA a
inner join TableB b ON b.a_id = a.a_id
where b.code = '42'
</code>```

But could be different if that extra criteria is in the ON clause:

```<code>select *
from TableA a
left join TableB b ON b.a_id = a.a_id AND b.code = '42'
</code>```

This will at least return all from TableA.

So if you think some data is missing, it could be because it filters to much.

Also, AND is evaluated before OR.  So it's best to use parenthesis () when using both.

```<code>...
FROM GrpItm
LEFT JOIN Itms
  ON Itms.nparent = GrpItm.nodeid
LEFT JOIN SalesPos_Dtls
  ON SalesPos_Dtls.ItemId = Itms.nodeid
 AND (@barcode IS NULL OR SalesPos_Dtls.ItemCode = @barcode)
INNER JOIN SalesPos
  ON  SalesPos.ID = SalesPos_Dtls.OrderId
 AND (@from IS NULL OR @from <= SalesPos.startdate)
 AND (@to IS NULL OR @to >= SalesPos.startdate)
LEFT JOIN SalesPosReturnH
  ON SalesPosReturnH.SalesPosID = SalesPos.ID
 AND (@from IS NULL OR @from <= SalesPosReturnH.CreatedTime)
 AND (@to IS NULL OR @to >= SalesPosReturnH.CreatedTime)
LEFT JOIN SalesPosReturnD
  ON SalesPosReturnD.SalesPosReturnID = SalesPosReturnH.ID
 AND SalesPosReturnD.ItemID = SalesPos_Dtls.ItemId
LEFT JOIN SalesPosDamageH
  ON SalesPosDamageH.SalesPosID = SalesPos.ID
 AND (@from IS NULL OR @from <= SalesPosDamageH.CreatedTime)
 AND (@to IS NULL OR @to >= SalesPosDamageH.CreatedTime)
LEFT JOIN SalesPosDamageD
  ON SalesPosDamageD.SalesPosReturnID = SalesPosDamageH.ID
 AND SalesPosDamageD.ItemID = SalesPos_Dtls.ItemId;
</code>```

Body:
When using LEFT JOIN one needs to watch out what's put in the WHERE clause.

Because it could make a LEFT JOIN behave like an INNER JOIN.

For example:

select *
from TableA a
left join TableB b ON b.a_id = a.a_id
where b.code = '42'

Will return exactly the same as:

select *
from TableA a
inner join TableB b ON b.a_id = a.a_id
where b.code = '42'

But could be different if that extra criteria is in the ON clause:

select *
from TableA a
left join TableB b ON b.a_id = a.a_id AND b.code = '42'

This will at least return all from TableA.

So if you think some data is missing, it could be because it filters to much.

Also, AND is evaluated before OR.  So it's best to use parenthesis () when using both.

...
FROM GrpItm
LEFT JOIN Itms
  ON Itms.nparent = GrpItm.nodeid
LEFT JOIN SalesPos_Dtls
  ON SalesPos_Dtls.ItemId = Itms.nodeid
 AND (@barcode IS NULL OR SalesPos_Dtls.ItemCode = @barcode)
INNER JOIN SalesPos
  ON  SalesPos.ID = SalesPos_Dtls.OrderId
 AND (@from IS NULL OR @from <= SalesPos.startdate)
 AND (@to IS NULL OR @to >= SalesPos.startdate)
LEFT JOIN SalesPosReturnH
  ON SalesPosReturnH.SalesPosID = SalesPos.ID
 AND (@from IS NULL OR @from <= SalesPosReturnH.CreatedTime)
 AND (@to IS NULL OR @to >= SalesPosReturnH.CreatedTime)
LEFT JOIN SalesPosReturnD
  ON SalesPosReturnD.SalesPosReturnID = SalesPosReturnH.ID
 AND SalesPosReturnD.ItemID = SalesPos_Dtls.ItemId
LEFT JOIN SalesPosDamageH
  ON SalesPosDamageH.SalesPosID = SalesPos.ID
 AND (@from IS NULL OR @from <= SalesPosDamageH.CreatedTime)
 AND (@to IS NULL OR @to >= SalesPosDamageH.CreatedTime)
LEFT JOIN SalesPosDamageD
  ON SalesPosDamageD.SalesPosReturnID = SalesPosDamageH.ID
 AND SalesPosDamageD.ItemID = SalesPos_Dtls.ItemId;


问:
R using pipe instead of $ syntax
Syntax question. I want to filter a data set then run cor.test() without altering the original data set. I can do this in separate lines and by creating a separate data frame.

```<code>library(dplyr)

df <- data(trees)
df <- filter(trees, Girth >12)
cor.test(df$Girth, df$Height)
</code>```

However I'm trying to be more efficient. I want to do the same thing in a pipe and without needing to creating a new data frame. Specifically, what is the syntax for eliminating the $ for selecting columns?

答:
You can use with():

```<code>library(dplyr)

filter(trees, Girth > 12) |>
  with(cor.test(Girth, Height))
</code>```

In base R:

```<code>subset(trees, Girth > 12) |>
  with(cor.test(Girth, Height))
</code>```

Title: R using pipe instead of $ syntax

Body:
Syntax question. I want to filter a data set then run cor.test() without altering the original data set. I can do this in separate lines and by creating a separate data frame.

library(dplyr)

df <- data(trees)
df <- filter(trees, Girth >12)
cor.test(df$Girth, df$Height)

However I'm trying to be more efficient. I want to do the same thing in a pipe and without needing to creating a new data frame. Specifically, what is the syntax for eliminating the $ for selecting columns?

Body:
You can use with():

library(dplyr)

filter(trees, Girth > 12) |>
  with(cor.test(Girth, Height))

In base R:

subset(trees, Girth > 12) |>
  with(cor.test(Girth, Height))


问:
Buttons under each other in div
i created div for some buttons in a kind of sidebar.
But I am not quite sure how do I get them under each other...

My previous solution were 2 divs under eachother but then it was not that could regarding the various display sizes that the buttons are directly under each other...

Any idea?

#sideBar {
  position: fixed;
  right: -29px;
  top: 52vh;
  display: inline-grid;
}

#feedbackBtn {
  z-index: 1000;
  transform: rotate(270deg);
}

#helpBtn {
  z-index: 1000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sideBar">
  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default"></Button>
</div></code>```

Image

答:
You could remove the display: inline-grid property from #sideBar, e.g.

#sideBar {
  position: fixed;
  right: 0px;
  top: 52vh;
  transform: rotate(270deg);
  z-index: 1000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="sideBar">
  <button id="feedbackBtn">Feedback</button>
  <button id="helpBtn">Help</button>
</div></code>```

Title: Buttons under each other in div

Body:
i created div for some buttons in a kind of sidebar.
But I am not quite sure how do I get them under each other...

My previous solution were 2 divs under eachother but then it was not that could regarding the various display sizes that the buttons are directly under each other...

Any idea?

#sideBar {
  position: fixed;
  right: -29px;
  top: 52vh;
  display: inline-grid;
}

#feedbackBtn {
  z-index: 1000;
  transform: rotate(270deg);
}

#helpBtn {
  z-index: 1000;
}

  <Button id="feedbackBtn" onClick={onButtonClick} design="Emphasized">
          Feedback
        </Button>

  <Button id="helpBtn" icon="sys-help" onClick={onButtonClickHelp} design="Default"></Button>

Image

Body:
You could remove the display: inline-grid property from #sideBar, e.g.

#sideBar {
  position: fixed;
  right: 0px;
  top: 52vh;
  transform: rotate(270deg);
  z-index: 1000;
}

<div id="sideBar">
  <button id="feedbackBtn">Feedback</button>
  <button id="helpBtn">Help</button>
</div>


问:
Trying to get only cells with certain initials but giving me syntax error? SQL
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

```<code> SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id
</code>```

答:
JOIN should always be placed just after FROM table-name. The below should work

SELECT first_name, last_name, title FROM members
JOIN withdrawals

ON members.member_id  = withdrawals.member_id
JOIN books
ON withdrawals.book_id = books.book_id
WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'

Body:
So my assignment question is to "Get a list of all books withdrawn by people with the initials 'B.W.'. Show a column for the first name, last name, initials, and the title of the book". I am trying to join these 3 tables as it is the only way to get this information, but Im having a hard time only displaying names with initials B.W. I get a syntax error saying:

"You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'JOIN withdrawals

When I remove my 'WHERE' statement (all of the second line), my syntax error goes away. How do I make this work?

Below is my code:

 SELECT first_name, last_name, title FROM members
     WHERE first_name LIKE 'B%' AND last_name LIKE 'W%'
      JOIN withdrawals
        ON members.member_id  = withdrawals.member_id
         JOIN books
             ON withdrawals.book_id = books.book_id


问:
How to pass data between activities forward and backward, android, kotlin
Let's say my application has 4 activities (A -> B -> C -> D) when going forward, activity A pass a data value called category to activity B and then activity B pass category and also and data value called level and both used in activity D to get data from firebase realtime database. but when the user goes back to activity C and tries to go again to D data passed from A (category) is now null. so data can't retrieve from firebase. my question is how can I solve this situation.? "I pass data using Intent by putting extras." are there any other ways?

答:
you could use startactivityforresult and set a result intent which includes the data you want to pass back
https://developer.android.com/training/basics/intents/result</p>


问:
Laravel Eloquent toArray method
I add the toArray() method because I need the result in an array format; it displays the error below. So I wonder how I can fix it? How can I create that query in an array?

```<code>HrHorizontalPreviredCalculation::from('hr_horizontal_previred_calculations')
    ->selectRaw('`Rut`,`DV`,`Apellido Paterno`,`Apellido Materno`,`Nombre`,`Sexo`,`Nacion`,`Tipo Pago`,`Periodo Desde`,`Periodo Hasta`,`Regimen`,`Tipo Trabajador`,`Dias Trabajados`,`Tipo Linea`,`Cod Movi`,`Fecha Desde`,`Fecha Hasta`,`Tramo Fam`,`Cargas Simples`,`Cargas Mat`,`Cargas Inv`,`Asig Familiar`,`Asig RetroAct`,`Reint Cargas`,`Sub Trab Jov`,`AFP`,`Impo Afp`,`Cot AFP`,`Aporte SIS`,`Ahorro AFP`,`Sust AFP`,`Tasa Pac AFP`,`Aporte idem`,`Num Per Sust`,`Per Desde Sust`,`Per Hasta Sust`,`Trab Pesado`,`% Trab Pesado`,`Cot Trab Pesado`,`Inst APVI`,`Num Contra APVI`,`Forma Pago APVI`,`Cotiza APVI`,`Cot Dep Conv`,`Inst APVC`,`Num Contra APVC`,`Forma Pago APVC`,`Cotiza APVC`,`Cot Emp APVC`,`Rut afi Volun`,`DV afi Volun`,`Ape Pat Volun`,`Ape Mat Volun`,`Nombre volun`,`Cod Mov Per`,`Fec Desde volun`,`Fec Hasta volun`,`Cod Afp volun`,`Monto Cap Volun`,`Monto aho Vol`,`Num Per Cotiza`,`Cod Ex caja`,`Tasa ex caja`,`Renta imp Fonasa`,`Cod INP`,`Renta desahu`,`Cod ex caja des`,`Tasa ex caja des`,`Cot Desahucio`,`Cotiza Fonasa`,`Cot Acc Trab INP`,`Boni Ley`,`Cargas fam INP`,`Bonos Gob`,`Cod Inst Salud`,`Num FUN`,`Impo Isapre`,`Moneda Plan`,`Cot Pactada`,`Cot Obli Isapre`,`Cot Ad Vol`,`Monto Ges`,`Cod CCAF`,`Impo CCAF`,`Cred Per CCAF`,`Desc Dental`,`Desc Leasing`,`Desc Seg Vida`,`Otros desc CCAF`,`Cot CCAF`,`Car Fam CCAF`,`Otros desc CCAF1`,`Otros desc CCAF2`,`Bono gob CCAF`,`Cod Sucur CCAF`,`Cod Mutual`,`Impo Mutual`,`Cotiza Mutual`,`Sucur Mutual`,`Renta Impo SC`,`Aporte Trab SC`,`Aporte empleador`,`Rut Pag Subs`,`DV Pag Subs`,`Centro costo`')
    ->where('period', $period)
    ->orderBy('employee_id', 'ASC')
    ->get();
</code>```

message: "Call to undefined method
Illuminate\Database\Eloquent\Builder::toArray()"

答:
if you want to use toArray()

```<code>HrHorizontalPreviredCalculation::from('hr_horizontal_previred_calculations')
                ->selectRaw('`Rut`,`DV`,`Apellido Paterno`,`Apellido Materno`,`Nombre`,`Sexo`,`Nacion`,`Tipo Pago`,`Periodo Desde`,`Periodo Hasta`,`Regimen`,`Tipo Trabajador`,`Dias Trabajados`,`Tipo Linea`,`Cod Movi`,`Fecha Desde`,`Fecha Hasta`,`Tramo Fam`,`Cargas Simples`,`Cargas Mat`,`Cargas Inv`,`Asig Familiar`,`Asig RetroAct`,`Reint Cargas`,`Sub Trab Jov`,`AFP`,`Impo Afp`,`Cot AFP`,`Aporte SIS`,`Ahorro AFP`,`Sust AFP`,`Tasa Pac AFP`,`Aporte idem`,`Num Per Sust`,`Per Desde Sust`,`Per Hasta Sust`,`Trab Pesado`,`% Trab Pesado`,`Cot Trab Pesado`,`Inst APVI`,`Num Contra APVI`,`Forma Pago APVI`,`Cotiza APVI`,`Cot Dep Conv`,`Inst APVC`,`Num Contra APVC`,`Forma Pago APVC`,`Cotiza APVC`,`Cot Emp APVC`,`Rut afi Volun`,`DV afi Volun`,`Ape Pat Volun`,`Ape Mat Volun`,`Nombre volun`,`Cod Mov Per`,`Fec Desde volun`,`Fec Hasta volun`,`Cod Afp volun`,`Monto Cap Volun`,`Monto aho Vol`,`Num Per Cotiza`,`Cod Ex caja`,`Tasa ex caja`,`Renta imp Fonasa`,`Cod INP`,`Renta desahu`,`Cod ex caja des`,`Tasa ex caja des`,`Cot Desahucio`,`Cotiza Fonasa`,`Cot Acc Trab INP`,`Boni Ley`,`Cargas fam INP`,`Bonos Gob`,`Cod Inst Salud`,`Num FUN`,`Impo Isapre`,`Moneda Plan`,`Cot Pactada`,`Cot Obli Isapre`,`Cot Ad Vol`,`Monto Ges`,`Cod CCAF`,`Impo CCAF`,`Cred Per CCAF`,`Desc Dental`,`Desc Leasing`,`Desc Seg Vida`,`Otros desc CCAF`,`Cot CCAF`,`Car Fam CCAF`,`Otros desc CCAF1`,`Otros desc CCAF2`,`Bono gob CCAF`,`Cod Sucur CCAF`,`Cod Mutual`,`Impo Mutual`,`Cotiza Mutual`,`Sucur Mutual`,`Renta Impo SC`,`Aporte Trab SC`,`Aporte empleador`,`Rut Pag Subs`,`DV Pag Subs`,`Centro costo`')
                ->where('period', $period)
                ->orderBy('employee_id', 'ASC')
                ->get()->toArray();
</code>```

hopefully that help you

Title: Laravel Eloquent toArray method

Body:
I add the toArray() method because I need the result in an array format; it displays the error below. So I wonder how I can fix it? How can I create that query in an array?

HrHorizontalPreviredCalculation::from('hr_horizontal_previred_calculations')
    ->selectRaw('`Rut`,`DV`,`Apellido Paterno`,`Apellido Materno`,`Nombre`,`Sexo`,`Nacion`,`Tipo Pago`,`Periodo Desde`,`Periodo Hasta`,`Regimen`,`Tipo Trabajador`,`Dias Trabajados`,`Tipo Linea`,`Cod Movi`,`Fecha Desde`,`Fecha Hasta`,`Tramo Fam`,`Cargas Simples`,`Cargas Mat`,`Cargas Inv`,`Asig Familiar`,`Asig RetroAct`,`Reint Cargas`,`Sub Trab Jov`,`AFP`,`Impo Afp`,`Cot AFP`,`Aporte SIS`,`Ahorro AFP`,`Sust AFP`,`Tasa Pac AFP`,`Aporte idem`,`Num Per Sust`,`Per Desde Sust`,`Per Hasta Sust`,`Trab Pesado`,`% Trab Pesado`,`Cot Trab Pesado`,`Inst APVI`,`Num Contra APVI`,`Forma Pago APVI`,`Cotiza APVI`,`Cot Dep Conv`,`Inst APVC`,`Num Contra APVC`,`Forma Pago APVC`,`Cotiza APVC`,`Cot Emp APVC`,`Rut afi Volun`,`DV afi Volun`,`Ape Pat Volun`,`Ape Mat Volun`,`Nombre volun`,`Cod Mov Per`,`Fec Desde volun`,`Fec Hasta volun`,`Cod Afp volun`,`Monto Cap Volun`,`Monto aho Vol`,`Num Per Cotiza`,`Cod Ex caja`,`Tasa ex caja`,`Renta imp Fonasa`,`Cod INP`,`Renta desahu`,`Cod ex caja des`,`Tasa ex caja des`,`Cot Desahucio`,`Cotiza Fonasa`,`Cot Acc Trab INP`,`Boni Ley`,`Cargas fam INP`,`Bonos Gob`,`Cod Inst Salud`,`Num FUN`,`Impo Isapre`,`Moneda Plan`,`Cot Pactada`,`Cot Obli Isapre`,`Cot Ad Vol`,`Monto Ges`,`Cod CCAF`,`Impo CCAF`,`Cred Per CCAF`,`Desc Dental`,`Desc Leasing`,`Desc Seg Vida`,`Otros desc CCAF`,`Cot CCAF`,`Car Fam CCAF`,`Otros desc CCAF1`,`Otros desc CCAF2`,`Bono gob CCAF`,`Cod Sucur CCAF`,`Cod Mutual`,`Impo Mutual`,`Cotiza Mutual`,`Sucur Mutual`,`Renta Impo SC`,`Aporte Trab SC`,`Aporte empleador`,`Rut Pag Subs`,`DV Pag Subs`,`Centro costo`')
    ->where('period', $period)
    ->orderBy('employee_id', 'ASC')
    ->get();

message: "Call to undefined method
Illuminate\Database\Eloquent\Builder::toArray()"

Body:
if you want to use toArray()

HrHorizontalPreviredCalculation::from('hr_horizontal_previred_calculations')
                ->selectRaw('`Rut`,`DV`,`Apellido Paterno`,`Apellido Materno`,`Nombre`,`Sexo`,`Nacion`,`Tipo Pago`,`Periodo Desde`,`Periodo Hasta`,`Regimen`,`Tipo Trabajador`,`Dias Trabajados`,`Tipo Linea`,`Cod Movi`,`Fecha Desde`,`Fecha Hasta`,`Tramo Fam`,`Cargas Simples`,`Cargas Mat`,`Cargas Inv`,`Asig Familiar`,`Asig RetroAct`,`Reint Cargas`,`Sub Trab Jov`,`AFP`,`Impo Afp`,`Cot AFP`,`Aporte SIS`,`Ahorro AFP`,`Sust AFP`,`Tasa Pac AFP`,`Aporte idem`,`Num Per Sust`,`Per Desde Sust`,`Per Hasta Sust`,`Trab Pesado`,`% Trab Pesado`,`Cot Trab Pesado`,`Inst APVI`,`Num Contra APVI`,`Forma Pago APVI`,`Cotiza APVI`,`Cot Dep Conv`,`Inst APVC`,`Num Contra APVC`,`Forma Pago APVC`,`Cotiza APVC`,`Cot Emp APVC`,`Rut afi Volun`,`DV afi Volun`,`Ape Pat Volun`,`Ape Mat Volun`,`Nombre volun`,`Cod Mov Per`,`Fec Desde volun`,`Fec Hasta volun`,`Cod Afp volun`,`Monto Cap Volun`,`Monto aho Vol`,`Num Per Cotiza`,`Cod Ex caja`,`Tasa ex caja`,`Renta imp Fonasa`,`Cod INP`,`Renta desahu`,`Cod ex caja des`,`Tasa ex caja des`,`Cot Desahucio`,`Cotiza Fonasa`,`Cot Acc Trab INP`,`Boni Ley`,`Cargas fam INP`,`Bonos Gob`,`Cod Inst Salud`,`Num FUN`,`Impo Isapre`,`Moneda Plan`,`Cot Pactada`,`Cot Obli Isapre`,`Cot Ad Vol`,`Monto Ges`,`Cod CCAF`,`Impo CCAF`,`Cred Per CCAF`,`Desc Dental`,`Desc Leasing`,`Desc Seg Vida`,`Otros desc CCAF`,`Cot CCAF`,`Car Fam CCAF`,`Otros desc CCAF1`,`Otros desc CCAF2`,`Bono gob CCAF`,`Cod Sucur CCAF`,`Cod Mutual`,`Impo Mutual`,`Cotiza Mutual`,`Sucur Mutual`,`Renta Impo SC`,`Aporte Trab SC`,`Aporte empleador`,`Rut Pag Subs`,`DV Pag Subs`,`Centro costo`')
                ->where('period', $period)
                ->orderBy('employee_id', 'ASC')
                ->get()->toArray();

hopefully that help you


问:
How to load a local html file inside an iframe in my react application?
I'm having troubles when trying to load a html file from my public folder in a React application created with create-react-app. Am I missing a config setting somewhere in webpack?

I currently have this folder structure:

And I want to show the test.html file inside an Iframe in my React component like this:

```<code>import React from 'react';

const Component = props => {
  return (<iframe src="/test/index.html"title="Docuvieware" />);
};

export default Component;
</code>```

But this is giving me a "Cannot GET /test/index.html" in the Iframe. Also when surfing directly to http://localhost:3000/test/index.html I get a white page that says 'Cannot GET /test/index.html'

I also tried to use "process.env.PUBLIC_URL" inside my component but this was undefined.

答:
I have managed to fix this by using CopyWebpackPlugin.
Just added the test folder in my src folder, and then added the following line to my webpack config:

```<code>new CopyWebpackPlugin([{ from: 'src/test', to: 'test' }]),
</code>```

and then /test/index.html gave the correct path.

Body:
I'm having troubles when trying to load a html file from my public folder in a React application created with create-react-app. Am I missing a config setting somewhere in webpack?

I currently have this folder structure:

And I want to show the test.html file inside an Iframe in my React component like this:

import React from 'react';

const Component = props => {
  return ();
};

export default Component;

But this is giving me a "Cannot GET /test/index.html" in the Iframe. Also when surfing directly to http://localhost:3000/test/index.html I get a white page that says 'Cannot GET /test/index.html'

I also tried to use "process.env.PUBLIC_URL" inside my component but this was undefined.

Body:
I have managed to fix this by using CopyWebpackPlugin.
Just added the test folder in my src folder, and then added the following line to my webpack config:

new CopyWebpackPlugin([{ from: 'src/test', to: 'test' }]),

and then /test/index.html gave the correct path.


问:
How to mock a DB connection in RestController Test?
I have a Rest controller GET method

```<code>@GetMapping("/users")
public List<Users> getAllUsers() {
    return userRepo.findAll()
}
</code>```

I need to test it, but I get the "Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured". The problem is that the nature of production does not allow me to use real connection or change it to embedded one. Is there a way to mock the DB somehow?

 The project is almost the same to the one in this article:
https://dzone.com/articles/how-to-create-rest-api-with-spring-boot

答:
Either you can use @MockBean annotation to mock the UserRepository or you can create an embedded in-memory H2 DB for the test by adding following properties in application-test.properties:

```<code>spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
</code>```

You can follow this link to understand it in detail.

Body:
I have a Rest controller GET method

@GetMapping("/users")
public List<Users> getAllUsers() {
    return userRepo.findAll()
}

I need to test it, but I get the "Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured". The problem is that the nature of production does not allow me to use real connection or change it to embedded one. Is there a way to mock the DB somehow?

 The project is almost the same to the one in this article:
https://dzone.com/articles/how-to-create-rest-api-with-spring-boot

Body:
Either you can use @MockBean annotation to mock the UserRepository or you can create an embedded in-memory H2 DB for the test by adding following properties in application-test.properties:

spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect

You can follow this link to understand it in detail.


问:
FreeRadius LDAP group check
I want to implement 802.1x. The computers belonging to Microsoft domey will be authenticated. The switch port will be configured in VLAN according to the computer's group membership. Simple configuration. Works well ;) FreeRadius 3.0.19

Question: due to AD complexity, is it possible to assign the same VLAN to computers from different groups?

Currently I'm doing it as follows:
in post-auth

```<code>if (Ldap-Group == VLAN16_SIEO1) {
    update reply {
        ...
    }
}
</code>```

I want to allocate the same VLAN to groups such as VLAN16_BSTO1 and VLAN16_ADMCE1 and others starting with VLAN16_

I cannot use the operator in the condition "if" =~ . FreeRadius does not start! Is it possible to check the group name so as not to create many "if" conditions?
In my case these conditions will be about 800 :)

anyone can help me, tell me how to config can solve this problem, thanks.

答:
I just wanted thank Arran!

For anyone else the following syntax got it working:

```<code>if (&control:LDAP-Cached-Membership[*] =~ /.*foo.*/) {
</code>```

Title: FreeRadius LDAP group check

Body:
I want to implement 802.1x. The computers belonging to Microsoft domey will be authenticated. The switch port will be configured in VLAN according to the computer's group membership. Simple configuration. Works well ;) FreeRadius 3.0.19

Question: due to AD complexity, is it possible to assign the same VLAN to computers from different groups?

Currently I'm doing it as follows:
in post-auth

if (Ldap-Group == VLAN16_SIEO1) {
    update reply {
        ...
    }
}

I want to allocate the same VLAN to groups such as VLAN16_BSTO1 and VLAN16_ADMCE1 and others starting with VLAN16_

I cannot use the operator in the condition "if" =~ . FreeRadius does not start! Is it possible to check the group name so as not to create many "if" conditions?
In my case these conditions will be about 800 :)

anyone can help me, tell me how to config can solve this problem, thanks.

Body:
I just wanted thank Arran!

For anyone else the following syntax got it working:

if (&control:LDAP-Cached-Membership[*] =~ /.*foo.*/) {


问:
Change background-image with jQuery - doesn´t work
```<code>$('#areaView').css('background-image', 'url(/areaNr1.jpg)');
</code>```

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

答:
```<code>$('#areaView').css('background-image', 'url(/jQuery/areaNr1.jpg)');
</code>```

this might solve the problem

Body:
$('#areaView').css('background-image', 'url(/areaNr1.jpg)');

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

Body:
$('#areaView').css('background-image', 'url(/jQuery/areaNr1.jpg)');

this might solve the problem


问:
Problem: I can't display values i want from my queries and database in a component on Laravel Livewire
I'm still new on Laravel and I'm still working on this project now:
So basically I have a table Recipes containing recipes with a name and vegetabes, a pivot table Recipes_vegetables and a table vegetables.
What i want is a search input that is gonna give me the values of my different tables that fit the input.
So this is my code:

Search.php:

```<code><?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Vegetable;
use App\Models\Recipe;

class Search extends Component
{
    public $query = '';

    public $vegetables;
    public $recipes;

    public function updatedQuery()
    {
        $this->vegetables = Vegetable::where('name', 'like', '%'.$this->query.'%')
                            ->with('recipes')
                            ->get();

        $this->recipes = Recipe::where('name', 'like', '%'.$this->query.'%')
                            ->with('vegetables')
                            ->get();
    }

    public function render()
    {
        return view('livewire.search');
    }
}
</code>```

search.blade.php :

```<code><div class="searchcomponent">
  <h1>Search</h1>
  <input wire:model="query" type="text" placeholder="Search...">
  @if(!empty($query))
    <ul>
      @if(!empty($recipes))
        <div class="vegetables">
          @foreach($vegetables as $vegetable)

              <li><span class="material-icons">lunch_dining</span>{{ $vegetable->name }}</li>

          @endforeach
        </div>
      @else
        <li>No result</li>
      @endif
      <div class="recipes">
        @foreach($recipes as $recipe)
          @foreach($recipe->vegetables as $vegetable)
            <li><span class="material-icons">menu_book</span>{{ $recipe->name }}<span class="ingredient">Ingredient: {{ $vegetable->name }}</span></li>
          @endforeach
        @endforeach
      </div>
    </ul>
  @endif
</div>
</code>```

Recipe.php :

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Recipe extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function vegetables(){
        return $this->belongsToMany(Vegetable::class, 'vegetables_recipes', 'recipe_id', 'vegetable_id');
    }

}
</code>```

Vegetable.php :

```<code><?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

}
</code>```

So basically this is what i get right now:

1st case: I'm typing a vegetable's name in the input:

What I should have :

Get every vegetable's name that fits the input AND get every recipe's name that fits the input AND get every recipe that has a vegetable 's name that fits the input
Exemple: I have a fish and chips recipe that has 'Potatoes' as an ingredient linked with the pivot table. If i type 'Po' I should have on my render:

Potato

Fish and chips (because the recipe is made with potatoes)

What I actually have right now:

If i type 'po': I'm only getting the results that have 'Po' in their name, so i'm getting Potato, but i'm not getting Fish and chips. If i type Fish tho, i'm getting Fish and chips.

2nd case::I'm typing a recipe's name in the input.

What I should have:

Get every recipe's name that fits the input AND get every vegetable's name that fits the input AND every vegetable that is needed for a recipe that fits the input.
Exemple: I have in my vegetables table : Egg, sugar, chocolate. My recipe table has a 'cake'
and with the pivot table i linked the cake with my egg my chocolate and my sugar. Now if i type 'cake' in my input i should have in the first div 'vegetables':

Sugar

Chocolate

Egg

And in my second div I should have 3 entries:

Cake, ingredient : Sugar

Cake, ingredient : Egg

Cake, ingredient : Chocolate

What I actually have :

All the second part, but I'm not getting any entry in my vegetable div....

Any idea how to solve those 2 problems ? Don’t hesitate to ask for any clarification or precision

答:
First problem:

You get the $recipes by name so if you type "Potato" it's going to check if any recipes have "Potato" in it's name and this is going to be false for the "Potato". why do you have any result in your page is because you use empty($recipes) which beside the time you load the page is always going to return true. so you need to replace it with $recipes->isEmpty().

you want the vegetable records to be shown on the page and then for each of them  want to see the recipes. so you should get the recipes from vegetable like $vegetable->recipes and loop through them. and you should not go through vegetables based on the $recipes being empty.

Second problem:

Again you get the $vegetables by name so if you type "Cake" it's going to check if any vegetables have "Cake" in it's name and this is going to be false for the "Cake".

Body:
I'm still new on Laravel and I'm still working on this project now:
So basically I have a table Recipes containing recipes with a name and vegetabes, a pivot table Recipes_vegetables and a table vegetables.
What i want is a search input that is gonna give me the values of my different tables that fit the input.
So this is my code:

Search.php:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Vegetable;
use App\Models\Recipe;

class Search extends Component
{
    public $query = '';

    public $vegetables;
    public $recipes;

    public function updatedQuery()
    {
        $this->vegetables = Vegetable::where('name', 'like', '%'.$this->query.'%')
                            ->with('recipes')
                            ->get();

        $this->recipes = Recipe::where('name', 'like', '%'.$this->query.'%')
                            ->with('vegetables')
                            ->get();
    }

    public function render()
    {
        return view('livewire.search');
    }
}

search.blade.php :

Search

  <input wire:model="query" type="text" placeholder="Search...">
  @if(!empty($query))

      @if(!empty($recipes))

          @foreach($vegetables as $vegetable)

lunch_dining{{ $vegetable->name }}

          @endforeach

      @else

No result

      @endif

        @foreach($recipes as $recipe)
          @foreach($recipe->vegetables as $vegetable)

menu_book{{ $recipe->name }}Ingredient: {{ $vegetable->name }}

          @endforeach
        @endforeach

  @endif

Recipe.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Recipe extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function vegetables(){
        return $this->belongsToMany(Vegetable::class, 'vegetables_recipes', 'recipe_id', 'vegetable_id');
    }

}

Vegetable.php :

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Vegetable extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name'];

    public function recipes(){
        return $this->belongsToMany(Recipe::class, 'vegetables_recipes', 'vegetable_id', 'recipe_id');
    }

}

So basically this is what i get right now:

1st case: I'm typing a vegetable's name in the input:

What I should have :

Get every vegetable's name that fits the input AND get every recipe's name that fits the input AND get every recipe that has a vegetable 's name that fits the input
Exemple: I have a fish and chips recipe that has 'Potatoes' as an ingredient linked with the pivot table. If i type 'Po' I should have on my render:

Potato

Fish and chips (because the recipe is made with potatoes)

What I actually have right now:

If i type 'po': I'm only getting the results that have 'Po' in their name, so i'm getting Potato, but i'm not getting Fish and chips. If i type Fish tho, i'm getting Fish and chips.

2nd case::I'm typing a recipe's name in the input.

What I should have:

Get every recipe's name that fits the input AND get every vegetable's name that fits the input AND every vegetable that is needed for a recipe that fits the input.
Exemple: I have in my vegetables table : Egg, sugar, chocolate. My recipe table has a 'cake'
and with the pivot table i linked the cake with my egg my chocolate and my sugar. Now if i type 'cake' in my input i should have in the first div 'vegetables':

Sugar

Chocolate

Egg

And in my second div I should have 3 entries:

Cake, ingredient : Sugar

Cake, ingredient : Egg

Cake, ingredient : Chocolate

What I actually have :

All the second part, but I'm not getting any entry in my vegetable div....

Any idea how to solve those 2 problems ? Don’t hesitate to ask for any clarification or precision


问:
Is there an R function to escape a string for regex characters
I'm wanting to build a regex expression substituting in some strings to search for, and so these string need to be escaped before I can put them in the regex, so that if the searched for string contains regex characters it still works.

Some languages have functions that will do this for you (e.g. python re.escape: https://stackoverflow.com/a/10013356/1900520).  Does R have such a function?

For example (made up function):

```<code>x = "foo[bar]"
y = escape(x) # y should now be "foo\\[bar\\]"
</code>```

答:
According to ?regex:

The symbol \w matches a ‘word’ character (a synonym for [[:alnum:]_], an extension) and \W is its negation ([^[:alnum:]_]).

Therefore, using capture groups, (\\W), we can detect the occurrences of non-word characters and escape it with the \\1-syntax:

```<code>> gsub("(\\W)", "\\\\\\1", "[](){}.|^+$*?\\These are words")
[1] "\\[\\]\\(\\)\\{\\}\\.\\|\\^\\+\\$\\*\\?\\\\These\\ are\\ words"
</code>```

Or similarly, replacing "([^[:alnum:]_])" for  "(\\W)".

Body:
I'm wanting to build a regex expression substituting in some strings to search for, and so these string need to be escaped before I can put them in the regex, so that if the searched for string contains regex characters it still works.

Some languages have functions that will do this for you (e.g. python re.escape: https://stackoverflow.com/a/10013356/1900520).  Does R have such a function?

For example (made up function):

x = "foo[bar]"
y = escape(x) # y should now be "foo\\[bar\\]"

Body:
According to ?regex:

The symbol \w matches a ‘word’ character (a synonym for [[:alnum:]_], an extension) and \W is its negation ([^[:alnum:]_]).

Therefore, using capture groups, (\\W), we can detect the occurrences of non-word characters and escape it with the \\1-syntax:

> gsub("(\\W)", "\\\\\\1", "[](){}.|^+$*?\\These are words")
[1] "\\[\\]\\(\\)\\{\\}\\.\\|\\^\\+\\$\\*\\?\\\\These\\ are\\ words"

Or similarly, replacing "([^[:alnum:]_])" for  "(\\W)".


问:
Update table with items where the date is the maximum
MySQL
I need to update only the rows in a table that have the maximum date grouped by an another column.

Table Objectversions

```<code>id, ObjectID, objectdatetime, Linktime, othercolumns
</code>```

I have tried

```<code>UPDATE Objectversions
    SET Linktime = 1
WHERE id IN (
                SELECT id
                FROM Objectversions
                WHERE Objectdatetime IN (
                        SELECT MAX(Objectdatetime)
                        FROM Objectversions
                        GROUP BY ObjectID
                    )
        );
</code>```

I get an error You can't specify target table Objectversions for update in FROM clause.

I have looked at other solutions and cannot work out how to do this. I'll be grateful for any ideas.

答:
Try using join instead:</p>
```<code>UPDATE Objectversions t
JOIN (
      SELECT id
      FROM Objectversions
      WHERE Objectdatetime IN (
             SELECT MAX(Objectdatetime)
             FROM Objectversions
             GROUP BY ObjectID)
 ) s
 ON(t.id = s.id)
SET t.Linktime = 1
</code>```

Body:
MySQL
I need to update only the rows in a table that have the maximum date grouped by an another column.

Table Objectversions

id, ObjectID, objectdatetime, Linktime, othercolumns

I have tried

UPDATE Objectversions
    SET Linktime = 1
WHERE id IN (
                SELECT id
                FROM Objectversions
                WHERE Objectdatetime IN (
                        SELECT MAX(Objectdatetime)
                        FROM Objectversions
                        GROUP BY ObjectID
                    )
        );

I get an error You can't specify target table Objectversions for update in FROM clause.

I have looked at other solutions and cannot work out how to do this. I'll be grateful for any ideas.

Body:
Try using join instead:

UPDATE Objectversions t
JOIN (
      SELECT id
      FROM Objectversions
      WHERE Objectdatetime IN (
             SELECT MAX(Objectdatetime)
             FROM Objectversions
             GROUP BY ObjectID)
 ) s
 ON(t.id = s.id)
SET t.Linktime = 1


问:
Passing the last node with data to the output XML (XSLT question)
I have the following xml:

```<code><peci:Address>
    <peci:Country>seq0</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq2</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country></peci:Country>
</peci:Address>
</code>```

Using the following XSLT line (sheet and template data is extensive so I've decided not to include it):

```<code>xsl:value-of select="peci:Address/peci:Country"/>
</code>```

Gets me the following data:

```<code><cell name="Country">seq0 seq2 </cell>
</code>```

Whereas I would like:

```<code><cell name="Country">seq2</cell>
</code>```

[last()] would produce <cell name="Country"/> so that is not what I'm looking for.

It would have to be scalable because there may be more or less than 3 Country nodes, some of which may be blank. I simply want the last instance of them all.

Eg:

```<code><peci:Address>
    <peci:Country>seq0</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq2</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country></peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq3</peci:Country>
</peci:Address>
</code>```

Should be:

```<code><cell name="Country">seq3</cell>
</code>```

If you could provide some ideas, that would be much appreciated.

Cheers!

答: Use a predicate (peci:Address/peci:Country[normalize-space()])[last()].

Body:
I have the following xml:

<peci:Address>
    <peci:Country>seq0</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq2</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country></peci:Country>
</peci:Address>

Using the following XSLT line (sheet and template data is extensive so I've decided not to include it):

xsl:value-of select="peci:Address/peci:Country"/>

Gets me the following data:

<cell name="Country">seq0 seq2 </cell>

Whereas I would like:

<cell name="Country">seq2</cell>

[last()] would produce <cell name="Country"/> so that is not what I'm looking for.

It would have to be scalable because there may be more or less than 3 Country nodes, some of which may be blank. I simply want the last instance of them all.

Eg:

<peci:Address>
    <peci:Country>seq0</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq2</peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country></peci:Country>
</peci:Address>
<peci:Address>
    <peci:Country>seq3</peci:Country>
</peci:Address>

Should be:

<cell name="Country">seq3</cell>

If you could provide some ideas, that would be much appreciated.

Cheers!


问:
no warning for missing ctor initializer list?
This code is missing a constructor initializer list:

```<code>#include <cstdio>

struct s {
    s() {}  // should be s(): m() {}
    int m;
};

int main() {
    struct s *px = new s();
    if (px->m) {
        printf("true\n");
    } else {
        printf("false\n");
    }
    delete px;
    return 0;
}
</code>```

gcc compiles clean with no warnings:

```<code>$ g++ -Wall -Wextra -g -O2 test.cpp
</code>```

However, valgrind knows that the class member m wasn't initialized:

```<code>$ valgrind ./a.out
==10953== Conditional jump or move depends on uninitialised value(s)
==10953==    at 0x400512: main (test.cpp:10)
==10953==
</code>```

Why didn't gcc warn about the missing initialization (-Wmissing-field-initializers or -Wuninitialized or -Wmaybe-uninitialized)?

Is there a flag I can pass that will catch this case?

答:
You could add -Weffc++ to catch it (inspired by Scott Meyers book "Effective C++"). Strangely enough it does not refer to any other -W option (and neither does clang++).

The option is however considered, by some, a bit outdated by now, but in this case, it's finding a real problem.

Body:
This code is missing a constructor initializer list:

#include <cstdio>

struct s {
    s() {}  // should be s(): m() {}
    int m;
};

int main() {
    struct s *px = new s();
    if (px->m) {
        printf("true\n");
    } else {
        printf("false\n");
    }
    delete px;
    return 0;
}

gcc compiles clean with no warnings:

$ g++ -Wall -Wextra -g -O2 test.cpp

However, valgrind knows that the class member m wasn't initialized:

$ valgrind ./a.out
==10953== Conditional jump or move depends on uninitialised value(s)
==10953==    at 0x400512: main (test.cpp:10)
==10953==

Why didn't gcc warn about the missing initialization (-Wmissing-field-initializers or -Wuninitialized or -Wmaybe-uninitialized)?

Is there a flag I can pass that will catch this case?


问:
Is there a way to aggregate values in a column in sqlite in one-to-many relationship into array?
Is there a way to aggregate values in a column in sqlite in one-to-many relationship into array?
For example, I have 2 tables like this:

```<code>Artists:
ArtistId    name
1            AC/DC
2            Accept

Albums:
AlbumId ArtistId Title
1         1        For Those About To Rock We Salute You
2         1        Let There Be Rock
3         2        Balls to the Wall
4         2        Restless and Wild
</code>```

When I just do a query with a join:

```<code>SELECT
   Name,
   Title
FROM
   artists
JOIN albums USING(ArtistId)
WHERE artists.ArtistId = 1;
</code>```

I get:

I found out that I can do group_concat:

```<code>SELECT
   Name,
   GROUP_CONCAT(Title)
FROM
   artists
JOIN albums USING(ArtistId)
WHERE artists.ArtistId = 1;
</code>```

To concatenate all values together:

But I still have to parse the coma-separated string with titles: For Those About To Rock We Salute You,Let There Be Rock in the code to get the array of titles for each artist.

I use Python and I'd prefer to get something like a tuple for each row:
(name, titlesArray)

A much easier way in this case for me would be to use json.loads and json.dumps functions to save all the "many" array members into the same row in the same table, instead of using the recommended way for databases to save values in different tables and then use joins to retrieve them: the "many" values is an array on the object, and it's just much easier to save and get them using just 2 functions: json.loads and json.dumps, compared to manually saving the "many" values into a separate table, create binding to the "one" value, then use group_concat to concat them into a string, and then parse it more to actually get my array back.

Is it possible to get an array of values, or do I have to do group_concat and parse the string?

答:
You might not be able to receive an array from sqlite straight away, but you can achieve the result with a very little edit on your query and a single line in python.

group_concat supports a custom delimiter that you can use later to split the entries.

Let's assume you have something like this:

from typing import Typle
import sqlite3

def connect(file: str = None) -> sqlite3.Connection:
    connection = None

    try:
        connection = sqlite3.connect(file)
    except sqlite3.Error:
        raise

    return connection

def select(connection: sqlite3.Connection) -> Tuple(str, str)):
    entry = None

    try:
        sql = """
        SELECT
            Name,
            GROUP_CONCAT(Title)
        FROM artists
        JOIN albums USING(ArtistId)
        WHERE artists.ArtistId = 1;
        """
        cursor.execute(sql, parameters)

        reply = cursor.fetchone()
        if reply is not None:
            entry = reply

    except sqlite3.Error:
        raise
    finally:
        cursor.close()

    return entry
```
<p>that you can use to connect to the database and select from it like so:</p>
<pre class="lang-py prettyprint-override"><code>connection = connect(r"/path/to/file.sqlite3")
if connection is not None:
    entry = select(connection)
    connection.close()
</code>```

It is not important if your query is inside a function or not, the important concept is that you are using python to do this query, and you can add some code to manipulate the values.

As you can see here group_concat accepts a separator that you can use to arbitrarily separate values.

Your new select function could be something like:

def select(connection: sqlite3.Connection) -> Tuple(str, Tuple(str, ...)):
    entry = None
    separator = r"|"

    try:
        sql = f"""
        SELECT
            Name,
            GROUP_CONCAT(Title, {separator})
        FROM artists
        JOIN albums USING(ArtistId)
        WHERE artists.ArtistId = 1;
        """
        cursor.execute(sql, parameters)

        reply = cursor.fetchone()
        if reply is not None:
            reply[1] = reply[1].split(separator)
            entry = reply

    except sqlite3.Error:
        raise
    finally:
        cursor.close()

    return entry
```
<p>Without changing how you use this function, you would now have a tuple with all the titles.</p>
<p>Another idea you'd like to consider is to do a more specific select query, like:</p>
<pre class="lang-sql prettyprint-override"><code>select albums.Title
from albums
where albums.ArtistId = 1;
</code>```

In this case, you can have a list of titles using: cursor.fetchall().
Of course the band name should be asked separately in this case.

Body:
Is there a way to aggregate values in a column in sqlite in one-to-many relationship into array?
For example, I have 2 tables like this:

Artists:
ArtistId    name
1            AC/DC
2            Accept

Albums:
AlbumId ArtistId Title
1         1        For Those About To Rock We Salute You
2         1        Let There Be Rock
3         2        Balls to the Wall
4         2        Restless and Wild

When I just do a query with a join:

SELECT
   Name,
   Title
FROM
   artists
JOIN albums USING(ArtistId)
WHERE artists.ArtistId = 1;

I get:

I found out that I can do group_concat:

SELECT
   Name,
   GROUP_CONCAT(Title)
FROM
   artists
JOIN albums USING(ArtistId)
WHERE artists.ArtistId = 1;

To concatenate all values together:

But I still have to parse the coma-separated string with titles: For Those About To Rock We Salute You,Let There Be Rock in the code to get the array of titles for each artist.

I use Python and I'd prefer to get something like a tuple for each row:
(name, titlesArray)

A much easier way in this case for me would be to use json.loads and json.dumps functions to save all the "many" array members into the same row in the same table, instead of using the recommended way for databases to save values in different tables and then use joins to retrieve them: the "many" values is an array on the object, and it's just much easier to save and get them using just 2 functions: json.loads and json.dumps, compared to manually saving the "many" values into a separate table, create binding to the "one" value, then use group_concat to concat them into a string, and then parse it more to actually get my array back.

Is it possible to get an array of values, or do I have to do group_concat and parse the string?

Body:
You might not be able to receive an array from sqlite straight away, but you can achieve the result with a very little edit on your query and a single line in python.

group_concat supports a custom delimiter that you can use later to split the entries.

Let's assume you have something like this:

from typing import Typle
import sqlite3

def connect(file: str = None) -> sqlite3.Connection:
    connection = None

    try:
        connection = sqlite3.connect(file)
    except sqlite3.Error:
        raise

    return connection

def select(connection: sqlite3.Connection) -> Tuple(str, str)):
    entry = None

    try:
        sql = """
        SELECT
            Name,
            GROUP_CONCAT(Title)
        FROM artists
        JOIN albums USING(ArtistId)
        WHERE artists.ArtistId = 1;
        """
        cursor.execute(sql, parameters)

        reply = cursor.fetchone()
        if reply is not None:
            entry = reply

    except sqlite3.Error:
        raise
    finally:
        cursor.close()

    return entry

that you can use to connect to the database and select from it like so:

connection = connect(r"/path/to/file.sqlite3")
if connection is not None:
    entry = select(connection)
    connection.close()

It is not important if your query is inside a function or not, the important concept is that you are using python to do this query, and you can add some code to manipulate the values.

As you can see here group_concat accepts a separator that you can use to arbitrarily separate values.

Your new select function could be something like:

def select(connection: sqlite3.Connection) -> Tuple(str, Tuple(str, ...)):
    entry = None
    separator = r"|"

    try:
        sql = f"""
        SELECT
            Name,
            GROUP_CONCAT(Title, {separator})
        FROM artists
        JOIN albums USING(ArtistId)
        WHERE artists.ArtistId = 1;
        """
        cursor.execute(sql, parameters)

        reply = cursor.fetchone()
        if reply is not None:
            reply[1] = reply[1].split(separator)
            entry = reply

    except sqlite3.Error:
        raise
    finally:
        cursor.close()

    return entry

Without changing how you use this function, you would now have a tuple with all the titles.

Another idea you'd like to consider is to do a more specific select query, like:

select albums.Title
from albums
where albums.ArtistId = 1;

In this case, you can have a list of titles using: cursor.fetchall().
Of course the band name should be asked separately in this case.


问:
Need to display Excel Spreadsheet in html using Angular
I'm trying to display a spreadsheet by uploading the excel document using ej2-syncfusion(spreadsheet), The document is being displayed successfully but I'm not able to copy the index number of the cell. Is there any way I can get the index number when the user copies a certain cell?

This is the output of syncfusion, I want the output as c1-c4 when the user copies the cell

答:
It works for me after adding the following to angular.json</p>
```<code>"stylePreprocessorOptions": {
  "includePaths": [
    "node_modules",
    "src/assets/styles"
  ]
</code>```

Body:
It works for me after adding the following to angular.json

"stylePreprocessorOptions": {
  "includePaths": [
    "node_modules",
    "src/assets/styles"
  ]


问:
time.sleep() not pausing timer in video
Background

I have a video with people walking around different homes. I implemented 3 different timers (for 3 different people) that begin timing when the people are inside the bboxes of the homes and pause when they are outside of the bboxes of the homes. For reference, I have included a visual of what the first frame of the video looks like.

Problem

The check implemented in the code below works fine - it returns True when a person's bbox is inside of a home bbox and returns False otherwise. I'm having difficulties when it comes to pausing the time as a person is walking around outside of the home bbox (i.e. when a person's bbox is not inside of a home bbox). As you can see in the code below, I used time.sleep(1) to pause the timer for a second each time a False is returned, however, this doesn't seem to work. It just keeps the timer running in the background. For example, if person 1's timer is at 15 seconds before a False is returned, its timer should pause. Then, when a True is returned, its timer should resume its time from 15 seconds and increment. However, in my case right now, it keeps running the timer in the background so when a True is returned after a False, the timer suddenly shows up as 24 seconds instead of resuming from where it left off before the time.sleep(). How do I go about solving this issue?

```<code># boxes_houses = [(#, #, #, #), (#, #, #, #), ...]

while cap.isOpened():

    # [...]

    def isInside(person, home):
        # Top-left corner
        if home['x1'] < person['x1'] and home['y1'] < person['y1']:
            # Bottom-right corner
            if person['x2'] + (person['x2'] - person['x1']) < home['x2'] + (home['x2'] - home['x1']) and person['y2'] + (person['y2'] - person['y1']) < home['y2'] + (home['y2'] - home['y1']):
                return True
        else:
            return False

    cnt_person = 0
    cnt_house = 0

    for box_person, box_house in zip(boxes_persons, boxes_houses):
        x_p1 = int(box_person[0])
        y_p1 = int(box_person[1])
        x_p2 = int(box_person[2])
        y_p2 = int(box_person[3])
        person_coords = {'x1': x_p1, 'y1': y_p1, 'x2': x_p2, 'y2': y_p2}
        cv2.rectangle(frame, (x_p1, y_p1), (x_p1 + x_p2, y_p1 + y_p2), (0, 0, 0), 2, 1)
        cv2.putText(frame, "House: {}".format(cnt_house), (x1, y1 - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 0), 1)

        x_h1 = int(box_house[0])
        y_h1 = int(box_house[1])
        x_h2 = int(box_house[2])
        y_h2 = int(box_house[3])
        cv2.rectangle(frame, (x_h1 , y_h1), (x_h1 + x_h2, y_h1+ y_h2), (0, 0, 255), 2, 1)
        cv2.putText(frame, "Person: {}".format(cnt_person ), (int(box_house[0]), int(box_house[1] - 5)), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

        isinside_checks = []
        for house in houses:
            isinside_checks.append(isInside(person_coords, house))

        ### CHECK ###

        if any(inside_checks): #if persons inside the home bbox
            # print ("Person", cnt_person, ": True\n")

            if cnt_person==0:
                cv2.putText(main_frame, "Person 0 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
            elif cnt_person==1:
                cv2.putText(main_frame, "Person 1 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
            elif cnt_person==2:
                cv2.putText(main_frame, "Person 2 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)

        else: #if persons outside the home bbox
            print ("Person", cnt_person, ": False\n")
            time.sleep(1) # should pause the time

        cnt_person = cnt_person + 1
        cnt_house = cnt_house + 1

    # show frame
    cv2.imshow('MultiTracker', frame)

    if cv2.waitKey(1) & 0xFF == 27:
        break
</code>```

答:
Interesting challenge you have. Seems like you understand the problem, the timer will continue to check time even when you sleep the execution of the program.
I believe this is because the timer is based on the number of milliseconds since an epoch from years ago or something.

The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

https://www.programiz.com/python-programming/time

Therefore, just because you pause your execution, that doesn’t mean that time hasn’t increased since that point in the past.

How would I handle this problem?

I would track the amount of time paused and subtract that from the total amount of time passed for each person.

Outside of the for loop initialise:

```<code>pause_times = [0, 0, 0] # the total time paused for each person
last_pause = [0, 0, 0] # the times of the last pause for each person
paused = False
</code>```

Then where you check whether people are inside or outside the houses, update the pause times or total times appropriately:

```<code>if any(inside_checks): #if persons inside the home bbox
    # print ("Person", cnt_person, ": True\n")
    paused = False
    if cnt_person==0:
            cv2.putText(main_frame, "Person 0 Time: {}".format(end_time-start_time-pause_times[0]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
    elif cnt_person==1:
            cv2.putText(main_frame, "Person 1 Time: {}".format(end_time-start_time-pause_times[1]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
    elif cnt_person==2:
            cv2.putText(main_frame, "Person 2 Time: {}".format(end_time-start_time-pause_times[2]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)

else: #if persons outside the home bbox
    print ("Person", cnt_person, ": False\n")
    if not paused:  # the timer hasn't been paused for a while
        last_pause[cnt_person] = end_time # updating the pause point
        paused = True
    pause_times[cnt_person] += end_time - last_pause[cnt_person] # track the total amount of time paused for each person
    last_pause[cnt_person] = end_time
</code>```

Disclaimer:

I feel obligated to say I might not totally understand your problem and I'm not an expert so my solution might be flawed. I hope that it offers you a different perspective at the very least. Cheers.

Title: time.sleep() not pausing timer in video

Body:
Background

I have a video with people walking around different homes. I implemented 3 different timers (for 3 different people) that begin timing when the people are inside the bboxes of the homes and pause when they are outside of the bboxes of the homes. For reference, I have included a visual of what the first frame of the video looks like.

Problem

The check implemented in the code below works fine - it returns True when a person's bbox is inside of a home bbox and returns False otherwise. I'm having difficulties when it comes to pausing the time as a person is walking around outside of the home bbox (i.e. when a person's bbox is not inside of a home bbox). As you can see in the code below, I used time.sleep(1) to pause the timer for a second each time a False is returned, however, this doesn't seem to work. It just keeps the timer running in the background. For example, if person 1's timer is at 15 seconds before a False is returned, its timer should pause. Then, when a True is returned, its timer should resume its time from 15 seconds and increment. However, in my case right now, it keeps running the timer in the background so when a True is returned after a False, the timer suddenly shows up as 24 seconds instead of resuming from where it left off before the time.sleep(). How do I go about solving this issue?

# boxes_houses = [(#, #, #, #), (#, #, #, #), ...]

while cap.isOpened():

    # [...]

    def isInside(person, home):
        # Top-left corner
        if home['x1'] < person['x1'] and home['y1'] < person['y1']:
            # Bottom-right corner
            if person['x2'] + (person['x2'] - person['x1']) < home['x2'] + (home['x2'] - home['x1']) and person['y2'] + (person['y2'] - person['y1']) < home['y2'] + (home['y2'] - home['y1']):
                return True
        else:
            return False

    cnt_person = 0
    cnt_house = 0

    for box_person, box_house in zip(boxes_persons, boxes_houses):
        x_p1 = int(box_person[0])
        y_p1 = int(box_person[1])
        x_p2 = int(box_person[2])
        y_p2 = int(box_person[3])
        person_coords = {'x1': x_p1, 'y1': y_p1, 'x2': x_p2, 'y2': y_p2}
        cv2.rectangle(frame, (x_p1, y_p1), (x_p1 + x_p2, y_p1 + y_p2), (0, 0, 0), 2, 1)
        cv2.putText(frame, "House: {}".format(cnt_house), (x1, y1 - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 0), 1)

        x_h1 = int(box_house[0])
        y_h1 = int(box_house[1])
        x_h2 = int(box_house[2])
        y_h2 = int(box_house[3])
        cv2.rectangle(frame, (x_h1 , y_h1), (x_h1 + x_h2, y_h1+ y_h2), (0, 0, 255), 2, 1)
        cv2.putText(frame, "Person: {}".format(cnt_person ), (int(box_house[0]), int(box_house[1] - 5)), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1)

        isinside_checks = []
        for house in houses:
            isinside_checks.append(isInside(person_coords, house))

        ### CHECK ###

        if any(inside_checks): #if persons inside the home bbox
            # print ("Person", cnt_person, ": True\n")

            if cnt_person==0:
                cv2.putText(main_frame, "Person 0 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
            elif cnt_person==1:
                cv2.putText(main_frame, "Person 1 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
            elif cnt_person==2:
                cv2.putText(main_frame, "Person 2 Time: {}".format(end_time-start_time), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)

        else: #if persons outside the home bbox
            print ("Person", cnt_person, ": False\n")
            time.sleep(1) # should pause the time

        cnt_person = cnt_person + 1
        cnt_house = cnt_house + 1

    # show frame
    cv2.imshow('MultiTracker', frame)

    if cv2.waitKey(1) & 0xFF == 27:
        break

Body:
Interesting challenge you have. Seems like you understand the problem, the timer will continue to check time even when you sleep the execution of the program.
I believe this is because the timer is based on the number of milliseconds since an epoch from years ago or something.

The time() function returns the number of seconds passed since epoch. For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

https://www.programiz.com/python-programming/time

Therefore, just because you pause your execution, that doesn’t mean that time hasn’t increased since that point in the past.

How would I handle this problem?

I would track the amount of time paused and subtract that from the total amount of time passed for each person.

Outside of the for loop initialise:

pause_times = [0, 0, 0] # the total time paused for each person
last_pause = [0, 0, 0] # the times of the last pause for each person
paused = False

Then where you check whether people are inside or outside the houses, update the pause times or total times appropriately:

if any(inside_checks): #if persons inside the home bbox
    # print ("Person", cnt_person, ": True\n")
    paused = False
    if cnt_person==0:
            cv2.putText(main_frame, "Person 0 Time: {}".format(end_time-start_time-pause_times[0]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
    elif cnt_person==1:
            cv2.putText(main_frame, "Person 1 Time: {}".format(end_time-start_time-pause_times[1]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)
    elif cnt_person==2:
            cv2.putText(main_frame, "Person 2 Time: {}".format(end_time-start_time-pause_times[2]), (450, 500), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0,0,0),1)

else: #if persons outside the home bbox
    print ("Person", cnt_person, ": False\n")
    if not paused:  # the timer hasn't been paused for a while
        last_pause[cnt_person] = end_time # updating the pause point
        paused = True
    pause_times[cnt_person] += end_time - last_pause[cnt_person] # track the total amount of time paused for each person
    last_pause[cnt_person] = end_time

Disclaimer:

I feel obligated to say I might not totally understand your problem and I'm not an expert so my solution might be flawed. I hope that it offers you a different perspective at the very least. Cheers.


问:
Should I #include .cpp files to header of TestSuite to make cxxtest work?

Situation is as follows: I've got a simple project consisting of two files - Calc.h and Calc.cpp.

Calc.h:

#pragma once

class Calc {
public:
    int add(int,int);
    static const int a = 42;
}
```
<p>Calc.cpp:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Calc.h"

class Calc {
public:
    int add(int a,int b){
        return a + b;
    };
}
</code>```

CalcTestSuite.h:

#pragma once
#include "Calc.h"
#include <cxxtest/TestSuite.h>

class CalcTestSuite : public CxxTest::TestSuite {
public:
     void testAddition(void)
     {
           Calc calculator;
           TS_ASSERT_EQUALS(calculator.a, 42);
           TS_ASSERT_EQUALS(calculator.add(1,2), 3);
     }
}
```
<h3>The problem</h3>
<p>The problem being is, when I do <code>cxxtestgen --error-printer -o runner.cpp CalcTestSuite.h && g++ -I$cxxtest -o runner.o runner.cpp && ./runner.o</code>, an error occurs:</p>
```runner.cpp: (.text._ZN13...(many letters)): undefined reference to `Calc::add(int,int)`
```
<p>Undoubtedly, the reason of that is wrong compiling as I compile code outside of Visual Studio 2019 or other IDE.</p>
<h3>How I tried to solve the problem:</h3>
<p>I see a couple of solutions:</p>
<p>1.) Leave build command as is and add <code>#include "Calc.cpp"</code> to TestSuite file, which will obviously work but would be a bad practice.</p>
<p>2.) Add Calc.cpp to g++ command: <code>g++ -I$cxxtest -o runner.o Calc.cpp runner.cpp && ./runner.o</code>, however, it leads to another problem:</p>
```Calc.cpp:3:7: error: redefinition of 'class Calc'
```

In that case I also tried changing #pragma once to #ifndef CALC_H... block in Calc.h, but the error remained.

I tried searching for real-world cxxtest code examples, but didn't find the site I've seen long ago. I would be glad to recieve any tips on what's the best way to deal with this issue.

And if you know the site where I can search for real-life code snippets I would be glad if you shared it.

答:
There are two problems:

You are violating One Definition Rule! You can't redefine Calc like this:

#include "Calc.h"

class Calc {
public:
   int add(int a,int b){
       return a + b;
   };
}
```
<p>It must be:</p>
<pre class="lang-cpp prettyprint-override"><code>#include "Calc.h"

int Calc::add(int a,int b) {
    return a + b;
};

const int Calc::a;
</code>```

Now this problem do not surfaces since you do not build this cpp and you should.

You didn't explain how you are building you code. Simplest way when it is done manually it can look like this:

cxxtestgen --error-printer -o CalcTestSuite.cpp CalcTestSuite.h
g++ -std=c++17 -Wall -Wextra Calc.cpp CalcTestSuite.cpp -o test
```

Offtopic: this cxxtest test framework is strange and has strange/complex build process of test. It would be better if you learn to use something more useful, Catch2 is great and easy to use (no funny build process) and it is supported by godbolt.

Body:
Situation is as follows: I've got a simple project consisting of two files - Calc.h and Calc.cpp.

Calc.h:

#pragma once

class Calc {
public:
    int add(int,int);
    static const int a = 42;
}

Calc.cpp:

#include "Calc.h"

class Calc {
public:
    int add(int a,int b){
        return a + b;
    };
}

CalcTestSuite.h:

#pragma once
#include "Calc.h"
#include <cxxtest/TestSuite.h>

class CalcTestSuite : public CxxTest::TestSuite {
public:
     void testAddition(void)
     {
           Calc calculator;
           TS_ASSERT_EQUALS(calculator.a, 42);
           TS_ASSERT_EQUALS(calculator.add(1,2), 3);
     }
}

The problem

The problem being is, when I do cxxtestgen --error-printer -o runner.cpp CalcTestSuite.h && g++ -I$cxxtest -o runner.o runner.cpp && ./runner.o, an error occurs:

runner.cpp: (.text._ZN13...(many letters)): undefined reference to `Calc::add(int,int)`

Undoubtedly, the reason of that is wrong compiling as I compile code outside of Visual Studio 2019 or other IDE.

How I tried to solve the problem:

I see a couple of solutions:

1.) Leave build command as is and add #include "Calc.cpp" to TestSuite file, which will obviously work but would be a bad practice.

2.) Add Calc.cpp to g++ command: g++ -I$cxxtest -o runner.o Calc.cpp runner.cpp && ./runner.o, however, it leads to another problem:

Calc.cpp:3:7: error: redefinition of 'class Calc'

In that case I also tried changing #pragma once to #ifndef CALC_H... block in Calc.h, but the error remained.

I tried searching for real-world cxxtest code examples, but didn't find the site I've seen long ago. I would be glad to recieve any tips on what's the best way to deal with this issue.

And if you know the site where I can search for real-life code snippets I would be glad if you shared it.

Body:
There are two problems:

You are violating One Definition Rule! You can't redefine Calc like this:

#include "Calc.h"

class Calc {
public:
   int add(int a,int b){
       return a + b;
   };
}

It must be:

#include "Calc.h"

int Calc::add(int a,int b) {
    return a + b;
};

const int Calc::a;

Now this problem do not surfaces since you do not build this cpp and you should.

You didn't explain how you are building you code. Simplest way when it is done manually it can look like this:

cxxtestgen --error-printer -o CalcTestSuite.cpp CalcTestSuite.h
g++ -std=c++17 -Wall -Wextra Calc.cpp CalcTestSuite.cpp -o test

Offtopic: this cxxtest test framework is strange and has strange/complex build process of test. It would be better if you learn to use something more useful, Catch2 is great and easy to use (no funny build process) and it is supported by godbolt.