问:
Rename opened workbook without firstly close it?
If I want to rename an opened workbook, I need to close it firstly, and then rename it which is a little tedious.

on 3rd party software “Office Tab” , It has this feature to Rename opened workbook without firstly close it.

Is it possible to be done by Excel without using other software ,even by using VBA soultion.

In advance , greatful for any help.

答:
there are various solutions to this problem,

the first one will be to run the following:

```<code>ActiveWorkbook.SaveAs "MyFile.xls"
Kill "MyPreviousFileName.xls"
</code>```

you do have to save it in order to change its name. and if you want to save the old copy, you can remove the kill function

if you want it to be more precise you can do as follows (edit: added @funthomas's suggestion):

```<code>Sub Macro2()

Dim rootDir as string
Dim FileName as String

rootDir = "\Desktop"
rootDir  = Replace(rootDir, "@1", environ(UserProfile))

FileName = "Test"

ActiveWorkbook.SaveAs rootDir & FileName & ".xlsm"

End Sub
</code>```

Body:
there are various solutions to this problem,

the first one will be to run the following:

ActiveWorkbook.SaveAs "MyFile.xls"
Kill "MyPreviousFileName.xls"

you do have to save it in order to change its name. and if you want to save the old copy, you can remove the kill function

if you want it to be more precise you can do as follows (edit: added @funthomas's suggestion):

Sub Macro2()

Dim rootDir as string
Dim FileName as String

rootDir = "\Desktop"
rootDir  = Replace(rootDir, "@1", environ(UserProfile))

FileName = "Test"

ActiveWorkbook.SaveAs rootDir & FileName & ".xlsm"

End Sub


来源: stackexchange

问:
Github API works in curl but not python - bad credentials
I am trying to use the Github API and it works when I do curl from terminal but not when using the Python Request library:

WORKS:

```<code>curl -v --location --request GET 'https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100' \
--header 'Authorization: Bearer MY_TOKEN'
</code>```

DOESN'T WORK:

```<code>import requests

url = https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100
r = requests.get(url, auth=(MY_GITHUB_USERNAME, MY_TOKEN))
</code>```

I get the following response for python:

" b'{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}' "

Would appreciate any help - thank you in advance!

答:
Please try with below snippet, you have to send PAT in header,

import requests

url = "https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100"

payload={}
headers = {
  'Authorization': 'Bearer MY_TOKEN',

}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)
```

Check the documentation
https://docs.github.com/en/rest/guides/getting-started-with-the-rest-api

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use the Github API and it works when I do curl from terminal but not when using the Python Request library:

WORKS:

curl -v --location --request GET 'https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100' \
--header 'Authorization: Bearer MY_TOKEN'

DOESN'T WORK:

import requests

url = https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100
r = requests.get(url, auth=(MY_GITHUB_USERNAME, MY_TOKEN))

I get the following response for python:

" b'{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}' "

Would appreciate any help - thank you in advance!

Body:
Please try with below snippet, you have to send PAT in header,

import requests

url = "https://api.github.com/search/repositories?q=stars:>=500+created:2017-01-01&order=asc&per_page=100"

payload={}
headers = {
  'Authorization': 'Bearer MY_TOKEN',

}

response = requests.request("GET", url, headers=headers, data=payload)

print(response.text)

Check the documentation
https://docs.github.com/en/rest/guides/getting-started-with-the-rest-api


问:
MySQL: Find all customerIDs with multiple ID Values
I have the following table

```<code>customerID | fieldID | fieldValue
1          | 1       | 0
1          | 2       | 8
1          | 3       | Test
1          | 4       | Other Value
2          | 1       | 8
2          | 4       | Testvalue
</code>```

I want all customerID which have e.g. the following values:

```<code>fieldID | fieldValue
1       | 0
2       | 8
</code>```

I have tried the following:

```<code>SELECT customerID
FROM my_table
WHERE
(fieldID = 1 AND fieldValue = 0) AND
(fieldID = 2 AND fieldValue = 8)
GROUP BY customerID
</code>```

Since I do not get a value, there is surely an error here. How should I proceed here?

答:
You need to change the AND between the parenthesis to OR</p>
```<code>SELECT customerID
FROM my_table
WHERE
(fieldID = 1 AND fieldValue = 0) OR
(fieldID = 2 AND fieldValue = 8)
GROUP BY customerID;
</code>```

Body:
I have the following table

customerID | fieldID | fieldValue
1          | 1       | 0
1          | 2       | 8
1          | 3       | Test
1          | 4       | Other Value
2          | 1       | 8
2          | 4       | Testvalue

I want all customerID which have e.g. the following values:

fieldID | fieldValue
1       | 0
2       | 8

I have tried the following:

SELECT customerID
FROM my_table
WHERE
(fieldID = 1 AND fieldValue = 0) AND
(fieldID = 2 AND fieldValue = 8)
GROUP BY customerID

Since I do not get a value, there is surely an error here. How should I proceed here?

Body:
You need to change the AND between the parenthesis to OR

SELECT customerID
FROM my_table
WHERE
(fieldID = 1 AND fieldValue = 0) OR
(fieldID = 2 AND fieldValue = 8)
GROUP BY customerID;


问:
Resizing table slow performance in electron app
I have the following js in my electron app to resize table columns:

```<code>const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    window.addEventListener('mousemove', function (e) {
        if (th) {
            th.style.width = startOffset + e.x + 'px'
        }
    })

    window.addEventListener('mouseup', function () {
        th = undefined
    })
}
</code>```

Example Table: (Arrays from json files populate the table contents)

```<code><table>
    <thead>
        <tr>
            <th>
                <div>Column 1</div>
                <button on:mousedown={resizerMouseDown} class="resizer"></button>
            </th>
            <th>
                <div>Column 2</div>
                <button on:mousedown={resizerMouseDown} class="resizer"></button>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="text" /></td>
            <td><input type="text" /></td>
        </tr>
    </tbody>
</table>
</code>```

When the table rows are more that 100, resizing the columns are very slow. I'm not even going to mention when the json files are huge (1000+ table rows).

Any suggestions to get better performance out of the code, or would this be a limitation of electron?

答:
Whenever the mouse moves, you're checking whether th was defined. This is not particularly efficient to do, since you only want your listeners to execute when the resizerMouseDown function was called in the first place.

To circumvent this (and to not register the same listener over and over again), I suggest to clean up the event listeners once the mouse is back up by using window.removeEventListener():

const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    const moveListener = e => {
        th.style.width = startOffset + e.x + 'px'
    }

    const upListener = e => {
        th = undefined
        window.removeEventListener('mousemove', moveListener)
        window.removeEventListener('mouseup', upListener)
    }

    window.addEventListener('mousemove', moveListener)
    window.addEventListener('mouseup', upListener)
}
```
<p>Also, it's worth noting that the move listener will fire whenever the browser sends the signal that the mouse moved. However, resizing the table on every move might not be very efficient and redrawing 1000+ rows over and over again is certainly heavy on the CPU and the GPU. Thus, what about adding a threshold and only resizing every 10 calls or so:</p>
<pre class="lang-js prettyprint-override"><code>const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    var skipCount = 0
    var isDirty = false
    var lastXValue = 0
    const resize = xValue => {
        th.style.width = startOffset + xValue + 'px'
        isDirty = false
    }

    const moveListener = e => {
        skipCount++
        if (skipCount >= 10) resize (e.x)
        else {
            lastXValue = e.x
            isDirty = true
        }
    }

    const upListener = e => {
        if (isDirty) resize (lastXValue)
        th = undefined
        window.removeEventListener('mousemove', moveListener)
        window.removeEventListener('mouseup', upListener)
    }

    window.addEventListener('mousemove', moveListener)
    window.addEventListener('mouseup', upListener)
}
</code>```

(As you can see, in case the last resize before the mouse button was up was skipped, the event listener for the mouseup event detects this and resizes the column a final time.) I suggest playing with the values, especially the skip threshold.

Aside from this, yes, resizing huge tables is slow by default. The browser will need to re-calculate the width of every single table cell and when there are many, it will slow down considerably.

One final note: I have not tested this code for its performance. This answer is based purely on general code efficiency and guesses towards performance bottlenecks. Feel free to analyse this code using Chromium's built-in profiler (also available on Electron); this will tell you exactly where you can optimise further.

Body:
I have the following js in my electron app to resize table columns:

const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    window.addEventListener('mousemove', function (e) {
        if (th) {
            th.style.width = startOffset + e.x + 'px'
        }
    })

    window.addEventListener('mouseup', function () {
        th = undefined
    })
}

Example Table: (Arrays from json files populate the table contents)

Column 1

                <button on:mousedown={resizerMouseDown} class="resizer"></button>

Column 2

                <button on:mousedown={resizerMouseDown} class="resizer"></button>

            <input type="text" />
            <input type="text" />

When the table rows are more that 100, resizing the columns are very slow. I'm not even going to mention when the json files are huge (1000+ table rows).

Any suggestions to get better performance out of the code, or would this be a limitation of electron?

Body:
Whenever the mouse moves, you're checking whether th was defined. This is not particularly efficient to do, since you only want your listeners to execute when the resizerMouseDown function was called in the first place.

To circumvent this (and to not register the same listener over and over again), I suggest to clean up the event listeners once the mouse is back up by using window.removeEventListener():

const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    const moveListener = e => {
        th.style.width = startOffset + e.x + 'px'
    }

    const upListener = e => {
        th = undefined
        window.removeEventListener('mousemove', moveListener)
        window.removeEventListener('mouseup', upListener)
    }

    window.addEventListener('mousemove', moveListener)
    window.addEventListener('mouseup', upListener)
}

Also, it's worth noting that the move listener will fire whenever the browser sends the signal that the mouse moved. However, resizing the table on every move might not be very efficient and redrawing 1000+ rows over and over again is certainly heavy on the CPU and the GPU. Thus, what about adding a threshold and only resizing every 10 calls or so:

const resizerMouseDown = (e) => {
    let th = e.target.parentNode
    let startOffset = th.offsetWidth - e.x

    var skipCount = 0
    var isDirty = false
    var lastXValue = 0
    const resize = xValue => {
        th.style.width = startOffset + xValue + 'px'
        isDirty = false
    }

    const moveListener = e => {
        skipCount++
        if (skipCount >= 10) resize (e.x)
        else {
            lastXValue = e.x
            isDirty = true
        }
    }

    const upListener = e => {
        if (isDirty) resize (lastXValue)
        th = undefined
        window.removeEventListener('mousemove', moveListener)
        window.removeEventListener('mouseup', upListener)
    }

    window.addEventListener('mousemove', moveListener)
    window.addEventListener('mouseup', upListener)
}

(As you can see, in case the last resize before the mouse button was up was skipped, the event listener for the mouseup event detects this and resizes the column a final time.) I suggest playing with the values, especially the skip threshold.

Aside from this, yes, resizing huge tables is slow by default. The browser will need to re-calculate the width of every single table cell and when there are many, it will slow down considerably.

One final note: I have not tested this code for its performance. This answer is based purely on general code efficiency and guesses towards performance bottlenecks. Feel free to analyse this code using Chromium's built-in profiler (also available on Electron); this will tell you exactly where you can optimise further.


问:
python: efficient and pythonic way to get sublist from a descending list which is larger than threshold
Given a list with descending order, e.g. [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2] and threshold = 1.2, I want to get sublist from original list with all elements larger than threshold

Method1:

orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = [i for i in orgin_lst if i > threshold]
```
<p>This is pythonic way but <strong>we don't use the descending property and cannot break out when found a element not larger than threshold</strong>. If there are few satisfied elements but oringal list is very large, the performance is not good.</p>
<p>Method2:</p>
<pre class="lang-py prettyprint-override"><code>orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = []
for i in orgin_lst:
    if i <= threshold:
        break
    lst.append(i)
</code>```

However this code is not quite pythonic.

Is there a way  that I can combine pythonic style and performance?

答:
I think your code was very close:

```<code>orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = []
for i in orgin_lst:
    if i <= threshold:
        break
    lst.append(i)
</code>```

But let's employ a generator.

```<code>def take_until(f, it):
    for x in it:
        if f(x): return
        yield x
</code>```

Now, we can write something like the following, for instance.

```<code>>>> for x in take_until(lambda x: x <= 1.2, lst):
...     print(x)
...
10
9
8
7
6
5
4
3
2
>>>
</code>```

Heck, if we really want a list, that's just as easy.

```<code>>>> list(take_until(lambda x: x <= 1.2, lst))
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>>
</code>```

Body:
Given a list with descending order, e.g. [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2] and threshold = 1.2, I want to get sublist from original list with all elements larger than threshold

Method1:

orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = [i for i in orgin_lst if i > threshold]

This is pythonic way but we don't use the descending property and cannot break out when found a element not larger than threshold. If there are few satisfied elements but oringal list is very large, the performance is not good.

Method2:

orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = []
for i in orgin_lst:
    if i <= threshold:
        break
    lst.append(i)

However this code is not quite pythonic.

Is there a way  that I can combine pythonic style and performance?

Body:
I think your code was very close:

orgin_lst = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, -1, -2, -2]
lst = []
for i in orgin_lst:
    if i <= threshold:
        break
    lst.append(i)

But let's employ a generator.

def take_until(f, it):
    for x in it:
        if f(x): return
        yield x

Now, we can write something like the following, for instance.

>>> for x in take_until(lambda x: x <= 1.2, lst):
...     print(x)
...
10
9
8
7
6
5
4
3
2
>>>

Heck, if we really want a list, that's just as easy.

>>> list(take_until(lambda x: x <= 1.2, lst))
[10, 9, 8, 7, 6, 5, 4, 3, 2]
>>>


答:
I think this is the query you actually want here:

SELECT customerID
FROM my_table
GROUP BY customerID
HAVING SUM(fieldID = 1 AND fieldValue = 2) > 0 AND
       SUM(fieldID = 0 AND fieldValue = 8) > 0;
```

Title: MySQL: Find all customerIDs with multiple ID Values


问:
Plot from for loop and legend from same loop dont match colors. How can I have them correspond. MATLAB
```<code>for j= 1:numfiles;
   plot(A(j,:))
   legendmatrix{j,1}=strcat('Run',num2str(j))
   hold all
end
legend(legendmatrix)
</code>```

hold all allows me to have different colors for all my curves. However when I use the strings from strcat and display them on the plot, not enough colors are used and they are not assigned to the corresponding curve.

In this case plot 1 is run 1 in the legend, etc... and I want the colors to match

答:
Here is a slightly different example:

```<code>%# sample data
N = 7;
A = rand(N,10);
x = 1:10;

%# plot each with a specific color
hold on
clr = lines(N);    %# LINES colormap
for j=1:N
   plot(x, A(j,:), 'Color',clr(j,:))
end
hold off

%# add legend
str = cellstr( num2str((1:N)','Run%d') );
legend(str)
</code>```

Note that if N>7, the LINES colormap will start to repeat colors, but you can always specify your own set of colors... You also have the option of using different markers and line-styles to get more visually distinct data.

ContentLicense: CC BY-SA 3.0

Body:
for j= 1:numfiles;
   plot(A(j,:))
   legendmatrix{j,1}=strcat('Run',num2str(j))
   hold all
end
legend(legendmatrix)

hold all allows me to have different colors for all my curves. However when I use the strings from strcat and display them on the plot, not enough colors are used and they are not assigned to the corresponding curve.

In this case plot 1 is run 1 in the legend, etc... and I want the colors to match

Body:
Here is a slightly different example:

%# sample data
N = 7;
A = rand(N,10);
x = 1:10;

%# plot each with a specific color
hold on
clr = lines(N);    %# LINES colormap
for j=1:N
   plot(x, A(j,:), 'Color',clr(j,:))
end
hold off

%# add legend
str = cellstr( num2str((1:N)','Run%d') );
legend(str)

Note that if N>7, the LINES colormap will start to repeat colors, but you can always specify your own set of colors... You also have the option of using different markers and line-styles to get more visually distinct data.


问:
How to get the dynamic height of UIView which contains two or more UILabels vertically?
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

```<code>let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant
</code>```

答:
I think your answer lies in layoutIfNeeded and let me explain why

Consider my storyboard set up to set up a Dynamic height UIView which should set its height automatically based on the UILabels within it, note that I did not set the height anchor and so it gives me constraint errors which you can ignore for now as they will be resolved once we are done setting up.

Next I add two labels to this view which have numberOfLines = 0

Top Label constraints

Bottom Label constraints

After this, the constraint errors go away and notice the height of the view in which the labels are contained in is 82:

Now I add this code which dynamically changes the text in the label

```<code>class DynamicHeightVC: UIViewController
{
    @IBOutlet var myView: UIView!
    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!

    var longText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it.
    """

    var reallyLongText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it. Some really long text that should make
    the UI label expand beyond a few lines and make the
    UIView expand along with it.
    """

    override func viewDidLoad()
    {
        super.viewDidLoad()

        labelOne.text = longText
        labelTwo.text = reallyLongText

        print("View height \(myView.frame.height)")
    }
}
</code>```

The output is View height 82.0 which is the value we saw on the storyboard and it is clearly wrong as the view's height is bigger:

So the issue is once you change / update the text, the constraints get updated and the frames will get updated at a later / different iteration of the main run loop which might not be useful to you since you want to do some calculations with it now.

If you want the frames to be updated in the next turn of the update cycle within the main run loop, you need to call view.setNeedsLayout().

If you want the frames to be updated immediately, you need to call view.layoutIfNeeded()

After making this change, the code is as follows:

```<code>class DynamicHeightVC: UIViewController
{
    @IBOutlet var myView: UIView!
    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!

    var longText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it.
    """

    var reallyLongText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it. Some really long text that should make
    the UI label expand beyond a few lines and make the
    UIView expand along with it.
    """

    override func viewDidLoad()
    {
        super.viewDidLoad()

        labelOne.text = longText
        labelTwo.text = reallyLongText

        view.layoutIfNeeded()

        print("Label 1 height \(labelOne.frame.height)")
        print("Label 2 height \(labelTwo.frame.height)")
        print("View height \(myView.frame.height)")
    }
}
</code>```

And now the console displays the correct, updated height:

```<code>Label 1 height 101.5
Label 2 height 183.0
View height 284.5
</code>```

Body:
I am trying to find the dynamic height of a UIView at the run time. So, for this I calculated the run time height of UILabels in it and the constraint constants and add them all to get the desired height. But this doesn't seems to be the correct way of doing it, because in case I alter the count of UILabel or constraints in future then I do have to change the code to calculate the dynamic height. So, is there any way to get the height of UIView at run time with any number of labels and constraints in it?

MY CODE

Here uiview is UIView of which I need to calculate the dynamic height, label1 and label2 are the UILabels in which I inserted text programatically. height is a string extension to find dynamic height of UILabel. label1TopConstraint, label1BottonContraint, label2BottomConstraint are constraints IBOutlets.

let label1Height = label1.text!.height(withConstrainedWidth: label1.frame.width, font: label1.font)
let label2Height = label2.text!.height(withConstrainedWidth: label2.frame.width, font: label2.font)
uiviewHeight = label1Height + label2Height + label1TopConstraint.constant + label1BottonContraint.constant + label2BottomConstraint.constant

Body:
I think your answer lies in layoutIfNeeded and let me explain why

Consider my storyboard set up to set up a Dynamic height UIView which should set its height automatically based on the UILabels within it, note that I did not set the height anchor and so it gives me constraint errors which you can ignore for now as they will be resolved once we are done setting up.

Next I add two labels to this view which have numberOfLines = 0

Top Label constraints

Bottom Label constraints

After this, the constraint errors go away and notice the height of the view in which the labels are contained in is 82:

Now I add this code which dynamically changes the text in the label

class DynamicHeightVC: UIViewController
{
    @IBOutlet var myView: UIView!
    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!

    var longText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it.
    """

    var reallyLongText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it. Some really long text that should make
    the UI label expand beyond a few lines and make the
    UIView expand along with it.
    """

    override func viewDidLoad()
    {
        super.viewDidLoad()

        labelOne.text = longText
        labelTwo.text = reallyLongText

        print("View height \(myView.frame.height)")
    }
}

The output is View height 82.0 which is the value we saw on the storyboard and it is clearly wrong as the view's height is bigger:

So the issue is once you change / update the text, the constraints get updated and the frames will get updated at a later / different iteration of the main run loop which might not be useful to you since you want to do some calculations with it now.

If you want the frames to be updated in the next turn of the update cycle within the main run loop, you need to call view.setNeedsLayout().

If you want the frames to be updated immediately, you need to call view.layoutIfNeeded()

After making this change, the code is as follows:

class DynamicHeightVC: UIViewController
{
    @IBOutlet var myView: UIView!
    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!

    var longText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it.
    """

    var reallyLongText = """
    Some really long text that should make the UI label
    expand beyond a few lines and make the UIView expand
    along with it. Some really long text that should make
    the UI label expand beyond a few lines and make the
    UIView expand along with it.
    """

    override func viewDidLoad()
    {
        super.viewDidLoad()

        labelOne.text = longText
        labelTwo.text = reallyLongText

        view.layoutIfNeeded()

        print("Label 1 height \(labelOne.frame.height)")
        print("Label 2 height \(labelTwo.frame.height)")
        print("View height \(myView.frame.height)")
    }
}

And now the console displays the correct, updated height:

Label 1 height 101.5
Label 2 height 183.0
View height 284.5


问:
Applying 'transition' effect to  elements not working properly
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="main">
      <h1>Contact</h1>
      <p>In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.</p>
      <div class="container">
        <img src="./insta.png">
        <h2>@bellapfisterphotography</h2>
      </div>
      <div class="container">
        <img src="./email.png">
        <h2>mail@gmail.com</h2>
      </div>
  </div></code>```

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

答:
That's because you are applying text-decoration on two different elements:

```<code>.container a {
  ...
  text-decoration: none;
}

.container a h2:hover {
  text-decoration: underline;
}
</code>```

text-decoration is a shorthand for text-decoration-line, text-decoration-color, text-decoration-style, and text-decoration-thickness properties. And text-decoration: none actually means text-decoration-line: none.

But you cannot meaningfully animate text-decoration-line and text-decoration-style. You can only meaningfully animate text-decoration-color (interpolated) and text-decoration-thickness.

So in your case, you can initially set the text decoration to transparent, and then change on hover. You can alternatively animate the thickness, starting with text-decoration-thickness: 0;.

.email-address {
  text-decoration-thickness: from-font;
  text-decoration-color: transparent;
}

.email-address:hover {
  text-decoration-thickness: 1px;
  text-decoration-color: currentColor;
  transition: all ease-in-out 0.25s;
}

.email-2:hover {
  text-decoration-thickness: 4px;
  text-decoration-color: red;
  transition: all ease-in-out 0.5s;
}

.email-3:hover {
  text-decoration-thickness: 2px;
  text-decoration-color: green;
  transition: all ease-in-out 1s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>
    email1@acme.com
  </li>
  <li>
    email2@acme.com
  </li>
  <li>
    email3@acme.com
  </li>
</ul></code>```

Additional Reference:

https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration

Title: Applying 'transition' effect to <a> elements not working properly

Body:
Below is some HTML code that I have for a website I'm working on:

.container {
    display: flex;
    flex-direction: row;
    position: relative;
    top: 10%;
    width: 25vw;
    min-width: 428px;
    height: auto;
    padding: 15px;

    justify-content: left;
    align-items: center;

    background-color: white;
}

.container a {
  color: black;
  margin-left: 10px;
  text-decoration: none;
  transition: all ease-in-out 0.25s;
}

.container a h2:hover {
  text-decoration: underline;
}

.container a img {
    width: 100px;
    height: auto;
}

.container + .container {
  margin-top: 20px;
}

Contact

In need of a commission? Do you just want to talk? Let me know by shooting me an email or DMing me on Instagram.

@bellapfisterphotography

mail@gmail.com

For some reason, the underline transition I'm applying to the containers  elements is not functioning as intended. Any help on fixing this or explaining why this happens would be greatly appreciated.

Body:
That's because you are applying text-decoration on two different elements:

.container a {
  ...
  text-decoration: none;
}

.container a h2:hover {
  text-decoration: underline;
}

text-decoration is a shorthand for text-decoration-line, text-decoration-color, text-decoration-style, and text-decoration-thickness properties. And text-decoration: none actually means text-decoration-line: none.

But you cannot meaningfully animate text-decoration-line and text-decoration-style. You can only meaningfully animate text-decoration-color (interpolated) and text-decoration-thickness.

So in your case, you can initially set the text decoration to transparent, and then change on hover. You can alternatively animate the thickness, starting with text-decoration-thickness: 0;.

.email-address {
  text-decoration-thickness: from-font;
  text-decoration-color: transparent;
}

.email-address:hover {
  text-decoration-thickness: 1px;
  text-decoration-color: currentColor;
  transition: all ease-in-out 0.25s;
}

.email-2:hover {
  text-decoration-thickness: 4px;
  text-decoration-color: red;
  transition: all ease-in-out 0.5s;
}

.email-3:hover {
  text-decoration-thickness: 2px;
  text-decoration-color: green;
  transition: all ease-in-out 1s;
}

<ul>
  <li>
    <a class="email-address email-1" href="#">email1@acme.com</a>
  </li>
  <li>
    <a class="email-address email-2" href="#">email2@acme.com</a>
  </li>
  <li>
    <a class="email-address email-3" href="#">email3@acme.com</a>
  </li>
</ul>

Additional Reference:

https://developer.mozilla.org/en-US/docs/Web/CSS/text-decoration


问:
fetch response 404 but page exists
I'm have this Fetch code (POST) but the response says status: 404 even though when I open the url in the browser, the page exists and returns a JSON. when I changed the url to https://httpbin.org/post it returns a normal data.. and when I use the same url but with GET method (without any init parameters for the fetch method) it returns status: 200.

what am I doing wrong?

when I open the url in the browser:

php controller

```<code>/*
 * filepath: application/modules/test/controllers/test.php
*/
public function homepage()
{
  $this->load->view('home', $this->data);
}

public function get_result()
{
  $response = [
    'status' => 0,
    'message' => 'abcde',
  ];
  echo json_encode($response);
}
</code>```

html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="button" id="btn1" value="Button1">

    <script src="/assets/js/test_fetch.js"></script>
</body>
</html>
</code>```

javascript

```<code>/*
 * filepath: /assets/js/test_fetch.js
*/
/*!
 * Filename: test_fetch.js
 * Tanggal: 20220214
 * Author: david santana
 * script utk belajar ttg penggunaan fetch API
 * Copyright Gotravelly.com@2022
*/
const myBtn1 = document.querySelector('#btnSubmit');
console.log(myBtn1);
myBtn1.addEventListener('click', function() {
    // fetch data from server
    const url = '/test/get_results';
    // const url = 'https://httpbin.org/post';
    let myData = {
        user_id: 123,
        name: 'david',
    };
    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify(myData)
    })
        .then(response => console.log(response));
});
</code>```

答:
never mind, my colleague pointed out to me that I didn't add the csrf and I need to use FormData in the body parameter.. after I tried it, it works!

but then I tried to use Object with the same csrf key-value pair like this, but it doesn't work

```<code>let myData = {
  user_id: 123,
  name: 'david',
};
let csrf_name = document.querySelector('#csrf').attributes['name'].value;
let csrf = document.querySelector('#csrf').value;
myData[csrf_name] = csrf;
</code>```

which brings me to a new question (if I may ask a follow-up question): does POST needs to always use a FormData as body parameter?

Title: fetch response 404 but page exists

Body:
I'm have this Fetch code (POST) but the response says status: 404 even though when I open the url in the browser, the page exists and returns a JSON. when I changed the url to https://httpbin.org/post it returns a normal data.. and when I use the same url but with GET method (without any init parameters for the fetch method) it returns status: 200.

what am I doing wrong?

when I open the url in the browser:

php controller

/*
 * filepath: application/modules/test/controllers/test.php
*/
public function homepage()
{
  $this->load->view('home', $this->data);
}

public function get_result()
{
  $response = [
    'status' => 0,
    'message' => 'abcde',
  ];
  echo json_encode($response);
}

html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <input type="button" id="btn1" value="Button1">

javascript

/*
 * filepath: /assets/js/test_fetch.js
*/
/*!
 * Filename: test_fetch.js
 * Tanggal: 20220214
 * Author: david santana
 * script utk belajar ttg penggunaan fetch API
 * Copyright Gotravelly.com@2022
*/
const myBtn1 = document.querySelector('#btnSubmit');
console.log(myBtn1);
myBtn1.addEventListener('click', function() {
    // fetch data from server
    const url = '/test/get_results';
    // const url = 'https://httpbin.org/post';
    let myData = {
        user_id: 123,
        name: 'david',
    };
    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: JSON.stringify(myData)
    })
        .then(response => console.log(response));
});

Body:
never mind, my colleague pointed out to me that I didn't add the csrf and I need to use FormData in the body parameter.. after I tried it, it works!

but then I tried to use Object with the same csrf key-value pair like this, but it doesn't work

let myData = {
  user_id: 123,
  name: 'david',
};
let csrf_name = document.querySelector('#csrf').attributes['name'].value;
let csrf = document.querySelector('#csrf').value;
myData[csrf_name] = csrf;

which brings me to a new question (if I may ask a follow-up question): does POST needs to always use a FormData as body parameter?


问:
Flutter: How to validate a URL String in a SignUp Form?
I have a Sign-up form with the following input fields:

Domain
Name
Email
Password

What I would like to achieve is the following process:

User types in Business Domain URL, types in Email address connected to the Domain and a Password.

What's the best way to make the app check in the background if the Domain sends back a 200 code to assure validation?
We can talk about a compensation, if that is desired.

I've experimented with "http 0.12.0+4" on pub.dev but it wasn't constructed exactly for what i want to achieve.

```<code>import 'package:easybeezzy/screens/login_screen.dart';
import 'package:flutter/material.dart';

class SignupScreen extends StatefulWidget {
  static final String id = 'signup_screen';

  @override
  _SignupScreenState createState() => _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  final _formKey = GlobalKey<FormState>();
  String _name, _email, _password, _domain;

  _submit() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      print(_name);
      print(_domain);
      print(_email);
      print(_password);
      //Logging in the User with Firebase
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Easy Beezy',
                  style: TextStyle(
                    fontSize: 50.0,
                    fontFamily: 'PlayfairDisplay',
                  ),
                ),
                Form(
                  key: _formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Domain'),
                          validator: (input) => input.length < 3
                              ? 'Please enter a valid Domain'
                              : null,
                          onSaved: (input) => _domain = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Name'),
                          validator: (input) => input.trim().isEmpty
                              ? 'Please enter a valid name'
                              : null,
                          onSaved: (input) => _name = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                            horizontal: 30.0, vertical: 10.0),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Email'),
                          validator: (input) => !input.contains('@')
                              ? 'Please enter a valid email, must be connected to the DOMAIN.'
                              : null,
                          onSaved: (input) => _email = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Password'),
                          validator: (input) => input.length < 6
                              ? 'Must be at least six characters'
                              : null,
                          onSaved: (input) => _password = input,
                          obscureText: true,
                        ),
                      ),
                      SizedBox(height: 20.0),
                      Container(
                        width: 250.0,
                        child: FlatButton(
                          onPressed: _submit,
                          color: Colors.amberAccent,
                          padding: EdgeInsets.all(10.0),
                          child: Text(
                            'Sign Up',
                            style: TextStyle(
                                fontSize: 20.0, color: Colors.black54),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 20.0,
                      ),
                      Container(
                        width: 250.0,
                        child: FlatButton(
                          onPressed: () => Navigator.pop(context),
                          color: Colors.blueAccent,
                          padding: EdgeInsets.all(10.0),
                          child: Text(
                            'Back to login',
                            style:
                                TextStyle(fontSize: 20.0, color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
</code>```

Thank you very much for your time, if you need more info about my project let me know so I can provide it to you.
You will not be forgotten once the app is ready for testing.

答:
You can use Uri.parse to check if the URL is valid.

bool validURL = Uri.parse(url).isAbsolute;
```

If you have a List of domains to validate with, you can use List.contains(String) - this returns a boolean.

Body:
I have a Sign-up form with the following input fields:

Domain
Name
Email
Password

What I would like to achieve is the following process:

User types in Business Domain URL, types in Email address connected to the Domain and a Password.

What's the best way to make the app check in the background if the Domain sends back a 200 code to assure validation?
We can talk about a compensation, if that is desired.

I've experimented with "http 0.12.0+4" on pub.dev but it wasn't constructed exactly for what i want to achieve.

import 'package:easybeezzy/screens/login_screen.dart';
import 'package:flutter/material.dart';

class SignupScreen extends StatefulWidget {
  static final String id = 'signup_screen';

  @override
  _SignupScreenState createState() => _SignupScreenState();
}

class _SignupScreenState extends State<SignupScreen> {
  final _formKey = GlobalKey<FormState>();
  String _name, _email, _password, _domain;

  _submit() {
    if (_formKey.currentState.validate()) {
      _formKey.currentState.save();
      print(_name);
      print(_domain);
      print(_email);
      print(_password);
      //Logging in the User with Firebase
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: SingleChildScrollView(
          child: Container(
            height: MediaQuery.of(context).size.height,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Easy Beezy',
                  style: TextStyle(
                    fontSize: 50.0,
                    fontFamily: 'PlayfairDisplay',
                  ),
                ),
                Form(
                  key: _formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Domain'),
                          validator: (input) => input.length < 3
                              ? 'Please enter a valid Domain'
                              : null,
                          onSaved: (input) => _domain = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Name'),
                          validator: (input) => input.trim().isEmpty
                              ? 'Please enter a valid name'
                              : null,
                          onSaved: (input) => _name = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                            horizontal: 30.0, vertical: 10.0),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Email'),
                          validator: (input) => !input.contains('@')
                              ? 'Please enter a valid email, must be connected to the DOMAIN.'
                              : null,
                          onSaved: (input) => _email = input,
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(
                          horizontal: 30.0,
                          vertical: 10.0,
                        ),
                        child: TextFormField(
                          decoration: InputDecoration(labelText: 'Password'),
                          validator: (input) => input.length < 6
                              ? 'Must be at least six characters'
                              : null,
                          onSaved: (input) => _password = input,
                          obscureText: true,
                        ),
                      ),
                      SizedBox(height: 20.0),
                      Container(
                        width: 250.0,
                        child: FlatButton(
                          onPressed: _submit,
                          color: Colors.amberAccent,
                          padding: EdgeInsets.all(10.0),
                          child: Text(
                            'Sign Up',
                            style: TextStyle(
                                fontSize: 20.0, color: Colors.black54),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 20.0,
                      ),
                      Container(
                        width: 250.0,
                        child: FlatButton(
                          onPressed: () => Navigator.pop(context),
                          color: Colors.blueAccent,
                          padding: EdgeInsets.all(10.0),
                          child: Text(
                            'Back to login',
                            style:
                                TextStyle(fontSize: 20.0, color: Colors.white),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Thank you very much for your time, if you need more info about my project let me know so I can provide it to you.
You will not be forgotten once the app is ready for testing.

Body:
You can use Uri.parse to check if the URL is valid.

bool validURL = Uri.parse(url).isAbsolute;

If you have a List of domains to validate with, you can use List.contains(String) - this returns a boolean.


问:
Is it proper way to identify one to many relationship flask-sqlalchemy?
```<code>class Restaurant(db.Model):
    __tablename__ = 'Restaurant'
    menu_restaurant = db.relationship('Menu', backref='Restaurant',cascade="all, delete, delete-orphan")

    restaurant_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    restaurant_name = db.Column(db.String(64),nullable=False)
    restaurant_user_id = db.Column(db.Integer, db.ForeignKey("user.user_id"), nullable=False)

    def __init__(self,restaurant_name,restaurant_user_id):
        self.restaurant_name=restaurant_name
        self.restaurant_user_id=restaurant_user_id

class Menu(db.Model):
    __tablename__ = 'menu'
    item_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    menu_restaurant_id = db.Column(db.Integer, db.ForeignKey('Restaurant.restaurant_id',ondelete='CASCADE'), nullable=False)
    item_name = db.Column(db.String(64))
    item_desc = db.Column(db.String(256))
    item_price = db.Column(db.Numeric(10, 2))
    item_image_path = db.Column(db.String(120), nullable=True)

    def __init__(self, menu_restaurant_id, item_name, item_desc,item_price,item_image):
        self.menu_restaurant_id = menu_restaurant_id
        self.item_name = item_name
        self.item_desc = item_desc
        self.item_price = item_price
        self.item_image = item_image
</code>```

Above the code I want to identify one to many relationship between Restaurant and Menu. One restaurant has many menus but each menu must be related with just one restaurant.If it is not true, I require your help.

答:
I think you have done it in right way.

Is it showing any error when you record data in your Main?

If not, then you have to check whether that Restaurant is having many menus by using for loop in html(jinja templating).
I am assuming that you are familiar with jinja and know to retrieve data from table(and their relationship also)

Just giving you a hint so that you can retrieve all the Menus of that Restaurant.

...

```<code>extract_menus = Restaurant.query.filter_by(Restaurant.menu_restaurant).()
return render_template('xyz.html', extract_menus=extract_menus)
</code>```

after this, work on your html template.

I hope I am able give you exact or nearby answer, any suggestion or questions-- you can ask

Body:
class Restaurant(db.Model):
    __tablename__ = 'Restaurant'
    menu_restaurant = db.relationship('Menu', backref='Restaurant',cascade="all, delete, delete-orphan")

    restaurant_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    restaurant_name = db.Column(db.String(64),nullable=False)
    restaurant_user_id = db.Column(db.Integer, db.ForeignKey("user.user_id"), nullable=False)

    def __init__(self,restaurant_name,restaurant_user_id):
        self.restaurant_name=restaurant_name
        self.restaurant_user_id=restaurant_user_id

class Menu(db.Model):
    __tablename__ = 'menu'
    item_id = db.Column(db.Integer, primary_key=True,autoincrement=True)
    menu_restaurant_id = db.Column(db.Integer, db.ForeignKey('Restaurant.restaurant_id',ondelete='CASCADE'), nullable=False)
    item_name = db.Column(db.String(64))
    item_desc = db.Column(db.String(256))
    item_price = db.Column(db.Numeric(10, 2))
    item_image_path = db.Column(db.String(120), nullable=True)

    def __init__(self, menu_restaurant_id, item_name, item_desc,item_price,item_image):
        self.menu_restaurant_id = menu_restaurant_id
        self.item_name = item_name
        self.item_desc = item_desc
        self.item_price = item_price
        self.item_image = item_image

Above the code I want to identify one to many relationship between Restaurant and Menu. One restaurant has many menus but each menu must be related with just one restaurant.If it is not true, I require your help.

Body:
I think you have done it in right way.

Is it showing any error when you record data in your Main?

If not, then you have to check whether that Restaurant is having many menus by using for loop in html(jinja templating).
I am assuming that you are familiar with jinja and know to retrieve data from table(and their relationship also)

Just giving you a hint so that you can retrieve all the Menus of that Restaurant.

...

extract_menus = Restaurant.query.filter_by(Restaurant.menu_restaurant).()
return render_template('xyz.html', extract_menus=extract_menus)

after this, work on your html template.

I hope I am able give you exact or nearby answer, any suggestion or questions-- you can ask


问:
C++ function timeout wrapper
Based on How to implement timeout for function in c++, I wrote this wrapper:

```<code>template <typename t_time, typename t_function, typename... t_params>
inline std::conditional_t<
    // if 't_function' return type is 'void'
    std::is_void_v<std::invoke_result_t<t_function, const bool &, t_params...>>,
    // the 'execute' wrapper will return 'bool', which will be 'true' if the
    // 'p_function' executes in less 'p_max_time', or 'false' otherwise
    bool,
    // else it will result a 'std::optional' with the return type of
    // 't_function', which will contain a value of that type, if the
    // 'p_function' executes in less 'p_max_time', or empty otherwise
    std::optional<std::invoke_result_t<t_function, const bool &, t_params...>>>
execute(t_time p_max_time, t_function &p_function, t_params &&... p_params) {
  std::mutex _mutex;
  std::condition_variable _cond;
  bool _timeout{false};

  typedef typename std::invoke_result_t<t_function, const bool &, t_params...>
      t_ret;

  if constexpr (std::is_void_v<t_ret>) {
    std::thread _th([&]() -> void {
      p_function(_timeout, std::forward<t_params>(p_params)...);
      _cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_mutex};
    if (_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return true;
    }

    _timeout = true;
    _th.detach();
    return false;
  } else {
    t_ret _ret;

    std::thread _th([&]() -> void {
      _ret = p_function(_timeout, std::forward<t_params>(p_params)...);
      _cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_mutex};
    if (_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return {std::move(_ret)};
    }
    _timeout = true;

    _th.detach();
    return {};
  }
}
</code>```

Unlike the code in the answers for the question I referenced, I would not like to throw an exception in the execute wrapper. If p_function does not return, the wrapper will return a bool, true if p_function executed in at most p_max_time, false otherwise. If p_function returns T, the wrapper will return std::optional<T> which will have a value if p_function does not exceed p_max_time, or it will be empty otherwise.

The const bool & parameter required for p_function is used to inform p_function that its execution exceeded p_max_time, so p_function may stop its execution, though execute will not count on it.

Here is an example:

```<code>    auto _function = [](const bool &p_is_timeout, int &&p_i) -> void {
      std::this_thread::sleep_for(1s);
      if (p_is_timeout) {
        std::cout << "timeout";
      } else {
        std::cout << "i = " << p_i << '\n';
      }
    };
    int _i{4};

    if (!async::execute(200ms, _function, std::move(_i))) {
      std::cout << "TIMEOUT!!\n";
    }
</code>```

So, the problem is _th.detach() causes crash when I execute some test functions in a row. I if change it to _th.join(), the crash no longer occurs, but, obviously, the function that calls the wrapper has to wait for p_function to end, which is not desired.

How can I make execute detach _th thread, without causing crash?

答:
Your lambda needs access to the local variables _ret and cond these don't exist after the end of execute so your code has undefined behaviour. Lambdas that capture by reference should only be used when the lambda has the same lifetime as the code that they're defined in.

You'd need to define your state variables in the heap so that they exist after the end of the function. For example you could use a shared_ptr:

```<code>template <typename Result>
struct state
{
  std::mutex _mutex;
  std::condition_variable _cond;
  Result _ret;
};
template <>
struct state<void>
{
  std::mutex _mutex;
  std::condition_variable _cond;
};

template <typename t_time, typename t_function, typename... t_params>
inline std::conditional_t<
    // if 't_function' return type is 'void'
    std::is_void_v<std::invoke_result_t<t_function, const bool &, t_params...>>,
    // the 'execute' wrapper will return 'bool', which will be 'true' if the
    // 'p_function' executes in less 'p_max_time', or 'false' otherwise
    bool,
    // else it will result a 'std::optional' with the return type of
    // 't_function', which will contain a value of that type, if the
    // 'p_function' executes in less 'p_max_time', or empty otherwise
    std::optional<std::invoke_result_t<t_function, const bool &, t_params...>>>
execute(t_time p_max_time, t_function &p_function, t_params &&... p_params) {
  typedef typename std::invoke_result_t<t_function, const bool &, t_params...>
      t_ret;
  auto _state = std::make_shared<state<t_ret>>();
  bool _timeout{false};

  if constexpr (std::is_void_v<t_ret>) {
    std::thread _th([&, _state]() -> void {
      p_function(_timeout, std::forward<t_params>(p_params)...);
      _state->_cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_state->_mutex};
    if (_state->_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return true;
    }

    _timeout = true;
    _th.detach();
    return false;
  } else {
    std::thread _th([&, _state]() -> void {
      _state->_ret = p_function(_timeout, std::forward<t_params>(p_params)...);
      _state->_cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_state->_mutex};
    if (_state->_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return {std::move(_state->_ret)};
    }
    _timeout = true;

    _th.detach();
    return {};
  }
}
</code>```

Note for simplicity I've left in the capture of the function arguments and function by reference but you still need to ensure those references remain valid for as long as they're needed (e.g. if the timeout is short the function could exit before the target function executes or if the arguments are references then the invoked function can't use those references after the function exits).

If you have c++20 you might want to look into std::jthread

Title: C++ function timeout wrapper

Body:
Based on How to implement timeout for function in c++, I wrote this wrapper:

template <typename t_time, typename t_function, typename... t_params>
inline std::conditional_t<
    // if 't_function' return type is 'void'
    std::is_void_v<std::invoke_result_t<t_function, const bool &, t_params...>>,
    // the 'execute' wrapper will return 'bool', which will be 'true' if the
    // 'p_function' executes in less 'p_max_time', or 'false' otherwise
    bool,
    // else it will result a 'std::optional' with the return type of
    // 't_function', which will contain a value of that type, if the
    // 'p_function' executes in less 'p_max_time', or empty otherwise
    std::optional<std::invoke_result_t<t_function, const bool &, t_params...>>>
execute(t_time p_max_time, t_function &p_function, t_params &&... p_params) {
  std::mutex _mutex;
  std::condition_variable _cond;
  bool _timeout{false};

  typedef typename std::invoke_result_t<t_function, const bool &, t_params...>
      t_ret;

  if constexpr (std::is_void_v<t_ret>) {
    std::thread _th([&]() -> void {
      p_function(_timeout, std::forward<t_params>(p_params)...);
      _cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_mutex};
    if (_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return true;
    }

    _timeout = true;
    _th.detach();
    return false;
  } else {
    t_ret _ret;

    std::thread _th([&]() -> void {
      _ret = p_function(_timeout, std::forward<t_params>(p_params)...);
      _cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_mutex};
    if (_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return {std::move(_ret)};
    }
    _timeout = true;

    _th.detach();
    return {};
  }
}

Unlike the code in the answers for the question I referenced, I would not like to throw an exception in the execute wrapper. If p_function does not return, the wrapper will return a bool, true if p_function executed in at most p_max_time, false otherwise. If p_function returns T, the wrapper will return std::optional<T> which will have a value if p_function does not exceed p_max_time, or it will be empty otherwise.

The const bool & parameter required for p_function is used to inform p_function that its execution exceeded p_max_time, so p_function may stop its execution, though execute will not count on it.

Here is an example:

    auto _function = [](const bool &p_is_timeout, int &&p_i) -> void {
      std::this_thread::sleep_for(1s);
      if (p_is_timeout) {
        std::cout << "timeout";
      } else {
        std::cout << "i = " << p_i << '\n';
      }
    };
    int _i{4};

    if (!async::execute(200ms, _function, std::move(_i))) {
      std::cout << "TIMEOUT!!\n";
    }

So, the problem is _th.detach() causes crash when I execute some test functions in a row. I if change it to _th.join(), the crash no longer occurs, but, obviously, the function that calls the wrapper has to wait for p_function to end, which is not desired.

How can I make execute detach _th thread, without causing crash?

Body:
Your lambda needs access to the local variables _ret and cond these don't exist after the end of execute so your code has undefined behaviour. Lambdas that capture by reference should only be used when the lambda has the same lifetime as the code that they're defined in.

You'd need to define your state variables in the heap so that they exist after the end of the function. For example you could use a shared_ptr:

template <typename Result>
struct state
{
  std::mutex _mutex;
  std::condition_variable _cond;
  Result _ret;
};
template <>
struct state<void>
{
  std::mutex _mutex;
  std::condition_variable _cond;
};

template <typename t_time, typename t_function, typename... t_params>
inline std::conditional_t<
    // if 't_function' return type is 'void'
    std::is_void_v<std::invoke_result_t<t_function, const bool &, t_params...>>,
    // the 'execute' wrapper will return 'bool', which will be 'true' if the
    // 'p_function' executes in less 'p_max_time', or 'false' otherwise
    bool,
    // else it will result a 'std::optional' with the return type of
    // 't_function', which will contain a value of that type, if the
    // 'p_function' executes in less 'p_max_time', or empty otherwise
    std::optional<std::invoke_result_t<t_function, const bool &, t_params...>>>
execute(t_time p_max_time, t_function &p_function, t_params &&... p_params) {
  typedef typename std::invoke_result_t<t_function, const bool &, t_params...>
      t_ret;
  auto _state = std::make_shared<state<t_ret>>();
  bool _timeout{false};

  if constexpr (std::is_void_v<t_ret>) {
    std::thread _th([&, _state]() -> void {
      p_function(_timeout, std::forward<t_params>(p_params)...);
      _state->_cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_state->_mutex};
    if (_state->_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return true;
    }

    _timeout = true;
    _th.detach();
    return false;
  } else {
    std::thread _th([&, _state]() -> void {
      _state->_ret = p_function(_timeout, std::forward<t_params>(p_params)...);
      _state->_cond.notify_one();
    });

    std::unique_lock<std::mutex> _lock{_state->_mutex};
    if (_state->_cond.wait_for(_lock, p_max_time) != std::cv_status::timeout) {
      _th.join();
      return {std::move(_state->_ret)};
    }
    _timeout = true;

    _th.detach();
    return {};
  }
}

Note for simplicity I've left in the capture of the function arguments and function by reference but you still need to ensure those references remain valid for as long as they're needed (e.g. if the timeout is short the function could exit before the target function executes or if the arguments are references then the invoked function can't use those references after the function exits).

If you have c++20 you might want to look into std::jthread


问:
How to make git skip some files on merge between branches
I have a docker multi-project, where some files are configuration and bash scripting files

.env (eg. facebook_app_id=abcd)

build.sh (eg. checkout project with depth 1)

install.sh

They specify how the different projects communicate together, which is different when in production or in development mode.

I solved this by creating different branches (dev, test, preprod, and prod) and having those files with the same names but different content in each branch.

So my need is to have those files present in git, but I don't want them to override content between branches. I can have a version in master, then modify it in each branch so that they become conflicting to get a warning at each merge, but that's not very user-friendly.

I've read this post, but it still doesn't answer my needs.

Any ideas?

答:
Since you want the files to be part of your repo, you dont want to ignore them.

But changes to settings for environmental-dependent attributes shall not be commit and merge every time. You can put files into skip-worktree for this. Works locally and needs to be setup at every local git repo.

https://compiledsuccessfully.dev/git-skip-worktree/

It might take some time (amount of commits merged) till the configuration files are all merged into one, but after that you only need to pay attention to the configurations when you actually change them.


问:
How to parameterize a part of string in a field of the response in karate
I am trying to print a response based on the particular parameters.
For that, I have the response from an API as below:

```<code>{
    "ABC": {
        "code": "ABC",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
    "DEF": {
        "code": "DEF",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "1",
        },
        "priority": "1"
    },
    "GHI": {
        "code": "GHI",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "2",
        },
        "priority": "1"
    },
    "JKL": {
        "code": "JKL",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
}
</code>```

Here is the feature file that I am using to print that particular value:

```<code>Feature: Value extraction
    Background:
    * def all = [ABC,DEF,GHI,JKL]
</code>```

Scenario: Extract response value

```<code>Given url
When method get
Then status 200
And def value = []
And eval for(var i=0;i<all.length;i++) {value.add(response['#(all[i])']["execution"]["status"]) }
And print value
</code>```

I want to extract the value of all parameters whose status is "0".

```<code>print response["ABC"]["execution"]["status"]
</code>```

The above line gives the result but I want to parameterise the ["ABC"] part
Any help on this? Is there any other way I can achieve this or am I doing something wrong to achieve this particular edge case?

答:
I'm providing a sample below that answers multiple questions:

```<code>* def response =
"""
{
    "ABC": {
        "code": "ABC",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
    "DEF": {
        "code": "DEF",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "1",
        },
        "priority": "1"
    }
}
"""
# get all values in root json
* def items = $.*
* def code = 'ABC'
* def found = items.filter(x => x.code == code && x.execution.status == '0')
* assert found.length == 1
# the expression on the right below is pure JS
* match found[0] == response[code]
</code>```

Note:

how to use json-path to simplify JSON, also refer: https://stackoverflow.com/a/68811696/143475

how to use the filter() API to "find" data using complex expressions, that can be parameterized, also see: https://github.com/karatelabs/karate#json-transforms

how to get the value of a key that can be dynamic and parameterized

Body:
I am trying to print a response based on the particular parameters.
For that, I have the response from an API as below:

{
    "ABC": {
        "code": "ABC",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
    "DEF": {
        "code": "DEF",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "1",
        },
        "priority": "1"
    },
    "GHI": {
        "code": "GHI",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "2",
        },
        "priority": "1"
    },
    "JKL": {
        "code": "JKL",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
}

Here is the feature file that I am using to print that particular value:

Feature: Value extraction
    Background:
    * def all = [ABC,DEF,GHI,JKL]

Scenario: Extract response value

Given url
When method get
Then status 200
And def value = []
And eval for(var i=0;i<all.length;i++) {value.add(response['#(all[i])']["execution"]["status"]) }
And print value

I want to extract the value of all parameters whose status is "0".

print response["ABC"]["execution"]["status"]

The above line gives the result but I want to parameterise the ["ABC"] part
Any help on this? Is there any other way I can achieve this or am I doing something wrong to achieve this particular edge case?

Body:
I'm providing a sample below that answers multiple questions:

* def response =
"""
{
    "ABC": {
        "code": "ABC",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "0",
        },
        "priority": "1"
    },
    "DEF": {
        "code": "DEF",
        "isActive": "true",
        "lastUpdatedBy": "username",
        "execution": {
            "status": "1",
        },
        "priority": "1"
    }
}
"""
# get all values in root json
* def items = $.*
* def code = 'ABC'
* def found = items.filter(x => x.code == code && x.execution.status == '0')
* assert found.length == 1
# the expression on the right below is pure JS
* match found[0] == response[code]

Note:

how to use json-path to simplify JSON, also refer: https://stackoverflow.com/a/68811696/143475

how to use the filter() API to "find" data using complex expressions, that can be parameterized, also see: https://github.com/karatelabs/karate#json-transforms

how to get the value of a key that can be dynamic and parameterized


问:
Spring Boot SessionScoped Object not expired after logout. Autowires two different objects in different controllers
I needed to auto wire logged in User Object in my controller /service classes. So i created a util Bean as

```<code>@Component
public class UtilBeans {
    @Autowired
    UserService userService;

    @Bean(name = "loggedInUser")
    @SessionScope
    public UserMaster userMaster() {
        UserMaster user;
        try {
            user = (UserMaster) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            user.setAuthorities(userService.getUserAuthorities(user.getUserId()));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("user Not logged in");

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

and used in controller class as

```<code>@Autowired
    @Qualifier(value = "loggedInUser")
    UserMaster user;
</code>```

In  most controllers  it works OK, but in some controllers first logged in user object doesn't change until I restart the application.

my logout configuration is as follows

```<code>.formLogin().loginPage("/loginForm").permitAll()
                .and()
                .formLogin().defaultSuccessUrl("/dashboard").and()

                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .deleteCookies("JSESSIONID").clearAuthentication(true)
                .invalidateHttpSession(true).permitAll();
</code>```

Please help me where I am doing wrong. What I understand is , Session Scoped object should expire on logout, and it do changes but why not in some cases.

答: I by mistake assigned a different object of same type and same id to user in controller, changing code to remove that assignment fixed the problem.</p>

Body:
I needed to auto wire logged in User Object in my controller /service classes. So i created a util Bean as

@Component
public class UtilBeans {
    @Autowired
    UserService userService;

    @Bean(name = "loggedInUser")
    @SessionScope
    public UserMaster userMaster() {
        UserMaster user;
        try {
            user = (UserMaster) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            user.setAuthorities(userService.getUserAuthorities(user.getUserId()));

        } catch (Exception e) {
            // TODO Auto-generated catch block
            System.out.println("user Not logged in");

        }
        return user;
    }
}

and used in controller class as

@Autowired
    @Qualifier(value = "loggedInUser")
    UserMaster user;

In  most controllers  it works OK, but in some controllers first logged in user object doesn't change until I restart the application.

my logout configuration is as follows

.formLogin().loginPage("/loginForm").permitAll()
                .and()
                .formLogin().defaultSuccessUrl("/dashboard").and()

                .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .deleteCookies("JSESSIONID").clearAuthentication(true)
                .invalidateHttpSession(true).permitAll();

Please help me where I am doing wrong. What I understand is , Session Scoped object should expire on logout, and it do changes but why not in some cases.


问:
Autoload MEMORY table from another MyISAM table
To increase server performance, I decided to use memory table for faster reading user's info.

My question is: How to auto load MEMORY table from another MyISAM table after server shutdown?

I can check rows count every time I want to lookup in MEMORY and then, load row by row by a PHP script, but it takes time to read 2,000,000 records from MyISAM and save in MEMORY. and checking rows count. although it is not thread safe and I should take care of it.

Is there any better way?

答: Simplest would be to modify whatever script is starting MySQL (mysqld_safe?) and have it run 'mysql' to issue a command to run a stored proc which does your table populating. I don't believe MySQL has anything internally that you can trigger automatically at startup, or any kind of internal job scheduler.</p>


问:
C++ ofStream: "<<" vs "put"
Being new to C++, I am confused about what << and put() means while using ofstream to write to a text file. I tried to experiment with the two following styles as follows:

Approach 1:

```<code>void writeTester() {
    std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc);
    std::vector<int> v{ 1,2,3,4 };
    for (int i = 0;i < 4;i++) {
        oFile.put(v[i]);
        //casting to character pointer and writing also produced similar result
        //oFile.put(*(char*)&v[i]);
    }
    oFile.close();
}
</code>```

Approach 2:

```<code>void writeTester() {
    std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc);
    std::vector<int> v{ 1,2,3,4 };
    for (int i = 0;i < 4;i++) {
        oFile << v[i];
    }
    oFile.close();
}
</code>```

While Approach 2 wrote the expected result to file (1234), Approach 1 wrote some garbage value to the file.

What is the difference between the 2 styles, and when to use which one? Also, what is the correct way to use Approach 1 to have "1234" as the output written to the file?

答:
Simply put, using the '<<' operator means certain overloads can be used, which means writing integer values (as in your case) will mean they're converting to their string representations before being written to the file.

Using put, however, will write a single byte to the stream. This means your 4 byte int will be truncated to a single byte, thus writing nonsense data to your file.

Here's the documentation for ofstream::put.
And here's the documentation for ofstream.

For completion, and to spark your interest, here's an ASCII table, where you can look up the values you were writing to the file. Depends on the byte order (endianness) of your machine, which char is written. On LE machines it should be NUL, but I get confused myself sometimes and mix up the byte orders in my head so please take that last sentence with a grain of salt.

Title: C++ ofStream: "<<" vs "put"

Body:
Being new to C++, I am confused about what << and put() means while using ofstream to write to a text file. I tried to experiment with the two following styles as follows:

Approach 1:

void writeTester() {
    std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc);
    std::vector<int> v{ 1,2,3,4 };
    for (int i = 0;i < 4;i++) {
        oFile.put(v[i]);
        //casting to character pointer and writing also produced similar result
        //oFile.put(*(char*)&v[i]);
    }
    oFile.close();
}

Approach 2:

void writeTester() {
    std::ofstream oFile("Resources/tst.txt", std::ios::out | std::ios::trunc);
    std::vector<int> v{ 1,2,3,4 };
    for (int i = 0;i < 4;i++) {
        oFile << v[i];
    }
    oFile.close();
}

While Approach 2 wrote the expected result to file (1234), Approach 1 wrote some garbage value to the file.

What is the difference between the 2 styles, and when to use which one? Also, what is the correct way to use Approach 1 to have "1234" as the output written to the file?


问:
Wiremock UI to connect to locally running Wiremock standalone server
I have downloaded the wiremock standalone jar locally. And I am starting the standalone server using below command.
java -jar wiremock-jre8-standalone-2.26.3.jar --port 8089 &
I am placing all the mocked endpoints under the mappings folder.

I need a user interface which can connect to my wiremock server and show me all the mappings.
It would be of advantage if the UI could provide features for editing, deleting and adding new files permanently.

答: Use any version from https://github.com/holomekc/wiremock/releases and run executable jar having mocked endpoint JSONs under the mappings folder.If you have not provided port configuration then UI with mapping details will be accessible over URL http://localhost:8080/__admin/webapp</p>


问:
How to use Python Unittest TearDownClass with TestResult.wasSuccessful()
I wanted to call setUpClass and tearDownClass so that setup and teardown would be performed only once for each test.  However, it keeps failing for me when I call tearDownClass.  I only want to record 1 test result, either PASS if both tests passed or FAIL if both tests failed. If I call only setup and tearDown then all works fine:

Calling setUpClass and tearDownClass:

```<code>#!/usr/bin/python

import datetime
import itertools
import logging
import os
import sys
import time
import unittest

LOGFILE = 'logfile.txt'

class MyTest(unittest.TestCase):

    global testResult
    testResult = None

    @classmethod
    def setUpClass(self):

        ## test result for DB Entry:
        self.dbresult_dict = {
             'SCRIPT'       : 'MyTest.py',
             'RESULT'      : testResult,
        }

    def test1(self):

       expected_number = 10
       actual_number = 10

       self.assertEqual(expected_number, actual_number)

   def test2(self):

       expected = True
       actual = True

       self.assertEqual(expected, actual)

   def run(self, result=None):
       self.testResult = result
       unittest.TestCase.run(self, result)

   @classmethod
   def tearDownClass(self):
       ok = self.testResult.wasSuccessful()
       errors = self.testResult.errors
       failures = self.testResult.failures
       if ok:
           self.dbresult_dict['RESULT'] = 'Pass'
       else:
           logging.info(' %d errors and %d failures',
                 len(errors), len(failures))
           self.dbresult_dict['RESULT'] = 'Fail'

if __name__ == '__main__':
   logger = logging.getLogger()
   logger.addHandler(logging.FileHandler(LOGFILE, mode='a'))
   stderr_file = open(LOGFILE, 'a')

   runner = unittest.TextTestRunner(verbosity=2, stream=stderr_file, descriptions=True)
   itersuite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
   runner.run(itersuite)
   sys.exit()
   unittest.main(module=itersuite, exit=True)

stderr_file.close()
</code>```

Error:

```<code>test1 (__main__.MyTest) ... ok
test2 (__main__.MyTest) ... ok
ERROR
===================================================================
ERROR: tearDownClass (__main__.MyTest)
-------------------------------------------------------------------
Traceback (most recent call last):
   File "testTearDownClass.py", line 47, in tearDownClass
    ok = self.testResult.wasSuccessful()
AttributeError: type object 'MyTest' has no attribute 'testResult'
----------------------------------------------------------------------
Ran 2 tests in 0.006s
FAILED (errors=1)
</code>```

答:
like @Marcin already pointed out, you're using the Unittest-Framework in a way it isn't intended.

To see if the tests are successful you check the given values with the expected, like you already did: assertEqual(given, expected). Unittest will then collect a summary of failed ones. you don't have to do this manually.

If you want to check that two tests need to be together successful or fail together, these should be combined in ONE Test, maybe as a additionally one, if the individual Tests need to be checked as well. This is nothing you want to save and load afterwards. The tests itself should be as stateless as possible.

When you say you want to run the SetUp and TearDown 'once per test', do you mean once per test-method or per test-run? This is different if you have more than one test-method inside your class:

setUp() Will be called before each test-method

tearDown() Will be called after each test-method

setUpClass() Will be called once per class (before the first test-method of this class)

tearDownClass() Will be called once per class (after the last test-method of this class)

Here's the official documentation

Here's a related answer

Body:
I wanted to call setUpClass and tearDownClass so that setup and teardown would be performed only once for each test.  However, it keeps failing for me when I call tearDownClass.  I only want to record 1 test result, either PASS if both tests passed or FAIL if both tests failed. If I call only setup and tearDown then all works fine:

Calling setUpClass and tearDownClass:

#!/usr/bin/python

import datetime
import itertools
import logging
import os
import sys
import time
import unittest

LOGFILE = 'logfile.txt'

class MyTest(unittest.TestCase):

    global testResult
    testResult = None

    @classmethod
    def setUpClass(self):

        ## test result for DB Entry:
        self.dbresult_dict = {
             'SCRIPT'       : 'MyTest.py',
             'RESULT'      : testResult,
        }

    def test1(self):

       expected_number = 10
       actual_number = 10

       self.assertEqual(expected_number, actual_number)

   def test2(self):

       expected = True
       actual = True

       self.assertEqual(expected, actual)

   def run(self, result=None):
       self.testResult = result
       unittest.TestCase.run(self, result)

   @classmethod
   def tearDownClass(self):
       ok = self.testResult.wasSuccessful()
       errors = self.testResult.errors
       failures = self.testResult.failures
       if ok:
           self.dbresult_dict['RESULT'] = 'Pass'
       else:
           logging.info(' %d errors and %d failures',
                 len(errors), len(failures))
           self.dbresult_dict['RESULT'] = 'Fail'

if __name__ == '__main__':
   logger = logging.getLogger()
   logger.addHandler(logging.FileHandler(LOGFILE, mode='a'))
   stderr_file = open(LOGFILE, 'a')

   runner = unittest.TextTestRunner(verbosity=2, stream=stderr_file, descriptions=True)
   itersuite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
   runner.run(itersuite)
   sys.exit()
   unittest.main(module=itersuite, exit=True)

stderr_file.close()

Error:

test1 (__main__.MyTest) ... ok
test2 (__main__.MyTest) ... ok
ERROR
===================================================================
ERROR: tearDownClass (__main__.MyTest)
-------------------------------------------------------------------
Traceback (most recent call last):
   File "testTearDownClass.py", line 47, in tearDownClass
    ok = self.testResult.wasSuccessful()
AttributeError: type object 'MyTest' has no attribute 'testResult'
----------------------------------------------------------------------
Ran 2 tests in 0.006s
FAILED (errors=1)


问:
How do I create a single list of object pairs from two lists in C#?
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:</p>

```<code>List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)
</code>```

答:
Something like this:

```<code> var listA = new object[] { "1", "2", "3" };
 var listB = new object[] { "a", "b", "c" };
 var listC = Enumerable.Zip(listA,listB, (x,y)=>new {x,y});

 foreach (var item in listC)
 {
    Console.WriteLine("{0},{1}", item.x,item.y);
 }
</code>```

Output:
   1,a
   2,b
   3,c

Body:
I have two lists of objects. List A and List B. I need to create List C which combines List A and List B into pairs. For example:

List A
object a1
object a2
object a3

List B
object b1
object b2
object b3

List C (creates pairs)
object c1 (object a1, object b1)
object c2 (object a2, object b2)
object c3 (object a3, object b3)

Body:
Something like this:

 var listA = new object[] { "1", "2", "3" };
 var listB = new object[] { "a", "b", "c" };
 var listC = Enumerable.Zip(listA,listB, (x,y)=>new {x,y});

 foreach (var item in listC)
 {
    Console.WriteLine("{0},{1}", item.x,item.y);
 }

Output:
   1,a
   2,b
   3,c


问:
Create stacked bar chart using data in API
I am beginner to angular and I try to create chart using json data in API and using kendo charts. I importing data using service file. It show data in the console but do not create the graph.

This is my component.html file.

```<code><kendo-chart [style.height]="'90%'" [style.width]="'90%'">
  <kendo-chart-tooltip format='{0}%'></kendo-chart-tooltip>
  <kendo-chart-series>
    <kendo-chart-series-item *ngFor="let item of series"
                             [data]="item.items" [name]="item.value"
                             field="value" categoryField="interval"
                             type="column" stack="true">
    </kendo-chart-series-item>
  </kendo-chart-series>
</kendo-chart>
</code>```

This is my component.ts file

```<code>import { Component, OnInit } from '@angular/core';
import { groupBy, GroupResult } from "@progress/kendo-data-query";
import { StackedBarChartService } from './stacked-bar-chart.service';
  @Component({
  selector: 'app-stacked-bar-chart',
  templateUrl: './stacked-bar-chart.component.html',
  styleUrls: ['./stacked-bar-chart.component.css']
})
export class StackedBarChartComponent implements OnInit {
  public series: GroupResult[];
  stackedbarchartdata: any = [];
  constructor(private StackedBarChart: StackedBarChartService) {
  }
    ngOnInit() {
    this.series = groupBy(this.stackedbarchartdata, [{ field: 'service' }]) as GroupResult[];
    this.StackedBarChart.getMethod().subscribe((res: any) => {
    this.stackedbarchartdata = res;
    console.log(this.stackedbarchartdata);
    })
  }
}
</code>```

This is my dataset

```<code>[
  {
    "id": 1,
    "interval": 1,
    "service": "Service 1",
    "value": 5
  },
  {
    "id": 2,
    "interval": 2,
    "service": "Service 1",
    "value": 15
  },
  {
    "id": 3,
    "interval": 1,
    "service": "Service 2",
    "value": 10
  },
  {
    "id": 4,
    "interval": 2,
    "service": "Service 2",
    "value": 5
  },
</code>```

答:
I have no idea about kendo charts but there is an error in your code.
You are assigning this.series = groupBy ..... but at that point stackedbarchartdata is still null therefore this.serie will always be null or empty.
You should move it inside the subscribe, have a look:

ngOnInit() {
  this.StackedBarChart.getMethod().subscribe((res: any) => {
    this.stackedbarchartdata = res;
    console.log(this.stackedbarchartdata);
    this.series = groupBy(this.stackedbarchartdata, [{ field: 'service' }]) as GroupResult[];
    console.log(this.series);
  });
}
```
<p>and in the HTML:</p>
<pre class="lang-html prettyprint-override"><code><h1 *ngIf="!series">Loading...</h1>
<kendo-chart *ngIf="series" [style.height]="'90%'" [style.width]="'90%'">
  <kendo-chart-tooltip format='{0}%'></kendo-chart-tooltip>
  <kendo-chart-series>
    <kendo-chart-series-item *ngFor="let item of series"
                             [data]="item.items" [name]="item.value"
                             field="value" categoryField="interval"
                             type="column" stack="true">
    </kendo-chart-series-item>
  </kendo-chart-series>
</kendo-chart>
</code>```

again I don't know nothing about kendo charts therefore there might be more errors but i hope this helps you

Body:
I am beginner to angular and I try to create chart using json data in API and using kendo charts. I importing data using service file. It show data in the console but do not create the graph.

This is my component.html file.

<kendo-chart [style.height]="'90%'" [style.width]="'90%'">
  <kendo-chart-tooltip format='{0}%'></kendo-chart-tooltip>
  <kendo-chart-series>
    <kendo-chart-series-item *ngFor="let item of series"
                             [data]="item.items" [name]="item.value"
                             field="value" categoryField="interval"
                             type="column" stack="true">
    </kendo-chart-series-item>
  </kendo-chart-series>
</kendo-chart>

This is my component.ts file

import { Component, OnInit } from '@angular/core';
import { groupBy, GroupResult } from "@progress/kendo-data-query";
import { StackedBarChartService } from './stacked-bar-chart.service';
  @Component({
  selector: 'app-stacked-bar-chart',
  templateUrl: './stacked-bar-chart.component.html',
  styleUrls: ['./stacked-bar-chart.component.css']
})
export class StackedBarChartComponent implements OnInit {
  public series: GroupResult[];
  stackedbarchartdata: any = [];
  constructor(private StackedBarChart: StackedBarChartService) {
  }
    ngOnInit() {
    this.series = groupBy(this.stackedbarchartdata, [{ field: 'service' }]) as GroupResult[];
    this.StackedBarChart.getMethod().subscribe((res: any) => {
    this.stackedbarchartdata = res;
    console.log(this.stackedbarchartdata);
    })
  }
}

This is my dataset

[
  {
    "id": 1,
    "interval": 1,
    "service": "Service 1",
    "value": 5
  },
  {
    "id": 2,
    "interval": 2,
    "service": "Service 1",
    "value": 15
  },
  {
    "id": 3,
    "interval": 1,
    "service": "Service 2",
    "value": 10
  },
  {
    "id": 4,
    "interval": 2,
    "service": "Service 2",
    "value": 5
  },

Body:
I have no idea about kendo charts but there is an error in your code.
You are assigning this.series = groupBy ..... but at that point stackedbarchartdata is still null therefore this.serie will always be null or empty.
You should move it inside the subscribe, have a look:

ngOnInit() {
  this.StackedBarChart.getMethod().subscribe((res: any) => {
    this.stackedbarchartdata = res;
    console.log(this.stackedbarchartdata);
    this.series = groupBy(this.stackedbarchartdata, [{ field: 'service' }]) as GroupResult[];
    console.log(this.series);
  });
}

and in the HTML:

<h1 *ngIf="!series">Loading...</h1>
<kendo-chart *ngIf="series" [style.height]="'90%'" [style.width]="'90%'">
  <kendo-chart-tooltip format='{0}%'></kendo-chart-tooltip>
  <kendo-chart-series>
    <kendo-chart-series-item *ngFor="let item of series"
                             [data]="item.items" [name]="item.value"
                             field="value" categoryField="interval"
                             type="column" stack="true">
    </kendo-chart-series-item>
  </kendo-chart-series>
</kendo-chart>

again I don't know nothing about kendo charts therefore there might be more errors but i hope this helps you