问:
How to debug injected javascript code in IE compatibility mode?
I need to inject some Javascript scripts to IE and then invoke some methods.

I tried the following simple C# code (the Javascript code is to build xpath from a known HTML element).

```<code>string xpath = @"
(function(win) {
    ""use strict"";
    var doc = win.document;

    if (doc._xpath_installed) return;
    doc._xpath_installed = true;

    doc.createXPath = function (node, optimized) {
        if (node.nodeType === Node.DOCUMENT_NODE) {
            return '/';
        }

        var steps = [];
        var contextNode = node;
        while (contextNode) {
            var step = _xPathValue(contextNode, optimized);
            if (!step) {
                break;
            }  // Error - bail out early.
            steps.push(step);
            if (step.optimized) {
                break;
            }
            contextNode = contextNode.parentNode;
        }

        steps.reverse();

        var stepvalues = [];
        steps.forEach(function (step) {
            stepvalues.push(_steptostring(step));
        });
        return (steps.length && steps[0].optimized ? '' : '/') + stepvalues.join('/');
    };

    var _xPathValue = function (node, optimized) {
        var ownValue;
        var ownIndex = _xPathIndex(node);
        if (ownIndex === -1) {
            return null;
        }  // Error.

        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                if (optimized && node.getAttribute('id')) {
                    return _stepnew('//*[@id=""' + node.getAttribute('id') + '""]', true);
                }
                ownValue = node.localName;
                break;
            case Node.ATTRIBUTE_NODE:
                ownValue = '@' + node.nodeName;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                ownValue = 'text()';
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                ownValue = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                ownValue = 'comment()';
                break;
            case Node.DOCUMENT_NODE:
                ownValue = '';
                break;
            default:
                ownValue = '';
                break;
        }

        if (ownIndex > 0) {
            ownValue += '[' + ownIndex + ']';
        }

        return _stepnew(ownValue, node.nodeType === Node.DOCUMENT_NODE);
    };

    var _xPathIndex = function (node) {
        // Returns -1 in case of error, 0 if no siblings matching the same expression,
        // <XPath index among the same expression-matching sibling nodes> otherwise.
        function areNodesSimilar(left, right) {
            if (left === right) {
                return true;
            }

            if (left.nodeType === Node.ELEMENT_NODE && right.nodeType === Node.ELEMENT_NODE) {
                return left.localName === right.localName;
            }

            if (left.nodeType === right.nodeType) {
                return true;
            }

            // XPath treats CDATA as text nodes.
            var leftType = left.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType;
            var rightType = right.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType;
            return leftType === rightType;
        }

        var siblings = node.parentNode ? node.parentNode.children : null;
        if (!siblings) {
            return 0;
        }  // Root node - no siblings.
        var hasSameNamedElements;
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
                hasSameNamedElements = true;
                break;
            }
        }
        if (!hasSameNamedElements) {
            return 0;
        }
        var ownIndex = 1;  // XPath indices start with 1.
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i])) {
                if (siblings[i] === node) {
                    return ownIndex;
                }
                ++ownIndex;
            }
        }
        return -1;
    };

    var _stepnew = function(value, optimized) {
        return {
            value: value,
            optimized: optimized || false
        }
    };

    var _steptostring = function(step) {
        return step[""value""];
    };
})(window);
";
</code>```

And then I try to inject the xpath string and invoke a method,

```<code>// doc is the html document (type: mshtml.IHTMLDocument2)
// element is the html element (type: mshtml.IHTMLElement)

doc.parentWindow.execScript(xpath, "JScript");

object[] args = new object[2];
args[0] = element;
args[1] = 1;
object result = doc.GetType().InvokeMember("createXPath", BindingFlags.Instance | BindingFlags.InvokeMethod, null, doc, args);
</code>```

It works fine in Internet Explorer 11 (Windows 10).

However, when I add the website to Compatibility View (settings-> compatibility view settings), the InvokeMember call throws exception "Exception from HRESULT: 0x80020101", which means there are some script errors in the Javascript code.

My question is, is there a way to debug into this Javascript code in the above situation? Without debugging it is almost impossible to find the root cause only based on the information 0x80020101.

答:
If you just want to debug code in Edge IE mode, you can use IEChooser to open Internet Explorer DevTools, as follows:

In Windows, open the Run dialog box. For example, press the Windows logo key + R.

Enter %systemroot%\system32\f12\IEChooser.exe, and then click OK.

In IEChooser, select the entry for the IE mode tab.

For more details, you could also refer to this doc: Open DevTools on a tab in IE mode.

Body:
I need to inject some Javascript scripts to IE and then invoke some methods.

I tried the following simple C# code (the Javascript code is to build xpath from a known HTML element).

string xpath = @"
(function(win) {
    ""use strict"";
    var doc = win.document;

    if (doc._xpath_installed) return;
    doc._xpath_installed = true;

    doc.createXPath = function (node, optimized) {
        if (node.nodeType === Node.DOCUMENT_NODE) {
            return '/';
        }

        var steps = [];
        var contextNode = node;
        while (contextNode) {
            var step = _xPathValue(contextNode, optimized);
            if (!step) {
                break;
            }  // Error - bail out early.
            steps.push(step);
            if (step.optimized) {
                break;
            }
            contextNode = contextNode.parentNode;
        }

        steps.reverse();

        var stepvalues = [];
        steps.forEach(function (step) {
            stepvalues.push(_steptostring(step));
        });
        return (steps.length && steps[0].optimized ? '' : '/') + stepvalues.join('/');
    };

    var _xPathValue = function (node, optimized) {
        var ownValue;
        var ownIndex = _xPathIndex(node);
        if (ownIndex === -1) {
            return null;
        }  // Error.

        switch (node.nodeType) {
            case Node.ELEMENT_NODE:
                if (optimized && node.getAttribute('id')) {
                    return _stepnew('//*[@id=""' + node.getAttribute('id') + '""]', true);
                }
                ownValue = node.localName;
                break;
            case Node.ATTRIBUTE_NODE:
                ownValue = '@' + node.nodeName;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                ownValue = 'text()';
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                ownValue = 'processing-instruction()';
                break;
            case Node.COMMENT_NODE:
                ownValue = 'comment()';
                break;
            case Node.DOCUMENT_NODE:
                ownValue = '';
                break;
            default:
                ownValue = '';
                break;
        }

        if (ownIndex > 0) {
            ownValue += '[' + ownIndex + ']';
        }

        return _stepnew(ownValue, node.nodeType === Node.DOCUMENT_NODE);
    };

    var _xPathIndex = function (node) {
        // Returns -1 in case of error, 0 if no siblings matching the same expression,
        // <XPath index among the same expression-matching sibling nodes> otherwise.
        function areNodesSimilar(left, right) {
            if (left === right) {
                return true;
            }

            if (left.nodeType === Node.ELEMENT_NODE && right.nodeType === Node.ELEMENT_NODE) {
                return left.localName === right.localName;
            }

            if (left.nodeType === right.nodeType) {
                return true;
            }

            // XPath treats CDATA as text nodes.
            var leftType = left.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : left.nodeType;
            var rightType = right.nodeType === Node.CDATA_SECTION_NODE ? Node.TEXT_NODE : right.nodeType;
            return leftType === rightType;
        }

        var siblings = node.parentNode ? node.parentNode.children : null;
        if (!siblings) {
            return 0;
        }  // Root node - no siblings.
        var hasSameNamedElements;
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i]) && siblings[i] !== node) {
                hasSameNamedElements = true;
                break;
            }
        }
        if (!hasSameNamedElements) {
            return 0;
        }
        var ownIndex = 1;  // XPath indices start with 1.
        for (var i = 0; i < siblings.length; ++i) {
            if (areNodesSimilar(node, siblings[i])) {
                if (siblings[i] === node) {
                    return ownIndex;
                }
                ++ownIndex;
            }
        }
        return -1;
    };

    var _stepnew = function(value, optimized) {
        return {
            value: value,
            optimized: optimized || false
        }
    };

    var _steptostring = function(step) {
        return step[""value""];
    };
})(window);
";

And then I try to inject the xpath string and invoke a method,

// doc is the html document (type: mshtml.IHTMLDocument2)
// element is the html element (type: mshtml.IHTMLElement)

doc.parentWindow.execScript(xpath, "JScript");

object[] args = new object[2];
args[0] = element;
args[1] = 1;
object result = doc.GetType().InvokeMember("createXPath", BindingFlags.Instance | BindingFlags.InvokeMethod, null, doc, args);

It works fine in Internet Explorer 11 (Windows 10).

However, when I add the website to Compatibility View (settings-> compatibility view settings), the InvokeMember call throws exception "Exception from HRESULT: 0x80020101", which means there are some script errors in the Javascript code.

My question is, is there a way to debug into this Javascript code in the above situation? Without debugging it is almost impossible to find the root cause only based on the information 0x80020101.


来源: stackexchange

问:
Assigning values to pointer types in a go struct
In an attempt to handle null values when trying to input a struct of data to a database row (using goqu) I've defined a struct similar to

```<code>type datain struct {
   id *float32 `db:"id"`
   tempr *float32 `db:"temperature"`
}
</code>```

and as these are all coming from strings I've made a function

```<code>func stringToFloat32(instr string) float32 {
    value, err := strconv.ParseFloat(instr, 32)
    if err != nil {
        log.Crit("error converting to float", "stringToFloat32", err)
    }
    return float32(value)
}
</code>```

to convert the strings to float32's... however when I try and use

```<code>var datastruct datain
*datastruct.id = stringToFloat32("1234.4")
</code>```

I get an error, invalid address or nil pointer dereference
which sort of makes sense to me.. but try as I might, I can't work out how to put a value in these structure fields if one exists.

I'm trying to use this mechanism to allow nulls when there is no value for one of the fields in the input csv string.

Maybe I'm doing this the hard way? I definitely have the syntax wrong somewhere.

Further digging.. seems I might need a new() function to assign a real variable to each pointer... Still can't help but feel this is doing things the hard way though.

答:
When you defined a datain variable without any initialization, the value of the id was nil, which means you couldn't de-reference it.

var datastruct datain
id := stringToFloat32("1234.4")
datastruct.id = &id
```

ContentLicense: CC BY-SA 4.0

Body:
In an attempt to handle null values when trying to input a struct of data to a database row (using goqu) I've defined a struct similar to

type datain struct {
   id *float32 `db:"id"`
   tempr *float32 `db:"temperature"`
}

and as these are all coming from strings I've made a function

func stringToFloat32(instr string) float32 {
    value, err := strconv.ParseFloat(instr, 32)
    if err != nil {
        log.Crit("error converting to float", "stringToFloat32", err)
    }
    return float32(value)
}

to convert the strings to float32's... however when I try and use

var datastruct datain
*datastruct.id = stringToFloat32("1234.4")

I get an error, invalid address or nil pointer dereference
which sort of makes sense to me.. but try as I might, I can't work out how to put a value in these structure fields if one exists.

I'm trying to use this mechanism to allow nulls when there is no value for one of the fields in the input csv string.

Maybe I'm doing this the hard way? I definitely have the syntax wrong somewhere.

Further digging.. seems I might need a new() function to assign a real variable to each pointer... Still can't help but feel this is doing things the hard way though.


问:
Vectorization using numpy
I translated this code from matlab.It is part of a larger body of code But I would like to get some advice on how to vectorize this section in order to make it faster. my major concern is with the for loops and if statements. If possible I would like to write it without using an if else statement. (Jax is not able to jit an if conditional). Thanks</p>
```<code>import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

print(par.shape)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

# First looping
k = 0
for i in range(num_rows):
    smf_1 = smf.copy()
    if  smf_1[i] == np.inf:

        par0_col[k] = par[i, 0]
        lb_col[k] = lb[i]
        ub_col[k] = ub[i]
        k = k+1

    else:
        par0_col[k:k+num_cols] = par[i, :num_cols]
        lb_col[k:k+num_cols] = lb[i]
        ub_col[k:k+num_cols] = ub[i]
        k = k+num_cols

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

# second looping
k = 0
for i in range(num_rows):
    smf_1 = smf.copy()
    if np.isinf(smf_1[i]):
        smf_1[i] = 0
        arr_1[i, :] = (par_log[k])
        arr_2[i, :] = 10**par_log[k]
        k = k+1

    else:
        arr_1[i, :] = par_log[k:k+num_cols]

        arr_2[i, :] = 10**par_log[k:k+num_cols]

        k = k+num_cols

# print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

</code>```

答:
This is challenging to fully vectorize, but I assume it is possible. Here is a start that removes the if/else logic for the first loop. The trick is precomputing the k values (smf_1 is trivial so I removed it):

```<code>num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))
# First looping
for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]
</code>```

Assume this same pattern should work for the second loop but didn't look too closely. If it is possible to fully vectorize this (i.e. remove the for loop), then this is the path forward as I understand it.

Title: Vectorization using numpy

Body:
I translated this code from matlab.It is part of a larger body of code But I would like to get some advice on how to vectorize this section in order to make it faster. my major concern is with the for loops and if statements. If possible I would like to write it without using an if else statement. (Jax is not able to jit an if conditional). Thanks

import numpy as np

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

print(par.shape)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))

# First looping
k = 0
for i in range(num_rows):
    smf_1 = smf.copy()
    if  smf_1[i] == np.inf:

        par0_col[k] = par[i, 0]
        lb_col[k] = lb[i]
        ub_col[k] = ub[i]
        k = k+1

    else:
        par0_col[k:k+num_cols] = par[i, :num_cols]
        lb_col[k:k+num_cols] = lb[i]
        ub_col[k:k+num_cols] = ub[i]
        k = k+num_cols

arr_1 = np.zeros(shape = (num_rows, num_cols))
arr_2 = np.zeros(shape = (num_rows, num_cols))

par_log = np.log10((par0_col - lb_col) / (1 - par0_col / ub_col))

# second looping
k = 0
for i in range(num_rows):
    smf_1 = smf.copy()
    if np.isinf(smf_1[i]):
        smf_1[i] = 0
        arr_1[i, :] = (par_log[k])
        arr_2[i, :] = 10**par_log[k]
        k = k+1

    else:
        arr_1[i, :] = par_log[k:k+num_cols]

        arr_2[i, :] = 10**par_log[k:k+num_cols]

        k = k+num_cols

# print(arr_1)

# [[0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.         0.         0.         0.         0.
#   0.         0.        ]
#  [0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361 0.37566361 0.37566361 0.37566361 0.37566361
#   0.37566361 0.37566361]
#  [0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996 0.61729996 0.61729996 0.61729996 0.61729996
#   0.61729996 0.61729996]
#  [0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336 0.81291336 0.81291336 0.81291336 0.81291336
#   0.81291336 0.81291336]
#  [0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608 0.99122608 0.99122608 0.99122608 0.99122608
#   0.99122608 0.99122608]]

Body:
This is challenging to fully vectorize, but I assume it is possible. Here is a start that removes the if/else logic for the first loop. The trick is precomputing the k values (smf_1 is trivial so I removed it):

num_rows = 5
num_cols = 20
smf = np.array([np.inf, 0.1, 0.1, 0.1, 0.1])
par_init = np.array([1,2,3,4,5])
lb = np.array([0.1, 0.1, 0.1, 0.1, 0.1])
ub = np.array([10, 10, 10, 10, 10])
par = np.broadcast_to(par_init[:,None],(num_rows,num_cols))

kvals = np.where(np.isinf(smf), 1, num_cols)
kvals = np.insert(kvals, 0, 0)
kvals = np.cumsum(kvals)

par0_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
lb_col = np.zeros(num_rows*num_cols - (num_cols-1) * np.sum(np.isinf(smf)))
ub_col = np.zeros(num_rows*num_cols- (num_cols-1) * np.sum(np.isinf(smf)))
# First looping
for i in range(num_rows):
    par0_col[kvals[i]:kvals[i+1]] = par[i, :kvals[i+1]-kvals[i]]
    lb_col[kvals[i]:kvals[i+1]] = lb[i]
    ub_col[kvals[i]:kvals[i+1]] = ub[i]

Assume this same pattern should work for the second loop but didn't look too closely. If it is possible to fully vectorize this (i.e. remove the for loop), then this is the path forward as I understand it.


问:
sending mail from Batch file
We have a script to backup files. After the backup operation is over, we would like to send a report as an email notification to some of our email addresses.

How could this be done?

答:
We use blat to do this all the time in our environment.  I use it as well to connect to Gmail with Stunnel.  Here's the params to send a file

```<code>blat -to user@example.com -server smtp.example.com -f batch_script@example.com -subject "subject" -body "body" -attach c:\temp\file.txt
</code>```

Or you can put that file in as the body

```<code>blat c:\temp\file.txt -to user@example.com -server smtp.example.com -f batch_script@example.com -subject "subject"
</code>```

ContentLicense: CC BY-SA 2.5

Title: sending mail from Batch file

LastEditorDisplayName: divo

Body:
We use blat to do this all the time in our environment.  I use it as well to connect to Gmail with Stunnel.  Here's the params to send a file

blat -to user@example.com -server smtp.example.com -f batch_script@example.com -subject "subject" -body "body" -attach c:\temp\file.txt

Or you can put that file in as the body

blat c:\temp\file.txt -to user@example.com -server smtp.example.com -f batch_script@example.com -subject "subject"

OwnerDisplayName: Keng


问:
Dynamically get difference between DateTime.Now and a model DateTime in Razor pages
I'm using c# .NET razor pages and trying to dynamically change the 'minutes ago' count.

Basically, I have this code:

```<code>@foreach(var comment in Model.Comments)
            {
                TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
                int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);

                <div>
                    <p>@comment.Message</p>
                    <span>@minutesAgo minutes ago</span>
                </div>
            }
</code>```

The calculation works, but it stays static on the page.
I'm trying to get it updated as long the user stays on the page.

答:
The calculation works, but it stays static on the page.

The fastest way is you can use js to aoto refresh the page to make the time update.

```<code>@foreach(var comment in Model.Comments)
{
       TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
       int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);
       <div>
            <p>@comment.Message</p>
            <span>@minutesAgo minutes ago</span>
       </div>
}
@section Scripts
{

    <script type="text/javascript">
        //recall the page every one minute.....
        window.setTimeout(function () {
            window.location.href = "/Index";   //the href depend on yourself...
        //or just reload the page...
        //window.location.reload();
        }, 1000*60);
    </script>
}
</code>```

Body:
I'm using c# .NET razor pages and trying to dynamically change the 'minutes ago' count.

Basically, I have this code:

@foreach(var comment in Model.Comments)
            {
                TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
                int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);

@comment.Message

                    @minutesAgo minutes ago

            }

The calculation works, but it stays static on the page.
I'm trying to get it updated as long the user stays on the page.

Body:
The calculation works, but it stays static on the page.

The fastest way is you can use js to aoto refresh the page to make the time update.

@foreach(var comment in Model.Comments)
{
       TimeSpan timeSpan = (DateTime.Now - comment.CommentDate);
       int minutesAgo = Convert.ToInt32(timeSpan.TotalMinutes);
       <div>
            <p>@comment.Message</p>
            <span>@minutesAgo minutes ago</span>
       </div>
}
@section Scripts
{

    <script type="text/javascript">
        //recall the page every one minute.....
        window.setTimeout(function () {
            window.location.href = "/Index";   //the href depend on yourself...
        //or just reload the page...
        //window.location.reload();
        }, 1000*60);
    </script>
}


问:
Amplify ssl certificate is expired - how to renew
I had my website hosted in amplify for 2 years. I had everything working perfectly but now suddenly the certificate is expired. According to amazon it should renew automatically but it is not happening...

I have tried to reach amazon to fix the issue but they charge you to open a case about the mistakes they do so I have no idea how to fix it...

Any idea?

答:
In my case, I have cleaned up some of my DNS records for the domain, and apparently some of them is for AWS ACM domain verification, and the renewal failed.

What worked for me was to remove the domain in Amplify and add it again.


问:
Find Average Score to Date
I have a student table as below;

```<code>CREATE TABLE exam_scores
(
 student_id text,
 exam_date date,
 exam_score int
 );

insert into exam_scores
Values
('a001','2018-03-29',75),
('a001','2018-04-25',89),
('b002','2018-02-24',91);
</code>```

I am trying to create a view such as;

student_id
exam_date
max_score_to_date
avg_score_to_date
max_score_ever

a001
2018-03-29
75
75
89

a001
2018-04-25
89
82
89

b002
2018-02-24
91
91
91

I can calculate all aggregated columns except "avg_score_to_date". I have my query below. Can you please help me modify my code, so it works correctly to calculate the average score to date?

```<code>SELECT
     student_id
    ,exam_date
    ,MAX(exam_score) OVER(Partition by student_id,exam_date) AS max_score_to_date
    ,AVG(exam_score) OVER(Partition by student_id,exam_date) avg_score_to_date
    ,MAX(exam_score) OVER(Partition by student_id) AS max_score_ever
 FROM exam_scores
</code>```

Thank you!

答:
you just need to do the group by student and add order by exam_date.

```<code>    SELECT
         student_id
        ,exam_date
        ,MAX(exam_score) OVER(Partition by student_id,exam_date) AS max_score_to_date
        ,AVG(exam_score) OVER(Partition by student_id order by exam_date) avg_score_to_date
        ,MAX(exam_score) OVER(Partition by student_id) AS max_score_ever
     FROM exam_scores;
</code>```

Title: Find Average Score to Date

Body:
I have a student table as below;

CREATE TABLE exam_scores
(
 student_id text,
 exam_date date,
 exam_score int
 );

insert into exam_scores
Values
('a001','2018-03-29',75),
('a001','2018-04-25',89),
('b002','2018-02-24',91);

I am trying to create a view such as;

student_id
exam_date
max_score_to_date
avg_score_to_date
max_score_ever

a001
2018-03-29
75
75
89

a001
2018-04-25
89
82
89

b002
2018-02-24
91
91
91

I can calculate all aggregated columns except "avg_score_to_date". I have my query below. Can you please help me modify my code, so it works correctly to calculate the average score to date?

SELECT
     student_id
    ,exam_date
    ,MAX(exam_score) OVER(Partition by student_id,exam_date) AS max_score_to_date
    ,AVG(exam_score) OVER(Partition by student_id,exam_date) avg_score_to_date
    ,MAX(exam_score) OVER(Partition by student_id) AS max_score_ever
 FROM exam_scores

Thank you!

Body:
you just need to do the group by student and add order by exam_date.

    SELECT
         student_id
        ,exam_date
        ,MAX(exam_score) OVER(Partition by student_id,exam_date) AS max_score_to_date
        ,AVG(exam_score) OVER(Partition by student_id order by exam_date) avg_score_to_date
        ,MAX(exam_score) OVER(Partition by student_id) AS max_score_ever
     FROM exam_scores;


问:
Uncaught TypeError: (0 , react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a function (React.js)
I use React Router Version 6 then I ran this code below:

import { useHistory } from 'react-router-dom'

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();
```

But I got this error:

Uncaught TypeError: (0 ,
react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a
function

Are there any mistakes for my code?

答:
For React Router Version 6, use "useNavigate" instead of "useHistory" which is React Router Version 5.

So replace your code (React Router Version 5):

import { useHistory } from 'react-router-dom'

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();
```
<p>With this code (<strong>React Router Version 6</strong>):</p>
<pre class="lang-js prettyprint-override"><code>import { useNavigate } from 'react-router-dom'

function Test() {
  const navigate = useNavigate();
  navigate('/');                    // Equivalent to "history.push('/');"
  navigate('/', { replace: true }); // Equivalent to "history.replace('/');"
  navigate(-1);                     // Equivalent to "history.goBack();"
}

Test();
</code>```

Body:
I use React Router Version 6 then I ran this code below:

import { useHistory } from 'react-router-dom'

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

But I got this error:

Uncaught TypeError: (0 ,
react_router_dom__WEBPACK_IMPORTED_MODULE_2__.useHistory) is not a
function

Are there any mistakes for my code?

Body:
For React Router Version 6, use "useNavigate" instead of "useHistory" which is React Router Version 5.

So replace your code (React Router Version 5):

import { useHistory } from 'react-router-dom'

function Test() {
  const history = useHistory();
  history.push('/');
  history.replace('/');
  history.goBack();
}

Test();

With this code (React Router Version 6):

import { useNavigate } from 'react-router-dom'

function Test() {
  const navigate = useNavigate();
  navigate('/');                    // Equivalent to "history.push('/');"
  navigate('/', { replace: true }); // Equivalent to "history.replace('/');"
  navigate(-1);                     // Equivalent to "history.goBack();"
}

Test();


问:
Is it possible to create a Bag of Words but word char or substrings?
Is it possible to create a BoW but instead of searching for words I do it for substrings?

I'm working on a python program were I input an array with various names (instead of full sentences) on it and try to apply BoW on it and the problem is that because BoW is for words in sentences the program treats them as sentences.

Example:
If I have the word Farahoka, Csanoha, April, Bas, Phrahonee and I'm looking for the substring aho

How could I do this?

Edit:
It seems that my question is not that clear, so I'll try to do my best to explain what is the task and what I need to do.

I have a list of various names on an array, and I'm trying to find a way to vectorize the letters or maybe find a way to separate into syllabes.

Example:

In BoW if I have The sky is blue today it will be separated into [The, sky, is, blue, today], in the problem I have I'm trying to do something similar, separate/find substrings for words.

Using the previous example, I want to take the word todayand search for the substring ay

Is it possible to do it without using things like if 'ay' in today or endswith('ay')?

In theory I need to use an unigram model for this in order to learn wights for a predictor but it seems all I can find online is focused on words and not substrings.

答:
Your best bet is to iterate over each word and check if your substring is in that word.

substring = 'aho'
words = ['Farahoka', 'Csanoha', 'April', 'Bas', 'Phrahonee']

for word in words:
    if substring in word:
        print(f'{substring} in {word}')
    else:
        print(f'{substring} not found in {word}')
```


问:
Allow CodeBuildAction to update SSM parameter
I'm currently trying to set an SSM Parameter Store value via a CodeBuildAction. My first attempt resulted in a 254 return code, which I'm guessing is because the request was not authorized. I then attempted to attach a managed policy to the role associated with the CodeBuildAction, but the cdk deploy failed with:

```<code>Policy arn:aws:iam::aws:policy/AWSServiceRoleForAmazonSSM does not exist or is not attachable. (Service: AmazonIdentityManagement; Status Code: 404; Error Code: NoSuchEntity; Request ID: 2f65f8db-64a5-4173-ac45-de4c56bffa44; Proxy: nu
ll)
</code>```

Here is the role setup:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
    ManagedPolicy.fromAwsManagedPolicyName("AWSServiceRoleForAmazonSSM"), // THIS IS THE NEW PART
  ],
});
```

I understand that this means that I'm using the wrong policy, but I'm struggling to find an alternative.

Is there a managed policy that will work here? If not, how would I set up an inline policy to achieve what I'm trying to do?

答:
I was able to get it to work with this:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
  ],
  inlinePolicies: {
    SSMPutItem: new PolicyDocument({
      statements: [
        new PolicyStatement({
          resources: ["*"],
          actions: ["ssm:*"],
          effect: Effect.ALLOW,
        }),
      ],
    }),
  },
});
```

It's probably way more relaxed than it needs to be, but this does solve the issue.

Body:
I'm currently trying to set an SSM Parameter Store value via a CodeBuildAction. My first attempt resulted in a 254 return code, which I'm guessing is because the request was not authorized. I then attempted to attach a managed policy to the role associated with the CodeBuildAction, but the cdk deploy failed with:

Policy arn:aws:iam::aws:policy/AWSServiceRoleForAmazonSSM does not exist or is not attachable. (Service: AmazonIdentityManagement; Status Code: 404; Error Code: NoSuchEntity; Request ID: 2f65f8db-64a5-4173-ac45-de4c56bffa44; Proxy: nu
ll)

Here is the role setup:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
    ManagedPolicy.fromAwsManagedPolicyName("AWSServiceRoleForAmazonSSM"), // THIS IS THE NEW PART
  ],
});

I understand that this means that I'm using the wrong policy, but I'm struggling to find an alternative.

Is there a managed policy that will work here? If not, how would I set up an inline policy to achieve what I'm trying to do?

Body:
I was able to get it to work with this:

this.codeBuildRole = new Role(this, "application-build-project-role", {
  assumedBy: new ServicePrincipal("codebuild.amazonaws.com"),
  managedPolicies: [
    ManagedPolicy.fromAwsManagedPolicyName(
      "AmazonEC2ContainerRegistryPowerUser"
    ),
  ],
  inlinePolicies: {
    SSMPutItem: new PolicyDocument({
      statements: [
        new PolicyStatement({
          resources: ["*"],
          actions: ["ssm:*"],
          effect: Effect.ALLOW,
        }),
      ],
    }),
  },
});

It's probably way more relaxed than it needs to be, but this does solve the issue.


问:
what is the regex pattern for a regex pattern?
What is the regex pattern for a regex pattern? I am using Ruby version 1.8.7, and have a requirement to determine if a given string is a regex pattern. What is the best pattern to use to determine this?

Thanks,
Anand

答:
Assuming the regex pattern is a string with two forward slashes, / defining the pattern, then the regex to find a pattern with two foward slashes at the beginning and end of a pattern is as following:

(\/(?:.)*\/(?:i|g|s|m|U)*)

ContentLicense: CC BY-SA 3.0


问:
Flutter TextFormField: The keyboard appeared and instantly disappeared
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.</p>
```<code>final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}
</code>```

答:
I've modified a bit of your code, and the keyboard is working fine. Maybe you can give it a try or compare with your code so you find the cause. Here is the full code</p>
```<code>import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  String? _account;
  Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: const TextStyle(fontSize: 15),
        decoration: const InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }

  // @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[_showAccountInput()],
        ),
      ),
    );
  }
}
</code>```

Body:
When I click the TextFormField, the keyboard appears, then it disappears instantly, just like blinking. I wonder that whether it is because the lacking of some parameters? Or some other problems? Thanks.
Here are my relative codes.

final _formKey = GlobalKey<FormState>();
String? _account;
Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: TextStyle(fontSize: 15),
        decoration: new InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: new AppBar(
        title: new Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            _showAccountInput()

          ],
        ),
      ),
    );
  }
}

Body:
I've modified a bit of your code, and the keyboard is working fine. Maybe you can give it a try or compare with your code so you find the cause. Here is the full code

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _formKey = GlobalKey<FormState>();
  String? _account;
  Widget _showAccountInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 0.0, 0.0),
      child: TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        style: const TextStyle(fontSize: 15),
        decoration: const InputDecoration(
            border: InputBorder.none,
            hintText: 'input',
            icon: Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        onSaved: (value) => _account = value?.trim(),
      ),
    );
  }

  // @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Second Screen"),
      ),
      body: Form(
        key: _formKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[_showAccountInput()],
        ),
      ),
    );
  }
}


问:
How do I give Android apps access to the Hexagon DSP
I'm trying to run some Android apps of mine on the Hexagon DSP on a Google Pixel. However, access to the DSP is being restricted. Using the AOSP source is it possible to modify the policy of whether Android programs can run on the Hexagon DSP? Using, e.g., SEL policies? The Android docs state that some OEMs (in particular for the Pixel) restrict access to the Hexagon DSP. Is this something decided in the proprietary binaries or in some configurations in AOSP?</p>

答:
you should try this https://github.com/geohot/freethedsp if your still interested. It should let you bypass the signature checks, Definitely read the source for more info, you'll have to edit the addresses in the code for the patch to work on your specific phone, but it should work. also thank you to geohot!

forgot to mention, i think i read somewhere that selinux policys on the newer versions of android only let certain apps access dsp remote procedure calls but you can fix that if your root or using AOSP.


问:
phpredis errors Class Redis not found in Linux
I met a weied problem when installing phpredis by

```<code>cd phpredis && ./configure && make && make install
</code>```

after that, I add

```<code>extension=redis.so
</code>```

into php.ini.

I can get an OK by running

```<code>php -r "if (new Redis() == true){ echo \"\r\n OK \r\n\"; }"
</code>```

BUT when running http:127.0.0.1, nginx throw a error " Fatal error: Class 'Redis' not found in index.php"

```<code><?php>
    $client = new Redis();
<?>
</code>```

I guess this may be some problems related with environment...

Thanks for any advice!

答:
If you're using composer and get the error "Class Redis not found" try put a backslash before the name class. Like this:</p>
```<code><?php
    $client = new \Redis();
<?
</code>```

Body:
I met a weied problem when installing phpredis by

cd phpredis && ./configure && make && make install

after that, I add

extension=redis.so

into php.ini.

I can get an OK by running

php -r "if (new Redis() == true){ echo \"\r\n OK \r\n\"; }"

BUT when running http:127.0.0.1, nginx throw a error " Fatal error: Class 'Redis' not found in index.php"

<?php>
    $client = new Redis();
<?>

I guess this may be some problems related with environment...

Thanks for any advice!

Body:
If you're using composer and get the error "Class Redis not found" try put a backslash before the name class. Like this:

<?php
    $client = new \Redis();
<?


问:
Python SMTP library can't handle IPv6
How can i add IPv6 option on SMTP library please ?

When i try to connect to SMTP using IPv6 i got this error :

```<code> smtpserver = smtplib.SMTP("smtp.gmail.com", 587, source_address=('2a00:xxxx:5::1e7', 80, 0, 0))
</code>```

Error : TypeError: AF_INET address must be a pair (host, port)

Which means smtplib.py doesn't support IPv6

I found an article about that "https://bugs.python.org/issue3461" . I tried to add the patch into my smtplib.py but it didn't work

Can anyone please help me to do this ?

答:
Python 3's socket.create_connection obtains the first DNS resolution entry of the target address that is connectable (and this is a behaviour that is documented in Python as unstable by the DNS design).

https://github.com/python/cpython/blob/fdcb675e/Lib/socket.py#L824

The CPython implementation _socket.connect throws the error in question on seeing a mismatch between the socket's address family at create time and the address family at another time,

https://github.com/python/cpython/blob/1aa6be0/Modules/socketmodule.c#L1807

Looking closer at socket.create_connection, I guess the source_address parameter cannot control the address family to use for the target.  The socket object sock is created in create_connection with the address family of the resolved target address.  Then source_address is used to specify the object's source with a call to sock.bind(source_address).  It appears that at this point, if the resolved target was IPv4 but source_address was IPv6, the error is thrown?

As a possible fix that would not monkey-patch socket.create_connection, I can imagine that instead of providing a symbolic host name in the target address, the caller resolves the host name first to an A or an AAAA entry, depending on the desired family.  The caller supplies the numeric recod as the target address.  The source address's family should be in accord with the desired family, too.

In other words, the caller can use socket.getaddrinfo to find the required target address by the desired family.  Other callers such as users of the request library can hot-wire socket.create_connection with the same idea.

https://docs.python.org/3/library/socket.html#socket.getaddrinfo

Title: Python SMTP library can't handle IPv6

Body:
How can i add IPv6 option on SMTP library please ?

When i try to connect to SMTP using IPv6 i got this error :

 smtpserver = smtplib.SMTP("smtp.gmail.com", 587, source_address=('2a00:xxxx:5::1e7', 80, 0, 0))

Error : TypeError: AF_INET address must be a pair (host, port)

Which means smtplib.py doesn't support IPv6

I found an article about that "https://bugs.python.org/issue3461" . I tried to add the patch into my smtplib.py but it didn't work

Can anyone please help me to do this ?


问:
How do I use already existing unique identifies in Airtable?
I have an Air-table base with the following information:

```<code>Company     ID

  A         123
  B         456
  C         789
</code>```

My question is how do I make the ID field into the record ID? Because, the issue I am having right now is that Air-table is automatically putting a Record ID field for a unique Identifier. I want the unique identifier to be my already existing ID field. But, I have not been able to get the functionality I want without completely overwriting the ID field. Does anyone have any idea how to go about this?

答:
map it

```<code>let recs=new Map(query.records.map(r=>[r.getCellValue('ID'),r.id]))
</code>```

(or, getCellValueAsString..)

thus, recs.get('123') returns record id (string like 'rec3Hj343cddk')

rec.has('456') - boolean to check existing or filter

if it doesn't fit your needs, then Dominik is right - you need to rethink your goal.

Body:
I have an Air-table base with the following information:

Company     ID

  A         123
  B         456
  C         789

My question is how do I make the ID field into the record ID? Because, the issue I am having right now is that Air-table is automatically putting a Record ID field for a unique Identifier. I want the unique identifier to be my already existing ID field. But, I have not been able to get the functionality I want without completely overwriting the ID field. Does anyone have any idea how to go about this?

Body:
map it

let recs=new Map(query.records.map(r=>[r.getCellValue('ID'),r.id]))

(or, getCellValueAsString..)

thus, recs.get('123') returns record id (string like 'rec3Hj343cddk')

rec.has('456') - boolean to check existing or filter

if it doesn't fit your needs, then Dominik is right - you need to rethink your goal.


问:
int a[] = {1,2,}; Why is a trailing comma in an initializer-list allowed?
Maybe I am not from this planet, but it would seem to me that the following should be a syntax error:

```<code>int a[] = {1,2,}; //extra comma in the end
</code>```

But it's not. I was surprised when this code compiled on Visual Studio, but I have learnt not to trust MSVC compiler as far as C++ rules are concerned, so I checked the standard and it is allowed by the standard as well. You can see 8.5.1 for the grammar rules if you don't believe me.

Why is this allowed? This may be a stupid useless question but I want you to understand why I am asking. If it were a sub-case of a general grammar rule, I would understand - they decided not to make the general grammar any more difficult just to disallow a redundant comma at the end of an initializer list. But no, the additional comma is explicitly allowed. For example, it isn't allowed to have a redundant comma in the end of a function-call argument list (when the function takes ...), which is normal.

So, again, is there any particular reason this redundant comma is explicitly allowed?

Body:
Maybe I am not from this planet, but it would seem to me that the following should be a syntax error:

int a[] = {1,2,}; //extra comma in the end

But it's not. I was surprised when this code compiled on Visual Studio, but I have learnt not to trust MSVC compiler as far as C++ rules are concerned, so I checked the standard and it is allowed by the standard as well. You can see 8.5.1 for the grammar rules if you don't believe me.

Why is this allowed? This may be a stupid useless question but I want you to understand why I am asking. If it were a sub-case of a general grammar rule, I would understand - they decided not to make the general grammar any more difficult just to disallow a redundant comma at the end of an initializer list. But no, the additional comma is explicitly allowed. For example, it isn't allowed to have a redundant comma in the end of a function-call argument list (when the function takes ...), which is normal.

So, again, is there any particular reason this redundant comma is explicitly allowed?

Body: <p>If you use an array without specified length,VC++6.0 can automaticly identify its length,so if you use "int a[]={1,2,};"the length of a is 3,but the last one hasn't been initialized,you can use "cout<


问:
Combine multiple sed commands into one
I have a file example.txt, I want to delete and replace fields in it.

The following commands are good, but in a very messy way, unfortunately I'm a rookie to sed command.

The commands I used:

sed 's/\-I\.\.\/\.\.\/\.\.//\n/g' example.txt > example.txt1

sed 's/\-I/\n/g' example.txt1 > example.txt2

sed '/^[[:space:]]*$/d' > example.txt2 example.txt3

sed 's/\.\.\/\.\.\/\.\.//g' > example.txt3 example.txt

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

```<code>Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App
</code>```

The file looks like this:

```<code>-I../../../Common/Component -I../../../Common/Component1 -I../../../Common/Component2 -I../../../Common/Component3 -I../../../Common/Component4 -I../../../Common/Component5 -I../../../Common/Component6 -IComp  -IApp  ../../../
</code>```

I want to know how the best way to transform input format to output format standard text-processing tool with 1 call with sed tool or awk.

答:
With your shown samples, please try following awk code. Written and tested in GNU awk.

```<code>awk -v RS='-I\\S+' 'RT{sub(/^-I.*Common\//,"Common/Components/",RT);sub(/^-I/,"",RT);print RT}' Input_file
</code>```

output with samples will be as follows:

```<code>Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App
</code>```

Explanation: Simple explanation would be, in GNU awk. Setting RS(record separator) as -I\\S+ -I till a space comes. In main awk program, check if RT is NOT NULL, substitute starting -I till Common with Common/Components/ in RT and then substitute starting -I with NULL in RT. Then printing RT here.

Title: Combine multiple sed commands into one

Body:
I have a file example.txt, I want to delete and replace fields in it.

The following commands are good, but in a very messy way, unfortunately I'm a rookie to sed command.

The commands I used:

sed 's/\-I\.\.\/\.\.\/\.\.//\n/g' example.txt > example.txt1

sed 's/\-I/\n/g' example.txt1 > example.txt2

sed '/^[[:space:]]*$/d' > example.txt2 example.txt3

sed 's/\.\.\/\.\.\/\.\.//g' > example.txt3 example.txt

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App

The file looks like this:

-I../../../Common/Component -I../../../Common/Component1 -I../../../Common/Component2 -I../../../Common/Component3 -I../../../Common/Component4 -I../../../Common/Component5 -I../../../Common/Component6 -IComp  -IApp  ../../../

I want to know how the best way to transform input format to output format standard text-processing tool with 1 call with sed tool or awk.

Body:
With your shown samples, please try following awk code. Written and tested in GNU awk.

awk -v RS='-I\\S+' 'RT{sub(/^-I.*Common\//,"Common/Components/",RT);sub(/^-I/,"",RT);print RT}' Input_file

output with samples will be as follows:

Common/Components/Component
Common/Components/Component1
Common/Components/Component2
Common/Components/Component3
Common/Components/Component4
Common/Components/Component5
Common/Components/Component6
Comp
App

Explanation: Simple explanation would be, in GNU awk. Setting RS(record separator) as -I\\S+ -I till a space comes. In main awk program, check if RT is NOT NULL, substitute starting -I till Common with Common/Components/ in RT and then substitute starting -I with NULL in RT. Then printing RT here.


问:
Copying List in Setter makes XML Unmarshaller not work
I have a DataBean like this:

```<code>@XmlRootElement
public class DataBean {
    private List<String> data;

    @XmlElement(name = "data")
    public List<String> getData() {
        return data != null ? Collections.unmodifiableList(data) : null;
    }

    public void setData(List<String> data) {
        data = new ArrayList<>(data);
        data.sort(Comparator.naturalOrder());
        this.data = data;
    }
}
</code>```

Inside of the DataBean, the list must be sorted, otherwise the DataBean is not usable in my domain. In order to avoid side effects, I copy the list in the setter and then sort it.

Marshalling this bean works fine, but when unmarshalling, the data list is empty (not null). Here is some code to demonstrate:

```<code>public class XmlTester {

    public static void main(String[] args) {
        List<String> data = Arrays.asList("one", "two", "three", "four");
        DataBean dataBean = new DataBean();
        dataBean.setData(data);
        System.out.printf("Data in original bean: %s%n%n", dataBean.getData().toString());

        try {
            String xmlString = serialize(dataBean);
            System.out.printf("XML:%n%s%n", xmlString);
            DataBean deserializedDataBean = deserialize(xmlString);
            System.out.printf("Data in deserialized bean: %s%n%n", deserializedDataBean.getData().toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    private static String serialize(DataBean dataBean) throws JAXBException {
        StringWriter w = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(DataBean.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(dataBean, w);
        return w.toString();
    }

    private static DataBean deserialize(String xmlString) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(DataBean.class);
        Unmarshaller um = context.createUnmarshaller();
        return (DataBean) um.unmarshal(new StringReader(xmlString));
    }
}
</code>```

This produces the following output:

```<code>Data in original bean: [four, one, three, two]

XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataBean>
    <data>four</data>
    <data>one</data>
    <data>three</data>
    <data>two</data>
</dataBean>

Data in deserialized bean: []
</code>```

If I remove the line data = new ArrayList<>(data); from the setter in the bean, unmarshalling works like a charm, so the copy operation seems to be the problem.

Why does copying make the list in the deserialized bean empty, and can I fix this without removing the copy operation?

Of course I could instead test if the data is sorted and throw an IllegalArgumentException if it isn't, but I would prefer to sort a copy in the setter.

答:
```<code>@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class DataBean {

    @XmlElement(name = "data")
    private List<String> data;

    public List<String> getData() {
        return data != null ? Collections.unmodifiableList(data) : null;
    }

    public void setData(List<String> data) {
        data = new ArrayList<>(data);
        data.sort(Comparator.naturalOrder());
        this.data = data;
    }
}
</code>```
```<code>Data in original bean: [four, one, three, two]

XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataBean>
    <data>four</data>
    <data>one</data>
    <data>three</data>
    <data>two</data>
</dataBean>

Data in deserialized bean: [four, one, three, two]
</code>```

Body:
I have a DataBean like this:

@XmlRootElement
public class DataBean {
    private List<String> data;

    @XmlElement(name = "data")
    public List<String> getData() {
        return data != null ? Collections.unmodifiableList(data) : null;
    }

    public void setData(List<String> data) {
        data = new ArrayList<>(data);
        data.sort(Comparator.naturalOrder());
        this.data = data;
    }
}

Inside of the DataBean, the list must be sorted, otherwise the DataBean is not usable in my domain. In order to avoid side effects, I copy the list in the setter and then sort it.

Marshalling this bean works fine, but when unmarshalling, the data list is empty (not null). Here is some code to demonstrate:

public class XmlTester {

    public static void main(String[] args) {
        List<String> data = Arrays.asList("one", "two", "three", "four");
        DataBean dataBean = new DataBean();
        dataBean.setData(data);
        System.out.printf("Data in original bean: %s%n%n", dataBean.getData().toString());

        try {
            String xmlString = serialize(dataBean);
            System.out.printf("XML:%n%s%n", xmlString);
            DataBean deserializedDataBean = deserialize(xmlString);
            System.out.printf("Data in deserialized bean: %s%n%n", deserializedDataBean.getData().toString());
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    private static String serialize(DataBean dataBean) throws JAXBException {
        StringWriter w = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(DataBean.class);
        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.marshal(dataBean, w);
        return w.toString();
    }

    private static DataBean deserialize(String xmlString) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(DataBean.class);
        Unmarshaller um = context.createUnmarshaller();
        return (DataBean) um.unmarshal(new StringReader(xmlString));
    }
}

This produces the following output:

Data in original bean: [four, one, three, two]

XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataBean>
    <data>four</data>
    <data>one</data>
    <data>three</data>
    <data>two</data>
</dataBean>

Data in deserialized bean: []

If I remove the line data = new ArrayList<>(data); from the setter in the bean, unmarshalling works like a charm, so the copy operation seems to be the problem.

Why does copying make the list in the deserialized bean empty, and can I fix this without removing the copy operation?

Of course I could instead test if the data is sorted and throw an IllegalArgumentException if it isn't, but I would prefer to sort a copy in the setter.

Body:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class DataBean {

    @XmlElement(name = "data")
    private List<String> data;

    public List<String> getData() {
        return data != null ? Collections.unmodifiableList(data) : null;
    }

    public void setData(List<String> data) {
        data = new ArrayList<>(data);
        data.sort(Comparator.naturalOrder());
        this.data = data;
    }
}

Data in original bean: [four, one, three, two]

XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<dataBean>
    <data>four</data>
    <data>one</data>
    <data>three</data>
    <data>two</data>
</dataBean>

Data in deserialized bean: [four, one, three, two]


问:
How do I add space between two images with headers and paragraphs using bootstrap?
I am replicating a portfolio from Codewell for practice and I can't seem to create space between the images without the images stretching and the text disappearing. I've tried using display: flex and justify-content: space-between and it stretches the images instead.

Here is a link to the portfolio for reference: https://www.codewell.cc/challenges/web-developer-portfolio--617d4897a383e41090a3e46f

Here is my code:

.web-div {
  display: flex;
  justify-content: space-between;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<div class="container">
  <div class="row">
    <div class="col-lg-6 web-div">
      <img src="Assets/Spense.png" alt="Spense Image">
      <h2>Spence.com <i class="fi fi-rr-arrow-right"></i></h2>
      <p>Rethinking the way writers get paid, an open-source platform designed to help writers focus more on writing, and less when and how they'll get paid. Project in collaboration with Codewell.cc</p>
    </div>
    <div class="col-lg-6 web-div">
      <img src="Assets/YelpCamp.png" alt="Yelp Camp">
      <h2>YelpCamp.com <i class="fi fi-rr-arrow-right"></i></h2>
      <p>Allowing backpack travelers to perfectly plan their trip through an open-source platform similar to TripAdvisor. With over 1m MAU, YelpCamp has been the crowd's favorite in 2021.</p>
    </div>
  </div>
</div></code>```

答:
If you are using BS5 then you should follow this:
https://getbootstrap.com/docs/5.0/utilities/spacing/</p>

Body:
I am replicating a portfolio from Codewell for practice and I can't seem to create space between the images without the images stretching and the text disappearing. I've tried using display: flex and justify-content: space-between and it stretches the images instead.

Here is a link to the portfolio for reference: https://www.codewell.cc/challenges/web-developer-portfolio--617d4897a383e41090a3e46f

Here is my code:

.web-div {
  display: flex;
  justify-content: space-between;
}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

Spence.com

Rethinking the way writers get paid, an open-source platform designed to help writers focus more on writing, and less when and how they'll get paid. Project in collaboration with Codewell.cc

YelpCamp.com

Allowing backpack travelers to perfectly plan their trip through an open-source platform similar to TripAdvisor. With over 1m MAU, YelpCamp has been the crowd's favorite in 2021.


问:
Type error using useNewUrlParser with mongoose in TypeScript
I'm doing the following:

```<code>// Connect to MongoDB
mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useCreateIndex: true }).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})
</code>```

and I'm getting the following error from WebStorm TypeScript service (running TSLint manually works fine):

TS2345: Argument of type '{ useNewUrlParser: boolean; useCreateIndex:
boolean; }' is not assignable to parameter of type '(err: MongoError)
=> void'.   Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type '(err: MongoError) => void'.

This seems to be an issue with @types/mongoose, but I've looked everywhere and I can't find where it's coming from.

Here is a workaround which does not really explain the issue:

```<code>    mongoose.set('useNewUrlParser', true)
    mongoose.set('useCreateIndex', true)
    mongoose.connect(MONGODB_URI).then(...
</code>```

Edit: mongoose 6 no longer need these options.

答:
These options are no longer necessary; hence why they aren't even in the type definitions. See the docs here: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options</p>
```<code>// Connect to MongoDB
mongoose.connect(MONGODB_URI).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})
</code>```

Body:
I'm doing the following:

// Connect to MongoDB
mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useCreateIndex: true }).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})

and I'm getting the following error from WebStorm TypeScript service (running TSLint manually works fine):

TS2345: Argument of type '{ useNewUrlParser: boolean; useCreateIndex:
boolean; }' is not assignable to parameter of type '(err: MongoError)
=> void'.   Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type '(err: MongoError) => void'.

This seems to be an issue with @types/mongoose, but I've looked everywhere and I can't find where it's coming from.

Here is a workaround which does not really explain the issue:

    mongoose.set('useNewUrlParser', true)
    mongoose.set('useCreateIndex', true)
    mongoose.connect(MONGODB_URI).then(...

Edit: mongoose 6 no longer need these options.

Body:
These options are no longer necessary; hence why they aren't even in the type definitions. See the docs here: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options

// Connect to MongoDB
mongoose.connect(MONGODB_URI).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})


问:
org.openqa.selenium.NoSuchSessionException: Unable to find session with ID error testing with Behat/Mink and Selenium2Driver in docker container
I'm trying to test a Symfony3 web application with Behat/Mink and Selenium2Driver so that I can test Javascript functionallity too.

The application runs in a docker container, so I added a new docker container for selenium-hub and chrome as described here:

# docker-compose.yml
version: '3.5' # Docker Engine release 17.12.0+

networks:
    servicesnet:
      driver: bridge

services:
   apache:
      build:
         context: './apache2'
      container_name: apache-service
      ports:
         - "80:80"
         - "443:443"
      tty: true
      networks:
         - servicesnet
      volumes:
         - ${HOST_APACHE_CONFIG}:/etc/apache2
         - ${HOST_PAGES_PATH}:/var/www/localhost/htdocs

   selenium-hub:
      image: selenium/hub:4.0.0-alpha-6-20200730
      container_name: selenium-hub
      ports:
         - "4444:4444"
      networks:
         - servicesnet

   chrome:
      image: selenium/node-chrome:4.0.0-alpha-6-20200730
      volumes:
         - /dev/shm:/dev/shm
      depends_on:
         - selenium-hub
      environment:
         - HUB_HOST=selenium-hub
      networks:
         - servicesnet
```
<p>When I run <code>docker-compose up</code> it outputs for the new containers:</p>
```chrome          | 2020-08-12 07:36:19,917 INFO Included extra file "/etc/supervisor/conf.d/selenium.conf" during parsing
chrome          | 2020-08-12 07:36:19,918 INFO supervisord started with pid 7
selenium-hub    | 2020-08-12 07:36:19,297 INFO Included extra file "/etc/supervisor/conf.d/selenium-grid-hub.conf" during parsing
selenium-hub    | 2020-08-12 07:36:19,298 INFO supervisord started with pid 7
selenium-hub    | 2020-08-12 07:36:20,301 INFO spawned: 'selenium-grid-hub' with pid 10
selenium-hub    | Starting Selenium Grid Hub...
selenium-hub    | 2020-08-12 07:36:20,311 INFO success: selenium-grid-hub entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
selenium-hub    | 07:36:20.588 INFO [LoggingOptions.getTracer] - Using OpenTelemetry for tracing
selenium-hub    | 07:36:20.589 INFO [LoggingOptions.createTracer] - Using OpenTelemetry for tracing
selenium-hub    | 07:36:20.607 INFO [EventBusOptions.createBus] - Creating event bus: org.openqa.selenium.events.zeromq.ZeroMqEventBus
selenium-hub    | 07:36:20.638 INFO [BoundZmqEventBus.<init>] - XPUB binding to [binding to tcp://*:4442, advertising as tcp://172.28.0.3:4442], XSUB binding to [binding to tcp://*:4443, advertising as tcp://172.28.0.3:4443]
selenium-hub    | 07:36:20.676 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://172.28.0.3:4442 and tcp://172.28.0.3:4443
selenium-hub    | 07:36:20.680 INFO [UnboundZmqEventBus.<init>] - Sockets created
selenium-hub    | 07:36:20.681 INFO [UnboundZmqEventBus.lambda$new$2] - Bus started
chrome          | 2020-08-12 07:36:21,136 INFO success: xvfb entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,136 INFO success: fluxbox entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,136 INFO success: vnc entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,137 INFO success: selenium-node entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
selenium-hub    | 07:36:21.308 INFO [Hub.execute] - Started Selenium hub 4.0.0-alpha-6 (revision 5f43a29cfc): http://172.28.0.3:4444
chrome          | 07:36:21.774 INFO [LoggingOptions.getTracer] - Using OpenTelemetry for tracing
chrome          | 07:36:21.775 INFO [LoggingOptions.createTracer] - Using OpenTelemetry for tracing
chrome          | 07:36:21.791 INFO [EventBusOptions.createBus] - Creating event bus: org.openqa.selenium.events.zeromq.ZeroMqEventBus
chrome          | 07:36:21.829 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://selenium-hub:4442 and tcp://selenium-hub:4443
chrome          | 07:36:21.857 INFO [UnboundZmqEventBus.<init>] - Sockets created
chrome          | 07:36:21.859 INFO [UnboundZmqEventBus.lambda$new$2] - Bus started
chrome          | 07:36:22.121 INFO [NodeServer.execute] - Reporting self as: http://172.28.0.5:5555
chrome          | 07:36:22.175 INFO [NodeOptions.report] - Adding Chrome for {"browserName": "chrome"} 8 times
chrome          | 07:36:22.298 INFO [NodeServer.execute] - Started Selenium node 4.0.0-alpha-6 (revision 5f43a29cfc): http://172.28.0.5:5555
chrome          | 07:36:22.302 INFO [NodeServer.execute] - Starting registration process for node id ff0154a7-ed4b-438a-887c-0a7f3a988cb4
selenium-hub    | 07:36:22.355 INFO [LocalDistributor.refresh] - Creating a new remote node for http://172.28.0.5:5555
selenium-hub    | 07:36:22.763 INFO [LocalDistributor.add] - Added node ff0154a7-ed4b-438a-887c-0a7f3a988cb4.
selenium-hub    | 07:36:22.770 INFO [Host.lambda$new$0] - Changing status of node ff0154a7-ed4b-438a-887c-0a7f3a988cb4 from DOWN to UP. Reason: http://172.28.0.5:5555 is ok
chrome          | 07:36:22.774 INFO [NodeServer.lambda$execute$0] - Node has been added
```
<p>Then I have the next method for every test:</p>
<pre class="lang-php prettyprint-override"><code><?php

namespace Tests\AppBundle\Controller;

use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Mink;
use Behat\Mink\Session;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

abstract class BaseControllerTest extends WebTestCase
{
    /**
     * @var Client
     */
    protected $client;
    /**
     * @var Session
     */
    protected $session;

    public function visitUri($uri)
    {
        $this->client = static::createClient();
        $pass = $this->client->getKernel()->getContainer()->getParameter('http_basic_auth_pass');
        $host = 'localhost'; // I've tried several things here (like 172.28.0.5:5555)

        $driver = new Selenium2Driver('chrome');
        $mink = new Mink(array(
            'chrome' => new Session($driver)
        ));
        $driver->setTimeouts(['page load' => 900000]);

        $mink->setDefaultSessionName('chrome');

        $this->session = $mink->getSession();

        $this->session->visit('http://user:' . $pass . '@' . $host . $uri);
    }
}
</code>```

And I call this method from a specific test:

    public function testClickOnSearch()
    {
        $this->visitUri(/mi-custom-uri);
        $page = $this->session->getPage();

        $this->session->wait(
            200000,
            "typeof jQuery !== 'undefined'"
        );

        $page->findButton('Buton text')->click();
        $this->assertContains('my-custom-uri-2', $this->session->getCurrentUrl());
    }
```

but I never get the session started. If I go to http://localhost:4444/wd/hub/session/url I see this error message:

"org.openqa.selenium.NoSuchSessionException: Unable to find session with ID: url\nBuild info: version: '4.0.0-alpha-6', revision: '5f43a29cfc'\nSystem info: host: 'fca78c7f81e6', ip: '172.28.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '5.4.0-42-generic', java.version: '1.8.0_252'\nDriver info: driver.version: unknown"

And executing the test, after 200 seconds this error is thrown:

PHP Fatal error:  Call to a member function click() on null

I'm sure something is missing but don't know what. Any idea?

答: Found you using selenium inside docker container. Than you can try environment variable SE_NODE_SESSION_TIMEOUT=999999</p>

Body:
I'm trying to test a Symfony3 web application with Behat/Mink and Selenium2Driver so that I can test Javascript functionallity too.

The application runs in a docker container, so I added a new docker container for selenium-hub and chrome as described here:

# docker-compose.yml
version: '3.5' # Docker Engine release 17.12.0+

networks:
    servicesnet:
      driver: bridge

services:
   apache:
      build:
         context: './apache2'
      container_name: apache-service
      ports:
         - "80:80"
         - "443:443"
      tty: true
      networks:
         - servicesnet
      volumes:
         - ${HOST_APACHE_CONFIG}:/etc/apache2
         - ${HOST_PAGES_PATH}:/var/www/localhost/htdocs

   selenium-hub:
      image: selenium/hub:4.0.0-alpha-6-20200730
      container_name: selenium-hub
      ports:
         - "4444:4444"
      networks:
         - servicesnet

   chrome:
      image: selenium/node-chrome:4.0.0-alpha-6-20200730
      volumes:
         - /dev/shm:/dev/shm
      depends_on:
         - selenium-hub
      environment:
         - HUB_HOST=selenium-hub
      networks:
         - servicesnet

When I run docker-compose up it outputs for the new containers:

chrome          | 2020-08-12 07:36:19,917 INFO Included extra file "/etc/supervisor/conf.d/selenium.conf" during parsing
chrome          | 2020-08-12 07:36:19,918 INFO supervisord started with pid 7
selenium-hub    | 2020-08-12 07:36:19,297 INFO Included extra file "/etc/supervisor/conf.d/selenium-grid-hub.conf" during parsing
selenium-hub    | 2020-08-12 07:36:19,298 INFO supervisord started with pid 7
selenium-hub    | 2020-08-12 07:36:20,301 INFO spawned: 'selenium-grid-hub' with pid 10
selenium-hub    | Starting Selenium Grid Hub...
selenium-hub    | 2020-08-12 07:36:20,311 INFO success: selenium-grid-hub entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
selenium-hub    | 07:36:20.588 INFO [LoggingOptions.getTracer] - Using OpenTelemetry for tracing
selenium-hub    | 07:36:20.589 INFO [LoggingOptions.createTracer] - Using OpenTelemetry for tracing
selenium-hub    | 07:36:20.607 INFO [EventBusOptions.createBus] - Creating event bus: org.openqa.selenium.events.zeromq.ZeroMqEventBus
selenium-hub    | 07:36:20.638 INFO [BoundZmqEventBus.<init>] - XPUB binding to [binding to tcp://*:4442, advertising as tcp://172.28.0.3:4442], XSUB binding to [binding to tcp://*:4443, advertising as tcp://172.28.0.3:4443]
selenium-hub    | 07:36:20.676 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://172.28.0.3:4442 and tcp://172.28.0.3:4443
selenium-hub    | 07:36:20.680 INFO [UnboundZmqEventBus.<init>] - Sockets created
selenium-hub    | 07:36:20.681 INFO [UnboundZmqEventBus.lambda$new$2] - Bus started
chrome          | 2020-08-12 07:36:21,136 INFO success: xvfb entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,136 INFO success: fluxbox entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,136 INFO success: vnc entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
chrome          | 2020-08-12 07:36:21,137 INFO success: selenium-node entered RUNNING state, process has stayed up for > than 0 seconds (startsecs)
selenium-hub    | 07:36:21.308 INFO [Hub.execute] - Started Selenium hub 4.0.0-alpha-6 (revision 5f43a29cfc): http://172.28.0.3:4444
chrome          | 07:36:21.774 INFO [LoggingOptions.getTracer] - Using OpenTelemetry for tracing
chrome          | 07:36:21.775 INFO [LoggingOptions.createTracer] - Using OpenTelemetry for tracing
chrome          | 07:36:21.791 INFO [EventBusOptions.createBus] - Creating event bus: org.openqa.selenium.events.zeromq.ZeroMqEventBus
chrome          | 07:36:21.829 INFO [UnboundZmqEventBus.<init>] - Connecting to tcp://selenium-hub:4442 and tcp://selenium-hub:4443
chrome          | 07:36:21.857 INFO [UnboundZmqEventBus.<init>] - Sockets created
chrome          | 07:36:21.859 INFO [UnboundZmqEventBus.lambda$new$2] - Bus started
chrome          | 07:36:22.121 INFO [NodeServer.execute] - Reporting self as: http://172.28.0.5:5555
chrome          | 07:36:22.175 INFO [NodeOptions.report] - Adding Chrome for {"browserName": "chrome"} 8 times
chrome          | 07:36:22.298 INFO [NodeServer.execute] - Started Selenium node 4.0.0-alpha-6 (revision 5f43a29cfc): http://172.28.0.5:5555
chrome          | 07:36:22.302 INFO [NodeServer.execute] - Starting registration process for node id ff0154a7-ed4b-438a-887c-0a7f3a988cb4
selenium-hub    | 07:36:22.355 INFO [LocalDistributor.refresh] - Creating a new remote node for http://172.28.0.5:5555
selenium-hub    | 07:36:22.763 INFO [LocalDistributor.add] - Added node ff0154a7-ed4b-438a-887c-0a7f3a988cb4.
selenium-hub    | 07:36:22.770 INFO [Host.lambda$new$0] - Changing status of node ff0154a7-ed4b-438a-887c-0a7f3a988cb4 from DOWN to UP. Reason: http://172.28.0.5:5555 is ok
chrome          | 07:36:22.774 INFO [NodeServer.lambda$execute$0] - Node has been added

Then I have the next method for every test:

<?php

namespace Tests\AppBundle\Controller;

use Behat\Mink\Driver\Selenium2Driver;
use Behat\Mink\Mink;
use Behat\Mink\Session;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

abstract class BaseControllerTest extends WebTestCase
{
    /**
     * @var Client
     */
    protected $client;
    /**
     * @var Session
     */
    protected $session;

    public function visitUri($uri)
    {
        $this->client = static::createClient();
        $pass = $this->client->getKernel()->getContainer()->getParameter('http_basic_auth_pass');
        $host = 'localhost'; // I've tried several things here (like 172.28.0.5:5555)

        $driver = new Selenium2Driver('chrome');
        $mink = new Mink(array(
            'chrome' => new Session($driver)
        ));
        $driver->setTimeouts(['page load' => 900000]);

        $mink->setDefaultSessionName('chrome');

        $this->session = $mink->getSession();

        $this->session->visit('http://user:' . $pass . '@' . $host . $uri);
    }
}

And I call this method from a specific test:

    public function testClickOnSearch()
    {
        $this->visitUri(/mi-custom-uri);
        $page = $this->session->getPage();

        $this->session->wait(
            200000,
            "typeof jQuery !== 'undefined'"
        );

        $page->findButton('Buton text')->click();
        $this->assertContains('my-custom-uri-2', $this->session->getCurrentUrl());
    }

but I never get the session started. If I go to http://localhost:4444/wd/hub/session/url I see this error message:

"org.openqa.selenium.NoSuchSessionException: Unable to find session with ID: url\nBuild info: version: '4.0.0-alpha-6', revision: '5f43a29cfc'\nSystem info: host: 'fca78c7f81e6', ip: '172.28.0.3', os.name: 'Linux', os.arch: 'amd64', os.version: '5.4.0-42-generic', java.version: '1.8.0_252'\nDriver info: driver.version: unknown"

And executing the test, after 200 seconds this error is thrown:

PHP Fatal error:  Call to a member function click() on null

I'm sure something is missing but don't know what. Any idea?


问:
Unhandled Runtime Error while executing a JS code
On my Localhost:3000, when I am running the code, I am getting an error saying:

```<code>Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')
</code>```

For the Source part, it is showing a certain section of my code, which is:-

```<code>    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])
</code>```

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

```<code> const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])
</code>```

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

```<code>import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (
    <div className="flex h-20 w-full items-center rounded-lg border border-[#151c22] bg-[#303339] px-12">
      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>
          <div
            onClick={() => {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />
            <div className={style.buttonText}>Buy Now</div>
          </div>
          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />
            <div className={style.buttonText}>Make Offer</div>
          </div>
        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />
          <div className={style.buttonText}>List Item</div>
        </div>
      )}
    </div>
  )
}

export default MakeOffer
</code>```

答:
selectedNFT is undefined as mentioned above.

The issue could be that it is running your code before it's defined.

This may go in your return function:

```<code>      {(typeof selectedNFT != 'undefined') ? (
        <div>Code that fetches from selectedNFT goes here.</div>
      ): (
        <div>This could be a loading bar..</div>
      )}
</code>```

This will run your code ONLY after everything else executes.

Body:
On my Localhost:3000, when I am running the code, I am getting an error saying:

Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'id')

For the Source part, it is showing a certain section of my code, which is:-

    ;(async () => {
  20 |     setSelectedMarketNft(
> 21 |       listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
     |                                                                       ^
  22 |     )
  23 |   })()
  24 | }, [selectedNft, listings, isListed])

There are certain questions of the similar type on stackOverflow, but I am unable to find any answers from any of them. I am making a web3 project, where I am using next.js, sanity and thirweb.

The source code that contains this is:-

 const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

Link to the full source code of the file where this error is occuring is:-
https://github.com/hemang-h/Standard-Demo-Marketplace-and-Minting/blob/main/components/nft/Purchase.js

Can anyone guide me what I am doing wrong here?

EXTRAS
Just for a better understanding, this is the full source code of the file where I am facing this error:

import { useEffect, useState } from 'react'

import { HiTag } from 'react-icons/hi'
import { IoMdWallet } from 'react-icons/io'
import toast, { Toaster } from 'react-hot-toast'

const style = {
  button: `mr-8 flex items-center py-2 px-12 rounded-lg cursor-pointer`,
  buttonIcon: `text-xl`,
  buttonText: `ml-2 text-lg font-semibold`,
}

const MakeOffer = ({ isListed, selectedNft, listings, marketPlaceModule }) => {
  const [selectedMarketNft, setSelectedMarketNft] = useState()
  const [enableButton, setEnableButton] = useState(false)

  useEffect(() => {
    if (!listings || isListed === 'false') return
    ;(async () => {
      setSelectedMarketNft(
        listings.find((marketNft) => marketNft.asset?.id === selectedNft.id)
      )
    })()
  }, [selectedNft, listings, isListed])

  useEffect(() => {
    if (!selectedMarketNft || !selectedNft) return

    setEnableButton(true)
  }, [selectedMarketNft, selectedNft])

  const confirmPurchase = (toastHandler = toast) =>
    toastHandler.success(`Purchase successful!`, {
      style: {
        background: '#04111d',
        color: '#fff',
      },
    })

  const buyItem = async (
    listingId = selectedMarketNft.id,
    quantityDesired = 1,
    module = marketPlaceModule
  ) => {
    console.log(listingId, quantityDesired, module, 'david')
    // yo RAZA lets goooo!!!
    //yo Qazi, ok
    // sure okay about to run it...
    // just clicked buy now...
    // still error
    // where can i see the contract address of the marketplace module
    // in [nftId.js]
    await module
      .buyoutDirectListing({
        listingId: listingId,
        quantityDesired: quantityDesired,
      })
      .catch((error) => console.error(error))

    confirmPurchase()
  }

  return (

      <Toaster position="bottom-left" reverseOrder={false} />
      {isListed === 'true' ? (
        <>

 {
              enableButton ? buyItem(selectedMarketNft.id, 1) : null
            }}
            className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}
          >
            <IoMdWallet className={style.buttonIcon} />

Buy Now

          <div
            className={`${style.button} border border-[#151c22]  bg-[#363840] hover:bg-[#4c505c]`}
          >
            <HiTag className={style.buttonIcon} />

Make Offer

        </>
      ) : (
        <div className={`${style.button} bg-[#2081e2] hover:bg-[#42a0ff]`}>
          <IoMdWallet className={style.buttonIcon} />

List Item

      )}

  )
}

export default MakeOffer

Body:
selectedNFT is undefined as mentioned above.

The issue could be that it is running your code before it's defined.

This may go in your return function:

      {(typeof selectedNFT != 'undefined') ? (
        <div>Code that fetches from selectedNFT goes here.</div>
      ): (
        <div>This could be a loading bar..</div>
      )}

This will run your code ONLY after everything else executes.