问:
PHP curl not getting the intended page content, Firefox does. Possible causes?
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

```<code>// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);
</code>```

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

```<code># Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK
</code>```

答: Instead of accessing the page by pretending to be a user, is it possible to access the information you require via their api (http://open.taobao.com/)?</p>

Body:
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK


来源: stackexchange

问:
Writing a function that returns true if given string has exactly 6 characters
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

```<code>Enter a string: 367777776
True
</code>```
```<code>Enter a string: 3677777777776
False
</code>```

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

```<code>def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

</code>```

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?

答:
You could use recursion. Loop over all the characters and for each one check to see of the next 6 are identical. If so, return true. If you get to the end of the array (or even within 6 characters of the end), return false.

For more info on recursion, check this out: https://www.programiz.com/python-programming/recursion

ContentLicense: CC BY-SA 4.0

Body:
I am trying to write a function that returns true or false if a given string has exactly  6 consecutive characters with the same value. If the string has more or less than 6, it will return false:

I am not allowed to use lists, sets or import any packages. I am only restricted to while loops, for loops, and utilizing basic mathematical operations

Two example runs are shown below:

Enter a string: 367777776
True

Enter a string: 3677777777776
False

Note that although I entered numbers, it is actually a string within the function argument for example: consecutive('3777776')

I tried to convert the string into an ASCII table and then try and filter out the numbers there. However, I

def consecutive(x):
    storage= ' '
    acc=0
    count=0
    for s in x:
        storage+= str(ord(s)) + ' '
        acc+=ord(s)
        if acc == acc:
            count+=1
    for s in x-1:

    return count

My intention is to compare the previous character's ASCII code  to the current character's ASCII code in the string. If the ASCII doesnt match, I will add an accumulator for it. The accumulator will list the number of duplicates. From there, I will implement an if-else statement to see if it is greater or less than 6 However, I have a hard time translating my thoughts into python code.

Can anyone assist me?


问:
Selenium Chromedriver: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Im trying to get Selenium working with Java. I'm using Maven. My pom.xml file looks like this

```<code><dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.1.2</version>
</dependency>
</code>```

When i try to run my programm the following error shows up. Chrome starts but does not open any sites. Ive tried chrome webdriver version 98 97 and 96. Does my normal chrome version matter?

```<code>Starting ChromeDriver 97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}) on port 61659
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97
</code>```

答:
This error message...

```<code>[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97
</code>```

...implies that the ChromeDriver was unable to initiate/spawn a new Browsing Context i.e. google-chrome session.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using chrome=98

Release Notes of ChromeDriver v98.0 clearly mentions the following:

Supports Chrome version 98

But you are using chromedriver=97.0.4692.71

Release Notes of chromedriver=97.0.4692.71 clearly mentions the following :

Supports Chrome version 97

So there is a clear mismatch between chromedriver=97.0 and the chrome=98.0

Solution

Ensure that:

Selenium is upgraded to  current released Version 4.1.2.

ChromeDriver is updated to  current ChromeDriver v98.0 level.

Chrome Browser is updated to  current chrome=98 (as per chromedriver=98.0.4758.48 release notes).

Body:
Im trying to get Selenium working with Java. I'm using Maven. My pom.xml file looks like this

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>4.1.2</version>
</dependency>

When i try to run my programm the following error shows up. Chrome starts but does not open any sites. Ive tried chrome webdriver version 98 97 and 96. Does my normal chrome version matter?

Starting ChromeDriver 97.0.4692.71 (adefa7837d02a07a604c1e6eff0b3a09422ab88d-refs/branch-heads/4692@{#1247}) on port 61659
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97

Body:
This error message...

[1644353402.048][WARNING]: This version of ChromeDriver has not been tested with Chrome version 98.
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
WARNING: Unable to find an exact match for CDP version 98, so returning the closest version found: 97
Feb. 08, 2022 9:50:02 PM org.openqa.selenium.devtools.CdpVersionFinder findNearestMatch
INFO: Found CDP implementation for version 98 of 97

...implies that the ChromeDriver was unable to initiate/spawn a new Browsing Context i.e. google-chrome session.

Your main issue is the incompatibility between the version of the binaries you are using as follows:

You are using chrome=98

Release Notes of ChromeDriver v98.0 clearly mentions the following:

Supports Chrome version 98

But you are using chromedriver=97.0.4692.71

Release Notes of chromedriver=97.0.4692.71 clearly mentions the following :

Supports Chrome version 97

So there is a clear mismatch between chromedriver=97.0 and the chrome=98.0

Solution

Ensure that:

Selenium is upgraded to  current released Version 4.1.2.

ChromeDriver is updated to  current ChromeDriver v98.0 level.

Chrome Browser is updated to  current chrome=98 (as per chromedriver=98.0.4758.48 release notes).


问:
CSS trapezoids and triangle stack food pyramid
I am currently trying to make a basic Food pyramid with six levels, The bottom 5 layers/levels will use trapezoids and the top level will be a triangle to make up a pyramid shape.

I currently can display 2 trapezoids and one triangle but after that any sizing that I use looks extremely strange and skewed, Please see the image below for what I am trying to achieve:
Css Food pyramid

Here is my current CSS code

body {
    background-color: #EFEFEF;
}
.shape {
    margin: auto;
}
.one {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 60px solid #EA1B07;
}
.one:hover {
    border-bottom: 60px solid #EA1B07;
}
.two {
    border-bottom: 75px solid #F4B600;
    border-left: 60px solid transparent;
    border-right: 60px solid transparent;
    height: 0;
    width: 100px;
}
.two:hover {
    border-bottom: 75px solid #F4B600;
}
.three {
    border-bottom: 100px solid #F9E029;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 1px;
}
.three:hover {
    border-bottom: 100px solid #F9E029;
}
.four {
    border-bottom: 100px solid #049DFC;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 60px;
    margin: auto;
}
.four:hover {
    border-bottom: 100px solid #049DFC;
}
.five {
    border-bottom: 100px solid #A77643;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 220px;
    margin: auto;
}
.five:hover {
    border-bottom: 100px solid #A77643;
}
.six {
    border-bottom: 100px solid #5CD533;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 380px;
    margin: auto;
}
.six:hover {
    border-bottom: 100px solid #5CD533;
}```

As you can see the top three layers aren't connected properly.

Also, the fifth orange/gold (#F4B600) layer need to have some padding above and below it like the above image.

Any help with this would be appreciated.

答:
Instead of trying to style each shape individually you could put all 6 elements in a container which is then shaped using CSS clip-path as that shape is simply a triangle.

Here's a basic snippet which results in:

.pyramid {
  clip-path: polygon(50% 0, 100% 100%, 0 100%);
  width: 100vmin;
  aspect-ratio: 2 / 1;
  background-color: gray;
  display: grid;
  grid-template-columns: 1fr;
  gap: 1vmin;
}
.pyramid > * {
  background: pink;
}
.one {
  background-color: #EA1B07;
}
.two {
  background-color: #F4B600;
}
.three {
  background-color: #F9E029
}
.four {
  background-color: #049DFC
}
.five {
  background-color: #A77643;
}
.six {
  background-color: #5CD533;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div></code>```

Obviously you'll want to decide on exactly the aspect ratios and gaps to suit your needs.

Body:
I am currently trying to make a basic Food pyramid with six levels, The bottom 5 layers/levels will use trapezoids and the top level will be a triangle to make up a pyramid shape.

I currently can display 2 trapezoids and one triangle but after that any sizing that I use looks extremely strange and skewed, Please see the image below for what I am trying to achieve:
Css Food pyramid

Here is my current CSS code

body {
    background-color: #EFEFEF;
}
.shape {
    margin: auto;
}
.one {
    width: 0;
    height: 0;
    border-left: 50px solid transparent;
    border-right: 50px solid transparent;
    border-bottom: 60px solid #EA1B07;
}
.one:hover {
    border-bottom: 60px solid #EA1B07;
}
.two {
    border-bottom: 75px solid #F4B600;
    border-left: 60px solid transparent;
    border-right: 60px solid transparent;
    height: 0;
    width: 100px;
}
.two:hover {
    border-bottom: 75px solid #F4B600;
}
.three {
    border-bottom: 100px solid #F9E029;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 1px;
}
.three:hover {
    border-bottom: 100px solid #F9E029;
}
.four {
    border-bottom: 100px solid #049DFC;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 60px;
    margin: auto;
}
.four:hover {
    border-bottom: 100px solid #049DFC;
}
.five {
    border-bottom: 100px solid #A77643;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 220px;
    margin: auto;
}
.five:hover {
    border-bottom: 100px solid #A77643;
}
.six {
    border-bottom: 100px solid #5CD533;
    border-left: 80px solid transparent;
    border-right: 80px solid transparent;
    height: 0;
    width: 380px;
    margin: auto;
}
.six:hover {
    border-bottom: 100px solid #5CD533;
}

As you can see the top three layers aren't connected properly.

Also, the fifth orange/gold (#F4B600) layer need to have some padding above and below it like the above image.

Any help with this would be appreciated.

Body:
Instead of trying to style each shape individually you could put all 6 elements in a container which is then shaped using CSS clip-path as that shape is simply a triangle.

Here's a basic snippet which results in:

.pyramid {
  clip-path: polygon(50% 0, 100% 100%, 0 100%);
  width: 100vmin;
  aspect-ratio: 2 / 1;
  background-color: gray;
  display: grid;
  grid-template-columns: 1fr;
  gap: 1vmin;
}
.pyramid > * {
  background: pink;
}
.one {
  background-color: #EA1B07;
}
.two {
  background-color: #F4B600;
}
.three {
  background-color: #F9E029
}
.four {
  background-color: #049DFC
}
.five {
  background-color: #A77643;
}
.six {
  background-color: #5CD533;
}

<div class="pyramid">
<div class="one"></div>
<div class="two"></div>
<div class="three"></div>
<div class="four"></div>
<div class="five"></div>
<div class="six"></div>
</div>

Obviously you'll want to decide on exactly the aspect ratios and gaps to suit your needs.


问:
Parse error. '}' expected when using dot notation with data layer variable data
I have an object that I have added to the datalayer that has an array in it. In a custom html tag (javascript), I can pull the data out just fine. And it is still a well formed object. But when I use the dot notation to access the array, Tag Manager gives the error

Error at line 10, character 39: Parse error. '}' expected

Line 10 is the authData line below. And this happened when I click the Preview button to test the changes.

```<code><script>
    var dlv = {{dlv - My-Variable}};
    var authData = { email: dlv.Items.0.Shipment.Address };
</script>
</code>```

I have followed the steps in this post. https://www.simoahava.com/gtm-tips/access-array-members-in-the-data-layer/

答:
An element in an index-dased array should be accessed using square bracket notation, like someArray[5]

```<code> var authData = { email: dlv.Items[0].Shipment.Address };
</code>```

And a variable can't have "-" in its' name, because it's confusing JavaScript, wheteher "-" should be treated as arithmetical operator or as a part of a variable name

```<code> My-Variable
</code>```

And the interpolation braces are used in JSX, not in JavaScript

```<code> {{ }}
</code>```

Body:
I have an object that I have added to the datalayer that has an array in it. In a custom html tag (javascript), I can pull the data out just fine. And it is still a well formed object. But when I use the dot notation to access the array, Tag Manager gives the error

Error at line 10, character 39: Parse error. '}' expected

Line 10 is the authData line below. And this happened when I click the Preview button to test the changes.

I have followed the steps in this post. https://www.simoahava.com/gtm-tips/access-array-members-in-the-data-layer/

Body:
An element in an index-dased array should be accessed using square bracket notation, like someArray[5]

 var authData = { email: dlv.Items[0].Shipment.Address };

And a variable can't have "-" in its' name, because it's confusing JavaScript, wheteher "-" should be treated as arithmetical operator or as a part of a variable name

 My-Variable

And the interpolation braces are used in JSX, not in JavaScript

 {{ }}


问:
URL filter parameters in Apache Superset dashboards
I'm trying to create simple superset dashboard with a single chart (Big Number)  that will filter data based on URL parameter passed to the dashboard. I've tried to fallow this Apache Superset Dashboard Filter with URL parameter ). I've used pattern &preselect_filters={"CHART-ID":{"tableColumnName1":["value1"]}} and then tried to define new filter in a chart like tableColumn = {{ filter_values('tableColumnName1')[0] }}, but this generates error. From my observation it resolves this expression without looking for query param.

How should I use it? Is there a documentation somewhere?

My superset version is 0.37.0

答:
You can open your dashboard, filter like you want to see and, in bullet menu (top right), click in "Copy chart URL". The URL is a shortened URL that redirects to a pre-filtered version of your dashboard.

Because the name of menu option, I don't know if this is a feature or a useful bug.


问:
Is it possible to define function that creates an N-dimensional list of lists easily?
I have searched and found these questions: How to create a multi-dimensional list and N dimensional array in python which hint toward what I am looking for, but they seem to only make 2D arrays and not ND arrays.

Problem:

My problem is that I am able to create an n-dimensional list of lists for a known n, but I am not sure how it can be generalized to work with all values of n.

Consider this example:

```<code>def makeList(n):
    return [[[n for _ in range(n)]
                for _ in range(n)]
                for _ in range(n)]
print(makeList(3))
</code>```

Output:

```<code>[[[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]
</code>```

This will create a list of lists that is a 3x3x3 array of 3's which is the intended result, but if we use a different n:

```<code>print(makeList(2))
</code>```

Output:

```<code>[[[2, 2],
  [2, 2]],
 [[2, 2],
  [2, 2]]]
</code>```

This will create a list of lists that is a 2x2x0 array of 2's and this is not the intended result. Instead the results should be a list of lists that is a 2x2 array of 2's.

Likewise if we set n = 4:

```<code>print(makeList(4))
</code>```

This will give a list of lists that is 4x4x4 when it should give a 4x4x4x4 list of lists.

The main issue is that the number of for loops must change depending on the input, but obviously the code can't "come to life" and recode itself magically, hence my issue.

I am looking for a way to get this result that is simple. I am sure I could continue developing ideas for solutions, but I have not been able to think of anything that is concise.

What I have tried:

The first idea I thought of was to use recursion, and this my simple approach:

```<code>def makeList(n, output = []):
    if not output:
        output = [n for _ in range(n)]
    else:
        output = [output for _ in range(n)]
    if len(output) == n:
        return output
    else:
        return makeList(n, output)
</code>```

This obviously will not work because if len(output) == n: will execute the first iteration since the length of the inner loops is equal to the length of the outermost loop. However, even if there was a condition that properly terminated the function, this solution would still not be ideal because I could run into maximum recursion errors with large values of n. Furthermore, even if these issues were resolved this code is still quite long as well as time consuming.

The other potential perspective I considered (and the solution that I found that works) is using a dict. My solution saves the intermediate lists of lists in a dict so it can be used for the next iteration:

```<code>def makeList(n):
    d = {str(i): None for i in range(n)}
    for i in range(n):
        if i == 0:
            d[str(i)] = [n for _ in range(n)]
        else:
            d[str(i)] = [d[str(i-1)] for _ in range(n)]
    return d[str(n-1)]
</code>```

But again, this is very long and doesn't seem very pythonic.

Solution requirements:

The ideal solution would be much more concise than mine with an efficient time complexity that only uses built-in functions.

Other options that are close to these requirements would also be helpful as long as the spirit of the answer is trying to best meet the requirements.

Being concise is the most important aspect, however, which is why I am not fully happy with my current attempts.

Body:
I have searched and found these questions: How to create a multi-dimensional list and N dimensional array in python which hint toward what I am looking for, but they seem to only make 2D arrays and not ND arrays.

Problem:

My problem is that I am able to create an n-dimensional list of lists for a known n, but I am not sure how it can be generalized to work with all values of n.

Consider this example:

def makeList(n):
    return [[[n for _ in range(n)]
                for _ in range(n)]
                for _ in range(n)]
print(makeList(3))

Output:

[[[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]

This will create a list of lists that is a 3x3x3 array of 3's which is the intended result, but if we use a different n:

print(makeList(2))

Output:

[[[2, 2],
  [2, 2]],
 [[2, 2],
  [2, 2]]]

This will create a list of lists that is a 2x2x0 array of 2's and this is not the intended result. Instead the results should be a list of lists that is a 2x2 array of 2's.

Likewise if we set n = 4:

print(makeList(4))

This will give a list of lists that is 4x4x4 when it should give a 4x4x4x4 list of lists.

The main issue is that the number of for loops must change depending on the input, but obviously the code can't "come to life" and recode itself magically, hence my issue.

I am looking for a way to get this result that is simple. I am sure I could continue developing ideas for solutions, but I have not been able to think of anything that is concise.

What I have tried:

The first idea I thought of was to use recursion, and this my simple approach:

def makeList(n, output = []):
    if not output:
        output = [n for _ in range(n)]
    else:
        output = [output for _ in range(n)]
    if len(output) == n:
        return output
    else:
        return makeList(n, output)

This obviously will not work because if len(output) == n: will execute the first iteration since the length of the inner loops is equal to the length of the outermost loop. However, even if there was a condition that properly terminated the function, this solution would still not be ideal because I could run into maximum recursion errors with large values of n. Furthermore, even if these issues were resolved this code is still quite long as well as time consuming.

The other potential perspective I considered (and the solution that I found that works) is using a dict. My solution saves the intermediate lists of lists in a dict so it can be used for the next iteration:

def makeList(n):
    d = {str(i): None for i in range(n)}
    for i in range(n):
        if i == 0:
            d[str(i)] = [n for _ in range(n)]
        else:
            d[str(i)] = [d[str(i-1)] for _ in range(n)]
    return d[str(n-1)]

But again, this is very long and doesn't seem very pythonic.

Solution requirements:

The ideal solution would be much more concise than mine with an efficient time complexity that only uses built-in functions.

Other options that are close to these requirements would also be helpful as long as the spirit of the answer is trying to best meet the requirements.

Being concise is the most important aspect, however, which is why I am not fully happy with my current attempts.

Body:
Using tuple(n for _ in range(n)) to get the dimension that you want, and numpy to generate a multidimensional array:

import numpy as np

def make_array(n):
    return np.full(tuple(n for _ in range(n)), n)

for n in range(1,5):
    print(make_array(n))

Output:

[1]

[[2 2]
 [2 2]]

[[[3 3 3]
  [3 3 3]
  [3 3 3]]

 [[3 3 3]
  [3 3 3]
  [3 3 3]]

 [[3 3 3]
  [3 3 3]
  [3 3 3]]]

[[[[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]]

 [[[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]]

 [[[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]]

 [[[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]

  [[4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]
   [4 4 4 4]]]]


问:
preg_replace what expression to use to replace specific text and add a period
Say I have a string as:

```<code>$orig = "Go 'outisde'Please";
</code>```

And i want to replace the word 'outside' (must be in single quotes) with the following:

```<code>$replaceWith = "OUT";
</code>```

And if the orig string has alphanumeric characters following it (not spaces or special, or quotes) then add a period after the replaceWith

So the expected output would become:

```<code>$out = "Go 'OUT'.Please";
</code>```

Here is what I have so far, but I am missing the part that adds a period as explained above.

```<code>$out = preg_replace("/'outside'/", $replaceWith, $orig); //handle single quotes
</code>```

This would evaluate as:

```<code>$out = "Go 'OUT'Please";
</code>```

My guess is there is a fancy regex that can help me with it. I tried searching and couldn't find anything directly for my use case. Thank you.

答:
You can use

$orig = "Go 'outside'Please";
$replaceWith = "OUT";
$out = preg_replace_callback("/'outside'([a-zA-Z0-9])?/", fn($m) => empty($m[1]) ? $replaceWith : "$replaceWith.${m[1]}", $orig);
echo $out; // => Go OUT.Please
```

See the PHP demo.

Here, 'outside'([a-zA-Z0-9])? matches 'outside' and then captures a letter or a digit into Group 1 with an optional ([a-zA-Z0-9])? pattern.

If Group 1 matches, the replacement is the $replaceWith + . + Group 1 value, else, the whole match is replaced with the $replaceWith string.

Body:
Say I have a string as:

$orig = "Go 'outisde'Please";

And i want to replace the word 'outside' (must be in single quotes) with the following:

$replaceWith = "OUT";

And if the orig string has alphanumeric characters following it (not spaces or special, or quotes) then add a period after the replaceWith

So the expected output would become:

$out = "Go 'OUT'.Please";

Here is what I have so far, but I am missing the part that adds a period as explained above.

$out = preg_replace("/'outside'/", $replaceWith, $orig); //handle single quotes

This would evaluate as:

$out = "Go 'OUT'Please";

My guess is there is a fancy regex that can help me with it. I tried searching and couldn't find anything directly for my use case. Thank you.

Body:
You can use

$orig = "Go 'outside'Please";
$replaceWith = "OUT";
$out = preg_replace_callback("/'outside'([a-zA-Z0-9])?/", fn($m) => empty($m[1]) ? $replaceWith : "$replaceWith.${m[1]}", $orig);
echo $out; // => Go OUT.Please

See the PHP demo.

Here, 'outside'([a-zA-Z0-9])? matches 'outside' and then captures a letter or a digit into Group 1 with an optional ([a-zA-Z0-9])? pattern.

If Group 1 matches, the replacement is the $replaceWith + . + Group 1 value, else, the whole match is replaced with the $replaceWith string.


问:
Macro questions
On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.

Has somebody a idea how i can make a macro like that?

```<code>SET(SomeVariable, 137);
</code>```

which will execute

```<code>SomeVariable = 137;
SomeVariable_inverse = ~137;
</code>```

Edit:

The best Solution seems to be:

```<code>#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)
</code>```

Thanks for the answers

答:
You can do it in a single statement, which avoids having to use do {} while (0).

```<code>#define SetInverse(token, value) (token##_inverse = ~(token = (value)))
</code>```

Also, this only evalutes (value) once, which is always nice.

OwnerDisplayName: nuriaion

ContentLicense: CC BY-SA 2.5

Title: Macro questions

Body:
On a software project (some old C compiler) we have a lot of variables which have to be saved normal and inverted.

Has somebody a idea how i can make a macro like that?

SET(SomeVariable, 137);

which will execute

SomeVariable = 137;
SomeVariable_inverse = ~137;

Edit:

The best Solution seems to be:

#define SET(var,value) do { var = (value); var##_inverse = ~(value); } while(0)

Thanks for the answers

LastEditorDisplayName: Evan Teran

Body:
You can do it in a single statement, which avoids having to use do {} while (0).

#define SetInverse(token, value) (token##_inverse = ~(token = (value)))

Also, this only evalutes (value) once, which is always nice.

OwnerDisplayName: ephemient


问:
Unable to run hop pipelines on Spark running on Kubernetes
I am looking for help in running hop pipelines on Spark cluster, running on kubernetes.

I have spark master deployed with 3 worker nodes on kubernetes

I am using hop-run.sh command to run pipeline on spark running on kubernetes.

Facing Below exception
-java.lang.NoClassDefFoundError: Could not initialize class com.amazonaws.services.s3.AmazonS3ClientBuilder

Looks like fat.jar is not getting associated with the spark when running hop-run.sh command.

I tried running same with spark-submit command too but not sure how to pass references of pipelines and workflows to Spark running on kubernetes, though I am able to add fat jar to the classpath (can be seen in logs)

Any kind of help is appreciated.
Thanks
like

答:
Could it be that you are using version 1.0?
We had a missing jar for S3 VFS which has been resolved in 1.1
https://issues.apache.org/jira/browse/HOP-3327

For more information on how to use spark-submit you can take a look at the following documentation:
https://hop.apache.org/manual/latest/pipeline/pipeline-run-configurations/beam-spark-pipeline-engine.html#_running_with_spark_submit

The location to the fat-jar the pipeline and the required metadata-export can all be VFS locations so no need to place those on the cluster itself.


问:
How to sort the date in dd-mm-yyyy format in c++
Suggest way to store and sort in c++.

input:

```<code>01-02-2022
15-01-2022
20-10-2021
25-12-2022
</code>```

答:
I would probably convert the strings to time_t's, and sort those. A time_t lets you represent the time with a single, easy to sort thing. Up to you whether to keep the original string with that time_t, or just convert back to the required format of string when you need it back.

#include <iostream>
#include <vector>
#include <chrono>
#include <sstream>
#include <iomanip>

class Date {
    tm expanded;
    time_t compact;
public:
    bool operator<(Date const& other) const {
        return compact < other.compact;
    }

    friend std::istream &operator>>(std::istream &is, Date &d) {
        is >> std::get_time(&d.expanded, "%d-%m-%Y");
        d.compact = mktime(&d.expanded);
        return is;
    }

    friend std::ostream &operator<<(std::ostream &os, Date const &d) {
        return os << std::put_time(&d.expanded, "%d-%m-%Y");
    }
};

int main() {
    std::istringstream input {
    R"(01-02-2022
    15-01-2022
    20-10-2021
    25-12-2022)"};

    std::vector<Date> dates { std::istream_iterator<Date>(input), {}};
    std::sort(dates.begin(), dates.end());
    std::copy(dates.begin(), dates.end(), std::ostream_iterator<Date>(std::cout, "\n"));
}
```
<p>Result:</p>
```20-10-2021
15-01-2022
01-02-2022
25-12-2022
```

Body:
Suggest way to store and sort in c++.

input:

01-02-2022
15-01-2022
20-10-2021
25-12-2022

Body:
I would probably convert the strings to time_t's, and sort those. A time_t lets you represent the time with a single, easy to sort thing. Up to you whether to keep the original string with that time_t, or just convert back to the required format of string when you need it back.

#include <iostream>
#include <vector>
#include <chrono>
#include <sstream>
#include <iomanip>

class Date {
    tm expanded;
    time_t compact;
public:
    bool operator<(Date const& other) const {
        return compact < other.compact;
    }

    friend std::istream &operator>>(std::istream &is, Date &d) {
        is >> std::get_time(&d.expanded, "%d-%m-%Y");
        d.compact = mktime(&d.expanded);
        return is;
    }

    friend std::ostream &operator<<(std::ostream &os, Date const &d) {
        return os << std::put_time(&d.expanded, "%d-%m-%Y");
    }
};

int main() {
    std::istringstream input {
    R"(01-02-2022
    15-01-2022
    20-10-2021
    25-12-2022)"};

    std::vector<Date> dates { std::istream_iterator<Date>(input), {}};
    std::sort(dates.begin(), dates.end());
    std::copy(dates.begin(), dates.end(), std::ostream_iterator<Date>(std::cout, "\n"));
}

Result:

20-10-2021
15-01-2022
01-02-2022
25-12-2022


问:
React-facebook-login work only for one account
Hello I have implemented react facebook login package in my app. However it works only for one account. I can't get login info data with another account. Here is my code:</p>
```<code>    const registerFb = async (req, res) => {
  console.log(req.body);
  const newUser = new UsersSchema({
    email: req.body.email,
  });
  try {
    const existEmail = await UsersSchema.findOne({ email: req.body.email });
    if (existEmail) {
      const token = jwt.sign({ email: req.body.email }, "privKey");
      res.send(token);
    } else {
      const savedUser = await newUser.save();
      res.send(savedUser);
    }
  } catch (err) {
    res.json({ message: err });
  }
};
</code>```

答:
Is your app still in development mode? If so, you can only test with specified users -- and the person who set-up the app is one of the specified users by default.

You can add more testing users under Roles in the App Dashboard.

Body:
Hello I have implemented react facebook login package in my app. However it works only for one account. I can't get login info data with another account. Here is my code:

    const registerFb = async (req, res) => {
  console.log(req.body);
  const newUser = new UsersSchema({
    email: req.body.email,
  });
  try {
    const existEmail = await UsersSchema.findOne({ email: req.body.email });
    if (existEmail) {
      const token = jwt.sign({ email: req.body.email }, "privKey");
      res.send(token);
    } else {
      const savedUser = await newUser.save();
      res.send(savedUser);
    }
  } catch (err) {
    res.json({ message: err });
  }
};


问:
Angular [Violation] Dom Mutation warnings in Chrome
In our Angular 6 project, in Chrome, I'm suddenly noticing these [Violation] warnings in our app stemming from zone.js line 1666. The message:

[Violation] Added synchronous DOM mutation listener to a 'DOMNodeInserted' event. Consider using MutationObserver to make the page more responsive.

I've never seen these before, but then again they're in a Chrome dev tools tab I've never noticed before (the console sidebar). When I switched over to an older branch and locally served it, these warnings still appear. So perhaps these warnings have always been there and I missed it all this time, or perhaps a merge with a teammate's project changed a file in Angular permanently, causing further builds to always cause these warnings.

I checked line 1666 of zone.js and it involves the following code:

```<code>    var customScheduleGlobal = function () {
        // if there is already a task for the eventName + capture,
        // just return, because we use the shared globalZoneAwareCallback here.
        if (taskData.isExisting) {
            return;
        }
        return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
    };
</code>```

To my knowledge we've never modified zone.js. What are these [Violation] warnings, how can I fix them, consequences of not fixing them?

答:
The errors you mentioned may occur due to the jQuery version. Therefore, I recommend updating the jQuery version first.

If you're still getting errors, you should edit the app.component.ts file in the project like this:

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-web-ui';

  ngOnInit() {
    this.detectDivChanges();
  }

  detectDivChanges() {
    const div = document.querySelector('.container')!;
    const config = { attributes: true, childList: true, subtree: true };
    const observer = new MutationObserver((mutation) => {
      console.log("it works. enjoy :)");
    })
    observer.observe(div, config);
  }
}
</code>```

If this method also didn't fix the problem, I'm sure that it depends on running extensions. An extension coded using an old version of jQuery and listening for DOM mutations will cause this issue.

The quickest way to find out if this is the cause of the problem is to also run the project in incognito mode.

Body:
In our Angular 6 project, in Chrome, I'm suddenly noticing these [Violation] warnings in our app stemming from zone.js line 1666. The message:

[Violation] Added synchronous DOM mutation listener to a 'DOMNodeInserted' event. Consider using MutationObserver to make the page more responsive.

I've never seen these before, but then again they're in a Chrome dev tools tab I've never noticed before (the console sidebar). When I switched over to an older branch and locally served it, these warnings still appear. So perhaps these warnings have always been there and I missed it all this time, or perhaps a merge with a teammate's project changed a file in Angular permanently, causing further builds to always cause these warnings.

I checked line 1666 of zone.js and it involves the following code:

    var customScheduleGlobal = function () {
        // if there is already a task for the eventName + capture,
        // just return, because we use the shared globalZoneAwareCallback here.
        if (taskData.isExisting) {
            return;
        }
        return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
    };

To my knowledge we've never modified zone.js. What are these [Violation] warnings, how can I fix them, consequences of not fixing them?

Body:
The errors you mentioned may occur due to the jQuery version. Therefore, I recommend updating the jQuery version first.

If you're still getting errors, you should edit the app.component.ts file in the project like this:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-web-ui';

  ngOnInit() {
    this.detectDivChanges();
  }

  detectDivChanges() {
    const div = document.querySelector('.container')!;
    const config = { attributes: true, childList: true, subtree: true };
    const observer = new MutationObserver((mutation) => {
      console.log("it works. enjoy :)");
    })
    observer.observe(div, config);
  }
}

If this method also didn't fix the problem, I'm sure that it depends on running extensions. An extension coded using an old version of jQuery and listening for DOM mutations will cause this issue.

The quickest way to find out if this is the cause of the problem is to also run the project in incognito mode.


问:
what is onChange={(e) => setName(e.target.value)}? in React mean
I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line "  onChange={(e) => setName(e.target.value)}".

Thank you for your help.

They used this example:

```<code>import ReactDOM from 'react-dom';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
</code>```

答:
There are at least 5 concepts that I can think of being used in this single line that I recommend you to learn about

Higher-Order Functions

Anonymous functions

Arrow Functions

State

Synthetic Events

To start your journey, just know that this code onChange={(e) => setName(e.target.value)} is the same as the one below:

```<code>function clickHandler(e) {
  setName(e.target.value)
}

<input
  type="text"
  value={name}
  onChange={clickHandler}
/>
</code>```

Maybe that makes things clearer.

Body:
I am new to React;I am learning about React Form. I understand the code but I do not really understand the concept behind and why we use this line "  onChange={(e) => setName(e.target.value)}".

Thank you for your help.

They used this example:

import ReactDOM from 'react-dom';

function MyForm() {
  const [name, setName] = useState("");

  const handleSubmit = (event) => {
    event.preventDefault();
    alert(`The name you entered was: ${name}`)
  }

  return (
    <form onSubmit={handleSubmit}>
      Enter your name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />

      <input type="submit" />
    </form>
  )
}

ReactDOM.render(<MyForm />, document.getElementById('root'));

Body:
There are at least 5 concepts that I can think of being used in this single line that I recommend you to learn about

Higher-Order Functions

Anonymous functions

Arrow Functions

State

Synthetic Events

To start your journey, just know that this code onChange={(e) => setName(e.target.value)} is the same as the one below:

function clickHandler(e) {
  setName(e.target.value)
}

<input
  type="text"
  value={name}
  onChange={clickHandler}
/>

Maybe that makes things clearer.


问:
How to get the indexes of all minimum values in pandas dataframe?
I have a dataframe:

```<code>df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0
</code>```

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

```<code>x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]
</code>```

I know idxmin() gives the first instance of the lowest value:

```<code>df.idxmin(axis=1)

x    A
y    A
z    B
</code>```

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

```<code>df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2
</code>```

答:
Convert the df into bool by finding every min value and pull columns that return True into a list</p>
```<code> s= df==df.min()

df['column_min']=s.agg(lambda s: s.index[s].values, axis=1)

 A   B   column_min
x  0  1        [A]
y  0  0     [A, B]
z  1  0        [B]
</code>```

Body:
I have a dataframe:

df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]

I know idxmin() gives the first instance of the lowest value:

df.idxmin(axis=1)

x    A
y    A
z    B

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2

Body:
Convert the df into bool by finding every min value and pull columns that return True into a list

 s= df==df.min()

df['column_min']=s.agg(lambda s: s.index[s].values, axis=1)

 A   B   column_min
x  0  1        [A]
y  0  0     [A, B]
z  1  0        [B]


问:
What does this error mean with setView: of NSMenuItem
I'm using setView: of NSMenuItem to customize a menu item, and everything goes happy until I put a pop up button in the content view. When I clicked the button, it didn't pop up its menu and I got the following message.

Error -25205 for CopyAttributeValue(data, type,
  (CFStringRef)attribute, &result, NULL) in
  -[NSAccessibilityAXUIElementWrapper accessibilityAttributeValue:] (line 1928 of file
  /SourceCache/AppKit/AppKit-1038.35/Accessibility.subproj/NSAccessibilityAPIBridge.m)

Does it mean that we can't pop up one menu over another one? Is there a workaround?

答:
Regardless of whether there’s a workaround, putting a pop-up menu inside another menu is extremely poor interface. You should find another way of implementing the functionality you desire. What are you actually trying to achieve? Maybe a regular NSMenuItem with a submenu would work?

NSPopover (new in Lion) or MAAttachedWindow are much better alternatives for implementing pop-up interfaces like a calendar.

ContentLicense: CC BY-SA 3.0


问:
LINQPad: How do I add a property to each row being dumped?
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })
```
<p>But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:</p>
<pre class="lang-cs prettyprint-override"><code>Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })
</code>```

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })
```

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

答:
I've got a slight variation on NetMage's extension method. Try this instead:

```<code>public static object Extendo(this object @object, Action<dynamic> inject)
{
    dynamic e = Util.ToExpando(@object);
    inject(e);
    return (object)e;
}
</code>```

The Action<dynamic> allows this code to be written:

```<code>var people = new[]
{
    new { name = "Fred", age = 41 },
    new { name = "John", age = 67 },
    new { name = "Dave", age = 23 },
};

people
    .Select(p => p.Extendo(d => d.IsOld = p.age >= 55))
    .Dump();
</code>```

I can extend this slightly again with this method:

```<code>public static object Extendo<T>(this IEnumerable<T> source, Action<T, dynamic> inject) =>
    source.Select(x => x.Extendo(d => inject(x, d)));
</code>```

Now I can write this:

```<code>people.Extendo((p, d) => d.IsOld = p.age >= 55).Dump();
</code>```

I get the same result.

Of course, these methods effectively return object so there's no further computation that can be done. So it's probably worthwhile just going straight for Dump. Try this:

```<code>public static void Dump<T>(this IEnumerable<T> source, Action<T, dynamic> inject) =>
    source.Select(x => x.Extendo(d => inject(x, d))).Dump();
</code>```

Now you just write this:

```<code>people.Dump((p, d) => d.IsOld = p.age >= 55);
</code>```

Body:
In LINQPad, I frequently want to Dump some SQL table, but add a property to each row. I usually default to the simple:

Publishers
.Select(p => new { p, AppCount = p.Apps.Count() })

But of course this results in messy output, because each item is formatted as a vertical table, with an extra column containing the added property. I could create a new object, but that's very verbose, and you lose the table traversal links:

Publishers
.Select(p => new { p.PublisherId, p.Name, p.Added, ..., AppCount = p.Apps.Count() })

What I'd love is some sort of merge syntax, which creates a dynamic object to dump with the added property:

Publishers
.Select(p => p.Merge(new { AppCount = p.Apps.Count() })

I've tried a few different ways to accomplish that: using JsonConvert.SerializeObject (this goes haywire trying to serialize all the foreign key references and repeating loops, using ExpandoObject (couldn't come up with a nice clean syntax), and libraries like https://github.com/kfinley/TypeMerger, which I haven't gotten to work either.

Has anyone come up with a clean way to do this? Does LINQPad have some built in synax for this I can use? Thanks!

UPDATE: I uploaded a sample script to demonstrate the issue and let anyone try their solutions against: http://share.linqpad.net/kclxpl.linq

To run, you'll need to populate the Nutshell database, which you can do using the "Populate demo database" sample in LINQPad.

Body:
I've got a slight variation on NetMage's extension method. Try this instead:

public static object Extendo(this object @object, Action<dynamic> inject)
{
    dynamic e = Util.ToExpando(@object);
    inject(e);
    return (object)e;
}

The Action<dynamic> allows this code to be written:

var people = new[]
{
    new { name = "Fred", age = 41 },
    new { name = "John", age = 67 },
    new { name = "Dave", age = 23 },
};

people
    .Select(p => p.Extendo(d => d.IsOld = p.age >= 55))
    .Dump();

I can extend this slightly again with this method:

public static object Extendo<T>(this IEnumerable<T> source, Action<T, dynamic> inject) =>
    source.Select(x => x.Extendo(d => inject(x, d)));

Now I can write this:

people.Extendo((p, d) => d.IsOld = p.age >= 55).Dump();

I get the same result.

Of course, these methods effectively return object so there's no further computation that can be done. So it's probably worthwhile just going straight for Dump. Try this:

public static void Dump<T>(this IEnumerable<T> source, Action<T, dynamic> inject) =>
    source.Select(x => x.Extendo(d => inject(x, d))).Dump();

Now you just write this:

people.Dump((p, d) => d.IsOld = p.age >= 55);


问:
Get sum of children in json object
I have a JSON object which has multiple children and grandchildren I want to get the sum of grandchildren and show it with the children, similar get the sum of children and show it with the parent.

So in the end, the parent should display the sum of all children.

```<code>{
    "id": 4,
    "Nominal": "4",
    "name": "Revenue",
    "type": "Revenue",
    "parent_id": 0,
    "children": [
        {
            "id": 14,
            "Nominal": "41",
            "name": "Operational Revenue",
            "parent_id": 4,
            "transactions_sum_debit": null,
            "transactions_sum_credit": null,
            "children": [
                {
                    "id": 46,
                    "Nominal": "4101",
                    "name": "Revenue of Products and services Sales",
                    "parent_id": 41,
                    "transactions_sum_debit": "1658.00",
                    "transactions_sum_credit": "3316.00",
                    "children": [],
                    "transactions": [
                        {
                            "id": 308,
                            "debit": null,
                            "credit": "64.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 310,
                            "debit": null,
                            "credit": "765.00"
                        },
                        {
                            "id": 318,
                            "debit": null,
                            "credit": "64.00",
                            "first_level_id": 46,
                            "invoice_id": 20
                        },
                        {
                            "id": 320,
                            "debit": null,
                            "credit": "765.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 340,
                            "debit": null,
                            "credit": "765.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 466,
                            "debit": "64.00",
                            "credit": null,
                            "first_level_id": 46
                        },
                        {
                            "id": 468,
                            "debit": "765.00",
                            "credit": null,
                            "first_level_id": 46
                        }
                    ]
                }
            ],
            "transactions": []
        },
        {
            "id": 15,
            "Nominal": "42",
            "parent_id": 4,
            "transactions_sum_debit": null,
            "transactions_sum_credit": null,
            "children": [
                {
                    "id": 47,
                    "Nominal": "4201",
                    "parent_id": 42,
                    "transactions_sum_debit": null,
                    "transactions_sum_credit": "1520.00",
                    "children": [],
                    "transactions": [
                        {
                            "id": 304,
                            "debit": null,
                            "credit": "380.00",
                            "first_level_id": 47
                        },
                        {
                            "id": 334,
                            "debit": null,
                            "credit": "380.00",
                            "first_level_id": 47
                        }
                    ]
                }
            ],
            "transactions": []
        }
    ]
}
</code>```

for example in the above JSON data I want to get the sum transactions_sum_debit from all the children and show it one level up. until the parent_id = 0

My View:

```<code>        //get sum of all children in json
        function sumOfChildrens(parent, id) {
            let data = parent;
            let ids = id;
            let transactions_sum_credit = 0;
            //call the function recursively until the last child
            for (let i = 0; i < data.length; i++) {
                if (data[i].id == ids) {
                    transactions_sum_credit += parseFloat(data[i].transactions_sum_credit);
                }
                if (data[i].children) {
                    transactions_sum_credit += sumOfChildrens(data[i].children, ids);
                }
            }
            console.log(transactions_sum_credit);
            return transactions_sum_credit;
        }

        $(document).ready(function() {
            $.ajax({
                headers: {
                    "Authorization": 'Bearer ' + sessionStorage.getItem('token')
                },
                type: "get",
                url: "{{ URL::asset('api/reports/get-generalLedger') }}",
                success: function(data) {
                    var data = data.data;
                    console.log(data);
                    $("#tablebody").empty();
                    data.map(parent => {
                        $("#tablebody").append(
                            `
                            <tr>
                                <td class="${parent.Nominal} id_${parent.id}">${parent.Nominal}</td>
                                <td class="${parent.Nominal} id_${parent.id}">${parent.name}</td>
                                <td class="${parent.Nominal} id_${parent.id}"></td>
                                <td class="${parent.Nominal} id_${parent.id}">${sumOfChildrens(parent,parent.id)}</td>
                            </tr>
                        `);
                    });
                },
                error: function(data) {
                    alert(data['message']);
                    console.log(data['message']);
                },
            });
        });
</code>```

答:
Stackoverflow isn't meant for other people to write code for you, but rather to answer specific questions or help solve problems. Instead of showing more code, explain what you've tried, which behavior you saw vs the one you expected.
That being said, I think the following code snippet might help you clarify your question or even solve the problem on your own.

// for each first level child
data.children.map((item) => {
  // for each next level child
  item.children.map((item2) => {
    // this is the list of transactions
    console.log(item2.transactions);
    let sum = 0;
    // go over each transaction
    item2.transactions.map((transaction) => {
      // debit != null
      if (transaction.debit) {
        sum += parseFloat(transaction.debit);
      }
    });
    // here you could add the sum to the parent
    console.log(sum);
  });
});
```

Try to edit this code so it works for you and come back if you have more questions.

Title: Get sum of children in json object

Body:
I have a JSON object which has multiple children and grandchildren I want to get the sum of grandchildren and show it with the children, similar get the sum of children and show it with the parent.

So in the end, the parent should display the sum of all children.

{
    "id": 4,
    "Nominal": "4",
    "name": "Revenue",
    "type": "Revenue",
    "parent_id": 0,
    "children": [
        {
            "id": 14,
            "Nominal": "41",
            "name": "Operational Revenue",
            "parent_id": 4,
            "transactions_sum_debit": null,
            "transactions_sum_credit": null,
            "children": [
                {
                    "id": 46,
                    "Nominal": "4101",
                    "name": "Revenue of Products and services Sales",
                    "parent_id": 41,
                    "transactions_sum_debit": "1658.00",
                    "transactions_sum_credit": "3316.00",
                    "children": [],
                    "transactions": [
                        {
                            "id": 308,
                            "debit": null,
                            "credit": "64.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 310,
                            "debit": null,
                            "credit": "765.00"
                        },
                        {
                            "id": 318,
                            "debit": null,
                            "credit": "64.00",
                            "first_level_id": 46,
                            "invoice_id": 20
                        },
                        {
                            "id": 320,
                            "debit": null,
                            "credit": "765.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 340,
                            "debit": null,
                            "credit": "765.00",
                            "first_level_id": 46
                        },
                        {
                            "id": 466,
                            "debit": "64.00",
                            "credit": null,
                            "first_level_id": 46
                        },
                        {
                            "id": 468,
                            "debit": "765.00",
                            "credit": null,
                            "first_level_id": 46
                        }
                    ]
                }
            ],
            "transactions": []
        },
        {
            "id": 15,
            "Nominal": "42",
            "parent_id": 4,
            "transactions_sum_debit": null,
            "transactions_sum_credit": null,
            "children": [
                {
                    "id": 47,
                    "Nominal": "4201",
                    "parent_id": 42,
                    "transactions_sum_debit": null,
                    "transactions_sum_credit": "1520.00",
                    "children": [],
                    "transactions": [
                        {
                            "id": 304,
                            "debit": null,
                            "credit": "380.00",
                            "first_level_id": 47
                        },
                        {
                            "id": 334,
                            "debit": null,
                            "credit": "380.00",
                            "first_level_id": 47
                        }
                    ]
                }
            ],
            "transactions": []
        }
    ]
}

for example in the above JSON data I want to get the sum transactions_sum_debit from all the children and show it one level up. until the parent_id = 0

My View:

        //get sum of all children in json
        function sumOfChildrens(parent, id) {
            let data = parent;
            let ids = id;
            let transactions_sum_credit = 0;
            //call the function recursively until the last child
            for (let i = 0; i < data.length; i++) {
                if (data[i].id == ids) {
                    transactions_sum_credit += parseFloat(data[i].transactions_sum_credit);
                }
                if (data[i].children) {
                    transactions_sum_credit += sumOfChildrens(data[i].children, ids);
                }
            }
            console.log(transactions_sum_credit);
            return transactions_sum_credit;
        }

        $(document).ready(function() {
            $.ajax({
                headers: {
                    "Authorization": 'Bearer ' + sessionStorage.getItem('token')
                },
                type: "get",
                url: "{{ URL::asset('api/reports/get-generalLedger') }}",
                success: function(data) {
                    var data = data.data;
                    console.log(data);
                    $("#tablebody").empty();
                    data.map(parent => {
                        $("#tablebody").append(
                            `

                                ${parent.Nominal}
                                ${parent.name}

                                ${sumOfChildrens(parent,parent.id)}

                        `);
                    });
                },
                error: function(data) {
                    alert(data['message']);
                    console.log(data['message']);
                },
            });
        });

Body:
Stackoverflow isn't meant for other people to write code for you, but rather to answer specific questions or help solve problems. Instead of showing more code, explain what you've tried, which behavior you saw vs the one you expected.
That being said, I think the following code snippet might help you clarify your question or even solve the problem on your own.

// for each first level child
data.children.map((item) => {
  // for each next level child
  item.children.map((item2) => {
    // this is the list of transactions
    console.log(item2.transactions);
    let sum = 0;
    // go over each transaction
    item2.transactions.map((transaction) => {
      // debit != null
      if (transaction.debit) {
        sum += parseFloat(transaction.debit);
      }
    });
    // here you could add the sum to the parent
    console.log(sum);
  });
});

Try to edit this code so it works for you and come back if you have more questions.


问:
Docker: The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

```<code>It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.
</code>```

my docker

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]
</code>```

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <!--PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.14.0" /-->
    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>
</code>```

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

答: As the package name indicates it is a windows dependant component. Try running your application on a windows container not linux.</p>

Body:
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.

my docker

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is: