问:
How do I get Phusion Passenger to recognize the correct version of Python for a web application?
I'm trying to set up my first Python web application through Flask. I've used the setup module on my hosting service, and I've hit a problem. When I try to run the app, I get an error page from Phusion Passenger. In the searching I've done so far, similar problems seem to come from Passenger's inability to locate the needed software. But I haven't done this before, so I may well be misunderstanding the problem. All help much appreciated.

Here are the contents of passenger_wsgi.py:

```<code>import imp
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

wsgi = imp.load_source('wsgi', 'flaskblog.py')
application = wsgi.application
</code>```

And here is what the site admin pulled from the error log:

```<code>[ E 2020-05-25 15:09:08.9018 32404/T1q age/Cor/App/Implementation.cpp:221 ]:
Could not spawn process for application /home/eriksimp/public_html/flaskblog: The application process exited prematurely.
App 28117 output:  File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
App 28117 output:  File "/home/eriksimp/public_html/flaskblog/passenger_wsgi.py", line 8, in <module>
App 28117 output:  File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
</code>```

答:
The problem was that I hadn't activated the environment. (I was following instructions that didn't include that step.) I created the app using cPanel, and at the end of the process, cPanel provided a Terminal command (at the top of the page) to activate the app. I entered Terminal through cPanel, ran that command, then ran "pip install flask."

Then I restarted the application and reloaded the page. Now it works!

Body:
I'm trying to set up my first Python web application through Flask. I've used the setup module on my hosting service, and I've hit a problem. When I try to run the app, I get an error page from Phusion Passenger. In the searching I've done so far, similar problems seem to come from Passenger's inability to locate the needed software. But I haven't done this before, so I may well be misunderstanding the problem. All help much appreciated.

Here are the contents of passenger_wsgi.py:

import imp
import os
import sys

sys.path.insert(0, os.path.dirname(__file__))

wsgi = imp.load_source('wsgi', 'flaskblog.py')
application = wsgi.application

And here is what the site admin pulled from the error log:

[ E 2020-05-25 15:09:08.9018 32404/T1q age/Cor/App/Implementation.cpp:221 ]:
Could not spawn process for application /home/eriksimp/public_html/flaskblog: The application process exited prematurely.
App 28117 output:  File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
App 28117 output:  File "/home/eriksimp/public_html/flaskblog/passenger_wsgi.py", line 8, in <module>
App 28117 output:  File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source


来源: stackexchange

问:
HttpClient.PostAsync() request not reaching destination
I am modifying the purchasing process of an e-commerce site, which has the ability to make purchases for multiple users and multiple products with a single purchase. Large purchases can occasionally take several minutes to complete, which the e-commerce site back-end would make the user wait for; not a great UX.

I am trying to make the site generate a JSON string and kick it over to an API which will do the purchase processing on a different server, and let the Site  continue on the the ThankYou page, without waiting for a response from the API.
My challenge is, sometimes the Post doesn't make it to the API. I put a thread.sleep command after the postasync and that seems to fix the issue on my local machine, but I have concerns about the reliability of that solution.

TLDR; my goal is to make the code reliably send posts to an API without awaiting the result. This is something I have struggled with before and if there is a best practice to achieve the result, I have not been able to find it. Any advice would be appreciated.

See post code below; nothing fancy going on. Code lives inside an eventHandler function on the e-commerce back-end.

```<code>using (System.Net.Http.HttpClient client = new HttpClient(new HttpClientHandler(),false))
                {
                    var url = ConfigurationManager.AppSettings["APIURL"];
                    var reqBody = new StringContent(RequestData.ToString(), Encoding.UTF8, "application/json");

                   var task =  client.PostAsync(url, reqBody);

                    //increases chance of post reaching API before function ends
                    Thread.Sleep(3000);
                }
</code>```

答:
reliably send posts to an API without awaiting the result

This isn't possible. Reliable code requires await. Calling asynchronous methods without awaiting them is a form of "fire and forget", and by definition fire-and-forget code does not care if (or whether) the operation completes.

One alternative approach that may work for you is to have a reliable queue and write to that instead of to the API. Then have a background processor that reads from that queue and posts to the API.

ContentLicense: CC BY-SA 4.0

Body:
I am modifying the purchasing process of an e-commerce site, which has the ability to make purchases for multiple users and multiple products with a single purchase. Large purchases can occasionally take several minutes to complete, which the e-commerce site back-end would make the user wait for; not a great UX.

I am trying to make the site generate a JSON string and kick it over to an API which will do the purchase processing on a different server, and let the Site  continue on the the ThankYou page, without waiting for a response from the API.
My challenge is, sometimes the Post doesn't make it to the API. I put a thread.sleep command after the postasync and that seems to fix the issue on my local machine, but I have concerns about the reliability of that solution.

TLDR; my goal is to make the code reliably send posts to an API without awaiting the result. This is something I have struggled with before and if there is a best practice to achieve the result, I have not been able to find it. Any advice would be appreciated.

See post code below; nothing fancy going on. Code lives inside an eventHandler function on the e-commerce back-end.

using (System.Net.Http.HttpClient client = new HttpClient(new HttpClientHandler(),false))
                {
                    var url = ConfigurationManager.AppSettings["APIURL"];
                    var reqBody = new StringContent(RequestData.ToString(), Encoding.UTF8, "application/json");

                   var task =  client.PostAsync(url, reqBody);

                    //increases chance of post reaching API before function ends
                    Thread.Sleep(3000);
                }


问:
I used turtle in python to make an bad design generator
So i made a simple input(), slapped in a background with bgpic, and made so that the thing user wrote in input will work as text on the window, and it works. Is there any way so i can save the contents of the window to my pc without screenshots and cropping it?</p>

答:
I just had a rollercoaster of discovery with this exact problem! I ended up using the properties of turtle as a tkinter canvas to save it to a postscript. Then I used Pillow to convert the .ps to a .png.
Here is the code I ended with:

```<code>import turtle
from PIL import Image

t = turtle.Turtle()
draw_stuff()

# Save as a postscript:
canvas = t.getscreen().getcanvas()
canvas.postscript(file="myfile.ps")

# Convert to a png:
img = Image.open('myfile.ps')
img.save('myfile.png')
</code>```

For further information here are my posted questions:
This shows how to convert it to a .ps:

How can I save a Turtle object (turtle.py) as a .png or .jpg in Python 3?

This shows how to convert it to a .png using PIL. NOTE: If you go to this link and look at the pictures, you should see an error just like the one you got.

How can I convert a .ps file into a .png file?

Feel free to ask any questions, especially about any problems you encounter with Ghostscript or PATH. Hope this helps!

How to fix the OS Error: Ghostscript not found in paths:
First. make sure you've downloaded ghostscript. Here is the link to download the most recent version:

https://www.ghostscript.com/download/gsdnld.html

Once downloaded, go to your file explorer then open
C:\Windows\Program Files (x86)\gs.  (You may have to click view then check the hidden files box at the top of the interface) Then open gs9.52 and click the folder "bin". Copy the file path, it should be:

C:\Program Files (x86)\gs\gs9.52\bin

Last step- you need to add that file path to your system's PATH. Here is a great article, just follow these instructions:

https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/

Once you add the file path to your system's PATH, you may need to restart your PC before it works. Then run the code you wrote using Pillow and the error should be gone. Let me know if there are any more problems.

Body:
I just had a rollercoaster of discovery with this exact problem! I ended up using the properties of turtle as a tkinter canvas to save it to a postscript. Then I used Pillow to convert the .ps to a .png.
Here is the code I ended with:

import turtle
from PIL import Image

t = turtle.Turtle()
draw_stuff()

# Save as a postscript:
canvas = t.getscreen().getcanvas()
canvas.postscript(file="myfile.ps")

# Convert to a png:
img = Image.open('myfile.ps')
img.save('myfile.png')

For further information here are my posted questions:
This shows how to convert it to a .ps:

How can I save a Turtle object (turtle.py) as a .png or .jpg in Python 3?

This shows how to convert it to a .png using PIL. NOTE: If you go to this link and look at the pictures, you should see an error just like the one you got.

How can I convert a .ps file into a .png file?

Feel free to ask any questions, especially about any problems you encounter with Ghostscript or PATH. Hope this helps!

How to fix the OS Error: Ghostscript not found in paths:
First. make sure you've downloaded ghostscript. Here is the link to download the most recent version:

https://www.ghostscript.com/download/gsdnld.html

Once downloaded, go to your file explorer then open
C:\Windows\Program Files (x86)\gs.  (You may have to click view then check the hidden files box at the top of the interface) Then open gs9.52 and click the folder "bin". Copy the file path, it should be:

C:\Program Files (x86)\gs\gs9.52\bin

Last step- you need to add that file path to your system's PATH. Here is a great article, just follow these instructions:

https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/

Once you add the file path to your system's PATH, you may need to restart your PC before it works. Then run the code you wrote using Pillow and the error should be gone. Let me know if there are any more problems.


问:
Enterprise Library 4.1 logging timestamp how to display millisecond
The following is in config file.

```<code> <formatters>
      <add template="{timestamp} {severity} {category} {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="SingleLineFormatter" />
 </formatters>
</code>```

which displays

31/05/2011 11:43:24 Information ...

But there is no millisecond displayed which would be useful for perf instrumentation, anyone knows how to display?  Thanks.

答:
You can specify  Standard or  Custom DateTime Format strings to the timestamp template token:

```<code><formatters>
      <add
        template="{timestamp(MM/dd/yyyy HH:mm:ss.fffffff)} {severity} {category} {message}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="SingleLineFormatter" />
 </formatters>
</code>```

This would output something like:

06/01/2011 20:12:43.3405776
  Information General This is the
  message

By default the DateTime will be in UTC time.  If you wish to use local time then prefix the format string with "local:".  e.g. {timestamp(local:MM/dd/yyyy HH:mm:ss.fffffff)}

Also, if you are looking to log performance tracing of method entries and exits you may want to look at the Tracer class.

ContentLicense: CC BY-SA 3.0

Body:
The following is in config file.

 <formatters>
      <add template="{timestamp} {severity} {category} {message}" type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="SingleLineFormatter" />
 </formatters>

which displays

31/05/2011 11:43:24 Information ...

But there is no millisecond displayed which would be useful for perf instrumentation, anyone knows how to display?  Thanks.

Body:
You can specify  Standard or  Custom DateTime Format strings to the timestamp template token:

<formatters>
      <add
        template="{timestamp(MM/dd/yyyy HH:mm:ss.fffffff)} {severity} {category} {message}"
        type="Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
        name="SingleLineFormatter" />
 </formatters>

This would output something like:

06/01/2011 20:12:43.3405776
  Information General This is the
  message

By default the DateTime will be in UTC time.  If you wish to use local time then prefix the format string with "local:".  e.g. {timestamp(local:MM/dd/yyyy HH:mm:ss.fffffff)}

Also, if you are looking to log performance tracing of method entries and exits you may want to look at the Tracer class.


问:
What is the Debian equivalent of urw-fonts (needed for utf-8 in wkhtmltopdf)?
I'm trying to convert an html document with text in multiple languages (utf-8 encoding) to pdf using wkhtmltopdf, and ran into the exact issue described here:

Squared characters issue on wkhtmltopdf

The most popular answers there are to install urw-fonts, which seems to have worked for many people with this issue. But when I search for this package in the Debian apt repository, it doesn't find anything. Someone suggested installing gsfonts-x11, but that didn't fix the issue.

My question is:

Is there a similar/equivalent Debian font package that can be used by wkhtmltopdf to correctly render utf-8 fonts?

Thanks!

答:
Getting other languages rendering in wkhtmltopdf:

created a folder: /path/to/downloaded/fonts

create fonts.conf (see below)

```<code>/path/to/downloaded/fonts/fonts.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/path/to/downloaded/fonts/</dir>
  <cachedir>/tmp/fonts-cache/</cachedir>
  <config></config>
</fontconfig>
</code>```

downloaded Google's Noto fonts into /var/task/fonts. For each language you need, you can download its associated language ttf files.

Set your ENV variables:
FONT_CONFIG_PATH=/path/to/downloaded/fonts/ and FONTCONFIG_FILE=/path/to/downloaded/fonts/fonts.conf

In the target HTML file, set the meta tag in the head of the document:

```<code><head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
</code>```

You may find that you need to add additional fonts, but they are found on the the
Google Noto Site. I used all the *-regular.ttf files to keep my container smaller.

If you happen to be doing this in AWS / amazonlinux2, you also need to set:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/wkhtmltopdf;
You can confirm that the libaries are mapped correctly with:
ldd /path/to/wkhtmltopdf
Your result should look like this:

```<code>        linux-vdso.so.1 (0x00007ffc7f5cf000)
        libXrender.so.1 => /var/task/lib/libXrender.so.1 (0x00007f1ea6db1000)
        libfontconfig.so.1 => /var/task/lib/libfontconfig.so.1 (0x00007f1ea6b74000)
        libfreetype.so.6 => /var/task/lib/libfreetype.so.6 (0x00007f1ea68d0000)
        libXext.so.6 => /var/task/lib/libXext.so.6 (0x00007f1ea66be000)
        libX11.so.6 => /var/task/lib/libX11.so.6 (0x00007f1ea6380000)
        libz.so.1 => /lib64/libz.so.1 (0x00007f1ea616b000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f1ea5f67000)
        librt.so.1 => /lib64/librt.so.1 (0x00007f1ea5d5f000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f1ea5b41000)
        libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f1ea57bf000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f1ea547f000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f1ea5269000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f1ea4ebe000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f1ea6fbb000)
        libexpat.so.1 => /var/task/lib/libexpat.so.1 (0x00007f1ea4c8c000)
        libxcb.so.1 => /var/task/lib/libxcb.so.1 (0x00007f1ea4a64000)
        libXau.so.6 => /var/task/lib/libXau.so.6 (0x00007f1ea4860000)
        linux-vdso.so.1 (0x00007ffce59b0000)
</code>```

If the path is wrong, it'll look like this:

```<code>        libXrender.so.1 => not found
        libfontconfig.so.1 => not found
        libfreetype.so.6 => not found
        libXext.so.6 => not found
        libX11.so.6 => not found
        libz.so.1 => /lib64/libz.so.1 (0x00007f2f1fed9000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f2f1fcd5000)
        librt.so.1 => /lib64/librt.so.1 (0x00007f2f1facd000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f2f1f8af000)
        libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f2f1f52d000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f2f1f1ed000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f2f1efd7000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f2f1ec2c000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f2f200ee000)
</code>```

Body:
Getting other languages rendering in wkhtmltopdf:

created a folder: /path/to/downloaded/fonts

create fonts.conf (see below)

/path/to/downloaded/fonts/fonts.conf
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
  <dir>/path/to/downloaded/fonts/</dir>
  <cachedir>/tmp/fonts-cache/</cachedir>
  <config></config>
</fontconfig>

downloaded Google's Noto fonts into /var/task/fonts. For each language you need, you can download its associated language ttf files.

Set your ENV variables:
FONT_CONFIG_PATH=/path/to/downloaded/fonts/ and FONTCONFIG_FILE=/path/to/downloaded/fonts/fonts.conf

In the target HTML file, set the meta tag in the head of the document:

<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>

You may find that you need to add additional fonts, but they are found on the the
Google Noto Site. I used all the *-regular.ttf files to keep my container smaller.

If you happen to be doing this in AWS / amazonlinux2, you also need to set:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/wkhtmltopdf;
You can confirm that the libaries are mapped correctly with:
ldd /path/to/wkhtmltopdf
Your result should look like this:

        linux-vdso.so.1 (0x00007ffc7f5cf000)
        libXrender.so.1 => /var/task/lib/libXrender.so.1 (0x00007f1ea6db1000)
        libfontconfig.so.1 => /var/task/lib/libfontconfig.so.1 (0x00007f1ea6b74000)
        libfreetype.so.6 => /var/task/lib/libfreetype.so.6 (0x00007f1ea68d0000)
        libXext.so.6 => /var/task/lib/libXext.so.6 (0x00007f1ea66be000)
        libX11.so.6 => /var/task/lib/libX11.so.6 (0x00007f1ea6380000)
        libz.so.1 => /lib64/libz.so.1 (0x00007f1ea616b000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f1ea5f67000)
        librt.so.1 => /lib64/librt.so.1 (0x00007f1ea5d5f000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f1ea5b41000)
        libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f1ea57bf000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f1ea547f000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f1ea5269000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f1ea4ebe000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f1ea6fbb000)
        libexpat.so.1 => /var/task/lib/libexpat.so.1 (0x00007f1ea4c8c000)
        libxcb.so.1 => /var/task/lib/libxcb.so.1 (0x00007f1ea4a64000)
        libXau.so.6 => /var/task/lib/libXau.so.6 (0x00007f1ea4860000)
        linux-vdso.so.1 (0x00007ffce59b0000)

If the path is wrong, it'll look like this:

        libXrender.so.1 => not found
        libfontconfig.so.1 => not found
        libfreetype.so.6 => not found
        libXext.so.6 => not found
        libX11.so.6 => not found
        libz.so.1 => /lib64/libz.so.1 (0x00007f2f1fed9000)
        libdl.so.2 => /lib64/libdl.so.2 (0x00007f2f1fcd5000)
        librt.so.1 => /lib64/librt.so.1 (0x00007f2f1facd000)
        libpthread.so.0 => /lib64/libpthread.so.0 (0x00007f2f1f8af000)
        libstdc++.so.6 => /lib64/libstdc++.so.6 (0x00007f2f1f52d000)
        libm.so.6 => /lib64/libm.so.6 (0x00007f2f1f1ed000)
        libgcc_s.so.1 => /lib64/libgcc_s.so.1 (0x00007f2f1efd7000)
        libc.so.6 => /lib64/libc.so.6 (0x00007f2f1ec2c000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f2f200ee000)


问:
Group and sum by week
I have a dataframe where the columns are by day in this format:

```<code>a    b    c     01/01/2020  01/02/2020  01/03/2020 ...
1000 2000 3000  2           5           7
.
.
.
</code>```

These are just arbitrary values. What I want is to sum the date columns and group them by week, like week_1, week_2,... so on and so forth. So for the example above it would look like:

```<code>a    b    c     week_1...
1000 2000 3000  14
.
.
.
</code>```

Is there a clean way to do it for columns? I know I can sum all the columns by selecting the date columns and summing them on the axis, but I'm not sure how to do it per week. Any help is appreciated!

答: try .stack or .melt to get columns on to rows and dt.week to get the week number. then do a groupby. Here is a post for week number: converting a pandas date to week number

Title: Group and sum by week

Body:
I have a dataframe where the columns are by day in this format:

a    b    c     01/01/2020  01/02/2020  01/03/2020 ...
1000 2000 3000  2           5           7
.
.
.

These are just arbitrary values. What I want is to sum the date columns and group them by week, like week_1, week_2,... so on and so forth. So for the example above it would look like:

a    b    c     week_1...
1000 2000 3000  14
.
.
.

Is there a clean way to do it for columns? I know I can sum all the columns by selecting the date columns and summing them on the axis, but I'm not sure how to do it per week. Any help is appreciated!


问:
Align text in center in css in mobile using media screen
i am trying to center align the text on mobile but it's not working.

here is the code

@media screen and (max-width: 100px) {
  .info1{

    width: 100px;
  height: 100px;
  margin: 0 auto;

  }
}  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div class="info1">
      <p style=" display:inline-block; "> Contact : +97252387
 ,  </p>
   <p style=" display:inline-block; ">Dizengoff square 85 Tel Aviv</p>
  </div></code>```

text-align is also no working

答:
Your centering is not working because your media query is

```<code>@media screen and (max-width: 100px) {...
</code>```

so it is probably working under 100px. But I am guessing you meant 1000px?

EDIT: here are 2 working examples:

@media screen and (max-width: 1000px) {
  .info1{

    width: 100px;
  height: 100px;
  margin: 0 auto;

  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="info1">
      <p style=" display:inline-block; "> Contact : +97252387
 ,  </p>
   <p style=" display:inline-block; ">Dizengoff square 85 Tel Aviv</p>
  </div></code>```

@media screen and (max-width: 1000px) {
  .info1 {
  display:flex;
  flex-direction: column;
  align-items: center;

  }
  .info1 > p {
    width: 100px;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="info1">
      <p style=" display:inline-block; "> Contact : +97252387
 ,  </p>
   <p style=" display:inline-block; ">Dizengoff square 85 Tel Aviv</p>
  </div></code>```

for the last example please note you can remove

```<code>.info1 > p {
    width: 100px;
}
</code>```

if you don't want fixed width.

Body:
i am trying to center align the text on mobile but it's not working.

here is the code

@media screen and (max-width: 100px) {
  .info1{

    width: 100px;
  height: 100px;
  margin: 0 auto;

  }
}

 Contact : +97252387
 ,

Dizengoff square 85 Tel Aviv

text-align is also no working

Body:
Your centering is not working because your media query is

@media screen and (max-width: 100px) {...

so it is probably working under 100px. But I am guessing you meant 1000px?

EDIT: here are 2 working examples:

@media screen and (max-width: 1000px) {
  .info1{

    width: 100px;
  height: 100px;
  margin: 0 auto;

  }
}

<div class="info1">
      <p style=" display:inline-block; "> Contact : +97252387
 ,  </p>
   <p style=" display:inline-block; ">Dizengoff square 85 Tel Aviv</p>
  </div>

@media screen and (max-width: 1000px) {
  .info1 {
  display:flex;
  flex-direction: column;
  align-items: center;

  }
  .info1 > p {
    width: 100px;
  }
}

<div class="info1">
      <p style=" display:inline-block; "> Contact : +97252387
 ,  </p>
   <p style=" display:inline-block; ">Dizengoff square 85 Tel Aviv</p>
  </div>

for the last example please note you can remove

.info1 > p {
    width: 100px;
}

if you don't want fixed width.


问:
Scheduling a composed task with arguments
I have those two tasks defined in Spring Cloud Dataflow, for sake of simplicity I'll simply call them first-task and second-task. Then I define a composed task:

```<code>task create --name my-composed-task --definition "first-task && second-task"
</code>```

Now, I need to schedule this task, but I need that the scheduled task starts with two arguments, let's say that those arguments are OBJECT_TYPES=1 and SKIP_EXTRA_STUFF=true. So I try to setup my schedule:

```<code>task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments 'OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true'
</code>```

But when the schedule starts, the second task fails because those arguments are mandatory. I also tried to change the schedule definition like this:

```<code>task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments "--composed-task-arguments='OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true'"
</code>```

but still the arguments are not passed across children tasks. Can someone tell me what's wrong with those definitions?

答:
For Composed Tasks, you can pass the arguments to the child tasks using the property key --composedTaskArguments. For instance,

you can do something like this:

```<code>task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments "--composedTaskArguments=\"OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true\""

</code>```

Also, note that the values specified by --composedTaskArguments are passed to all the child tasks. The ability to pass the arguments to a specific child task of a composed task has just been added to SCDF as well.

Body:
I have those two tasks defined in Spring Cloud Dataflow, for sake of simplicity I'll simply call them first-task and second-task. Then I define a composed task:

task create --name my-composed-task --definition "first-task && second-task"

Now, I need to schedule this task, but I need that the scheduled task starts with two arguments, let's say that those arguments are OBJECT_TYPES=1 and SKIP_EXTRA_STUFF=true. So I try to setup my schedule:

task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments 'OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true'

But when the schedule starts, the second task fails because those arguments are mandatory. I also tried to change the schedule definition like this:

task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments "--composed-task-arguments='OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true'"

but still the arguments are not passed across children tasks. Can someone tell me what's wrong with those definitions?

Body:
For Composed Tasks, you can pass the arguments to the child tasks using the property key --composedTaskArguments. For instance,

you can do something like this:

task schedule create --definitionName my-composed-task --name my-scheduled-task --expression '0 5 4 * ?' --arguments "--composedTaskArguments=\"OBJECT_TYPES=1 SKIP_EXTRA_STUFF=true\""

Also, note that the values specified by --composedTaskArguments are passed to all the child tasks. The ability to pass the arguments to a specific child task of a composed task has just been added to SCDF as well.


问:
Convert basic array to PHP array
I have an array that I pull that looks like this:

[157966745,275000353,43192565,305328212]...

How do I go about taking that "string" and converting it to a PHP array which I can then manipulate.

Title: Convert basic array to PHP array

Body:
preg_replace('/([\[|\]])/','',$strarr);
$new_arr=explode(','$strarr);


问:
How to check build variant inside the module's build.gradle
I have the following modules in my project:

```<code>MyProject
 - app  // the usual module that contains the java codes
 - theLibraryModule  // this is the module in question
   - theLibraryDebug.aar
   - theLibraryRelease.aar
   - build.gradle
</code>```

The theLibraryModule's build.gradle is below:

```<code>configurations.maybeCreate("default")
artifacts.add("default", file('theLibraryDebug.aar'))
</code>```

Is there a way to check the build variant (debug/release) I am using and load the proper AAR in my theLibraryModule module?

答:
Check this code to check the Build variant in your Gradle.

```<code>    // Customize your APK name here
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def appId = variant.applicationId// com.exampleFree.app OR com.examplePaid.app
            def versionName = variant.versionName
            def versionCode = variant.versionCode // e.g 1.0
            def flavorName = variant.flavorName // e. g. Free
            def buildType = variant.buildType.name // e. g. debug
            def variantName = variant.name // e. g. FreeDebug

            //customize your app name by using variables
            outputFileName = "${buildType}.apk"
        }
    }
</code>```

For  More

Body:
I have the following modules in my project:

MyProject
 - app  // the usual module that contains the java codes
 - theLibraryModule  // this is the module in question
   - theLibraryDebug.aar
   - theLibraryRelease.aar
   - build.gradle

The theLibraryModule's build.gradle is below:

configurations.maybeCreate("default")
artifacts.add("default", file('theLibraryDebug.aar'))

Is there a way to check the build variant (debug/release) I am using and load the proper AAR in my theLibraryModule module?

Body:
Check this code to check the Build variant in your Gradle.

    // Customize your APK name here
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def appId = variant.applicationId// com.exampleFree.app OR com.examplePaid.app
            def versionName = variant.versionName
            def versionCode = variant.versionCode // e.g 1.0
            def flavorName = variant.flavorName // e. g. Free
            def buildType = variant.buildType.name // e. g. debug
            def variantName = variant.name // e. g. FreeDebug

            //customize your app name by using variables
            outputFileName = "${buildType}.apk"
        }
    }

For  More


问:
PIXI.JS Newbie, looking for advice and troubleshoot of a textureCache, loader issue
ive ventured into the world of PIXI and JS, new programming language for me, liking the way it is right now but i have an issue.

I am a bit confused with the TextureCache and the loader. If you look at part of my code i try to add 3 different images to the screen. Ive been following the 'Get Started section' of the pixi website. I wanted to add their cat image, which i have, the tileset image (all of it)* and then a tile of the tileset image.

The issue is, i create 3 new sprite instances and the tileset image shows the area ive set for the tile(rocket) when i want it to show the whole tileset. Ive loaded in the tileset iin the cahce and the loader.

Why does tile show the cropped image and not the whole image?

Am i using the cache correctly to just store images?

Am i using the resources method properly to locate the image FROM the cache or the loader?

Is there any point of the cache?

my thoughts**
when you use the rectangle method, it destroys the original image and the cropped version is now tileset1 (the name of my image)?

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.2.4/pixi.js"></script></code>```

答:
Is there any point of the cache? - this question seems to be most important from your questions :)

Searching around about "pixi.js" and "TextureCache" gives following answers for example:

https://github.com/pixijs/pixi.js/issues/4053

MySecret commented on May 23, 2017:

the docs has no specs about PIXI.utils.TextureCache

...

englercj commented on May 26, 2017

This is intentional, it is not meant as a public-facing API. It is an internal cache used by some texture creation methods.

https://www.html5gamedevs.com/topic/17788-loader-and-texturecache-tutorial-anywhere/

xerver - Pixi.js Moderator:

Here is the loader: https://github.com/englercj/resource-loader

The code is really well documented, and there are examples on the readme. The pixi examples also use the loader a few times: http://pixijs.github.io/examples/

The TextureCache is an internal mechanism, there is rarely any reason you should even know it exists.

https://www.html5gamedevs.com/topic/25575-pixiloaderresources-or-texturecache/

xerver - Pixi.js Moderator:

Dont do this:

let e = PIXI.utils.TextureCache[player.img];

Instead use the resources the loader loaded for you:

let e = PIXI.loader.resources[player.img].texture;

...

TLDR: Usually TextureCache shouldnt be used directly :)

See also:

this explanation: https://www.html5gamedevs.com/topic/9255-pixijs-caching/?tab=comments#comment-55233

http://pixijs.download/release/docs/PIXI.BaseTexture.html#.addToCache

^ example of usage: https://jsfiddle.net/themoonrat/br35x20j/


问:
How to consume tap events for Map in CollapsingToolbar
I want to put a MapWidget into a FlexibleSpaceBar (inside a SliverAppBar inside a NestedScrollView) to show it in a Collapsable Toolbar. My widget tree looks like this:

```<code>Scaffold
 |
 |- NestedScrollView
     |
     |- SliverAppBar
     |   |
     |   |- FlexibleSpaceBar
     |       |
     |       |- Map
     |
     |- ListView
</code>```

The problem is that the NestedScrollViewconsumes all the Gesture events and I cannot use pinch-to-zoom any more on the Map. What's the best way to solve this?

Here's some code:

```<code>class ListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<int> list = List<int>.generate(10, (i) => i + 1);
    return NestedScrollView(
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          SliverAppBar(
              expandedHeight: 250.0,
              floating: true,
              pinned: true,
              snap: false,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('Second Screen'),
                background: MapWidget(),
              )),
        ];
      },
      body: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          int item = list[index];
          return Text('item $item');
        },
      ),
    );
  }
}
</code>```

答:
If you are using GoogleMap as your MapWidget, perhaps this can help:

```<code>gestureRecognizers: Set()
  ..add(Factory<PanGestureRecognizer>(() => PanGestureRecognizer()))
  ..add(Factory<VerticalDragGestureRecognizer>(
      () => VerticalDragGestureRecognizer())),
</code>```

With this you can use pan and drag gestures inside your Map Widget.

I looked a bit through the other gesture recognizer options, the closest thing to pinch-to-zoom was ScaleGestureRecognizer but I didn't test it.

Body:
I want to put a MapWidget into a FlexibleSpaceBar (inside a SliverAppBar inside a NestedScrollView) to show it in a Collapsable Toolbar. My widget tree looks like this:

Scaffold
 |
 |- NestedScrollView
     |
     |- SliverAppBar
     |   |
     |   |- FlexibleSpaceBar
     |       |
     |       |- Map
     |
     |- ListView

The problem is that the NestedScrollViewconsumes all the Gesture events and I cannot use pinch-to-zoom any more on the Map. What's the best way to solve this?

Here's some code:

class ListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    List<int> list = List<int>.generate(10, (i) => i + 1);
    return NestedScrollView(
      headerSliverBuilder: (context, innerBoxIsScrolled) {
        return [
          SliverAppBar(
              expandedHeight: 250.0,
              floating: true,
              pinned: true,
              snap: false,
              flexibleSpace: FlexibleSpaceBar(
                title: Text('Second Screen'),
                background: MapWidget(),
              )),
        ];
      },
      body: ListView.builder(
        itemCount: list.length,
        itemBuilder: (context, index) {
          int item = list[index];
          return Text('item $item');
        },
      ),
    );
  }
}

Body:
If you are using GoogleMap as your MapWidget, perhaps this can help:

gestureRecognizers: Set()
  ..add(Factory<PanGestureRecognizer>(() => PanGestureRecognizer()))
  ..add(Factory<VerticalDragGestureRecognizer>(
      () => VerticalDragGestureRecognizer())),

With this you can use pan and drag gestures inside your Map Widget.

I looked a bit through the other gesture recognizer options, the closest thing to pinch-to-zoom was ScaleGestureRecognizer but I didn't test it.


问:
HTTP REST: If a request is idempotent, but the resource is unchangeable once inserted, should PUT or POST be used?
Imagine an HTTP REST endpoint, where a resource is inserted, and that the resource is understood to be a "message".  Each individual message is identified by a unique identifier, such as a GUID value of some sort.  The same message cannot be duplicated.

Now, in a lot of cases, that would lend itself to the PUT verb, since it's idempotent.  However consider the following scenario:

```<code>1. The sender sends this message to the receiver:

    {
        "id": 123,
        "text": "original text"
    }

2. Now the receiver has this value for the message stored in its database:

    {
        "id": 123,
        "text": "original text"
    }

3. For whatever reason, the sender tries to send the same message again, but with amended
   text:

    {
        "id": 123,
        "text": "amended text"
    }

4. The receiver receives that as well, but since the id field is the same as before, no
   action is taken, and this is what the receiver still has in its database:

    {
        "id": 123,
        "text": "original text"
    }
</code>```

The reason for the receiver's behavior is that each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.  Furthermore, trying to change the message's contents like that and resend it with the same ID is invalid behavior on the sender's end.

So technically this is idempotent, which usually leans toward PUT.  However updates are not allowed in any context here, simply inserts.  So do we choose PUT or POST, or does it even matter?  PUT is supposed to be the full representation of the resource, but if it's simply discarded, is it okay to still return a 2xx response?

For the purposes of this question, assume that the route used is always of the form <host>/.../message, never of the form <host>/.../message/{id}.  In that case, I am wondering if being restricted to the <host>/.../message route scheme automatically means POST should be used.

答:
Now, in a lot of cases, that would lend itself to the POST verb, since it's idempotent.

This might be a typo on your end, but POST is NOT idempotent. However PUT is.

PUT is supposed to be the full representation of the resource, but if it's simply discarded, is it okay to still return a 2xx response?

Totally fine. You requested that a resource with a given id have a given state, and that will be true when the response is sent back.

So do we choose PUT or POST, or does it even matter?

I would say good options are

PUT /messages/{id}, 201 if the id is new, 204 if the message has the same text as the existing message, 4xx if the text is not the same as the existing message

POST /messages, 201 if the id is new, 4xx if the id already exists

With the PUT the client can see "oh, 2xx, message delivered", or "4xx, I messed up". But you have to have some mechanism (maybe a fingerprint) to quickly check if the text is the same as the initial message.

With the POST the client would need to inspect an error response to see if they needed to fix something and try again, or if the message was already delivered. If we returned a 2xx (other than 202) from our POST of an existing message, most clients would interpret that to mean that a new (duplicate) message had been sent.

assume that the route used is always of the form <host>/.../message, never of the form <host>/.../message/{id}

An unfortunate requirement, in that case I would use POST as described above. We technically could use PUT with that path, but typically that would signal that we want to create/replace the entire message history (you could document around it, but operations that don't do what they look like they should are not typically considered RESTfull).

Body:
Imagine an HTTP REST endpoint, where a resource is inserted, and that the resource is understood to be a "message".  Each individual message is identified by a unique identifier, such as a GUID value of some sort.  The same message cannot be duplicated.

Now, in a lot of cases, that would lend itself to the PUT verb, since it's idempotent.  However consider the following scenario:

1. The sender sends this message to the receiver:

    {
        "id": 123,
        "text": "original text"
    }

2. Now the receiver has this value for the message stored in its database:

    {
        "id": 123,
        "text": "original text"
    }

3. For whatever reason, the sender tries to send the same message again, but with amended
   text:

    {
        "id": 123,
        "text": "amended text"
    }

4. The receiver receives that as well, but since the id field is the same as before, no
   action is taken, and this is what the receiver still has in its database:

    {
        "id": 123,
        "text": "original text"
    }

The reason for the receiver's behavior is that each distinct message is to be uniquely identified by its id field, and that if another message is sent with the same id, it is simply considered a duplicate.  Furthermore, trying to change the message's contents like that and resend it with the same ID is invalid behavior on the sender's end.

So technically this is idempotent, which usually leans toward PUT.  However updates are not allowed in any context here, simply inserts.  So do we choose PUT or POST, or does it even matter?  PUT is supposed to be the full representation of the resource, but if it's simply discarded, is it okay to still return a 2xx response?

For the purposes of this question, assume that the route used is always of the form <host>/.../message, never of the form <host>/.../message/{id}.  In that case, I am wondering if being restricted to the <host>/.../message route scheme automatically means POST should be used.


问:
Web accessibility - focus items
I am working on a website, making it accessible. But I am having some trouble with the voice reader focus going into the items located in the footer.
I tried using aria-label but it didn't work.
I'll attach an image.
The elements enter focus, which I can tell because of the blue ring around the item, but I don't know how to get the orange ring to focus to those anchor elements in the footer.
<img src="https://i.stack.imgur.com/OZbVl.jpg" alt="voice over focus in the element above while the regular focus is in the item in the footer"> </p>

答:
The problem was created due to the use of "fontawesome.com" for the social media Icons. In order to include an alternative text or label to the element (provide by fontawesome.com) you need to use a different method: In my specific case this solved it:

```<code><a href="https://www.instagram.com/iamthonystark/" aria-label="Instagram">
<i aria-hidden="true" class="fab fa-instagram fa-3x"></i>
</a>
</code>```

Here is the link to this solution and the solution to other possible issues related to accessibility and fontawesome.com

https://fontawesome.com/how-to-use/on-the-web/other-topics/accessibility

Title: Web accessibility - focus items

Body:
The problem was created due to the use of "fontawesome.com" for the social media Icons. In order to include an alternative text or label to the element (provide by fontawesome.com) you need to use a different method: In my specific case this solved it:

<a href="https://www.instagram.com/iamthonystark/" aria-label="Instagram">
<i aria-hidden="true" class="fab fa-instagram fa-3x"></i>
</a>

Here is the link to this solution and the solution to other possible issues related to accessibility and fontawesome.com

https://fontawesome.com/how-to-use/on-the-web/other-topics/accessibility


问:
Scrape Genius Lyrics
So I have to do a project for school, I need to create a simple website who uses an API. I want to use the genius API to collect the lyrics but you can't because of copyright. I can only use the API to find certain information about a song like creator, url of the cover{image}, or song link (genius). So if I want to get the lyrics I need to scrape the link of the song. I have some problems with scraping because it's usually accomplished with node.js and I can't use node.js because it's not allowed in the project.

Do anybody have an idea how to scrape this link to find the lyrics only with pure javascript (i can also use jQuery): https://genius.com/Lil-peep-white-tee-lyrics

I know that the html page contain a tag  and all the lyrics are here.

Example :

```<code><div class="lyrics">
   <p> This is the lyrics</p>
</div>
</code>```

If anybody has an idea it would be very helpful. Thanks

答:
The problem you are running into is actually a fairly common issue in programming. It's easy to underestimate the complexity of a system before getting down to implementing it, or to find that a platform is not capable of handling the task you need it to. In these cases, you need to be able to do one of two things, either redefine the system you're building, or expand the framework you're building it on.

You said this is for a school assignment where the objective is to consume an api. My first step would be to talk to your instructor to see if the project's goals can be redefined to only include the information provided through the api.
If getting the lyrics is required, the next attempt should be to find an api that can provide them like this one. https://developer.musixmatch.com/plans.

Scraping webpages should be the last resort.

Title: Scrape Genius Lyrics

Body:
So I have to do a project for school, I need to create a simple website who uses an API. I want to use the genius API to collect the lyrics but you can't because of copyright. I can only use the API to find certain information about a song like creator, url of the cover{image}, or song link (genius). So if I want to get the lyrics I need to scrape the link of the song. I have some problems with scraping because it's usually accomplished with node.js and I can't use node.js because it's not allowed in the project.

Do anybody have an idea how to scrape this link to find the lyrics only with pure javascript (i can also use jQuery): https://genius.com/Lil-peep-white-tee-lyrics

I know that the html page contain a tag  and all the lyrics are here.

Example :

 This is the lyrics

If anybody has an idea it would be very helpful. Thanks


问:
STM32CubeMx: Is it possible to configure ST controllers using SPL(Standard Peripheral Library)
stm32CubeMx software is providing options for configuration only using HAL & LL drivers.Is it possible using Standard Peripheral drivers.

Thank you.

答: You can get the SPL for "older" stm mcus. BUT you shouldn't go out and learn SPL instead of HAL (LL). It isn't supported and won't be added to in future. Invest your time in using the HAL or it's minimal subset. This will offer perspective in  the future.</p>


问:
firebase init command failing to execute
Can someone help me to solve this error  I cannot run firebase init command before running firebase deploy.

Error: Authentication Error: Your credentials are no longer valid. Please run firebase login --reauth

For CI servers and headless environments, generate a new token with firebase login:ci

答:
For such Authentication Error from Firebase CLI.

Do the below steps:

```<code> 1. firebase logout
 2. firebase login
 3. Once the URL opens, go to Google account and remove access which was already given to firebase app distribution ["Remove Access"]
 4. Come back to the URL window and select Allow
 5. Should result in a successful login
</code>```

Even after this repeatedly getting Firebase login CLI issue - suggest restart your system and do firebase login again

Hope this helps!

Body:
For such Authentication Error from Firebase CLI.

Do the below steps:

 1. firebase logout
 2. firebase login
 3. Once the URL opens, go to Google account and remove access which was already given to firebase app distribution ["Remove Access"]
 4. Come back to the URL window and select Allow
 5. Should result in a successful login

Even after this repeatedly getting Firebase login CLI issue - suggest restart your system and do firebase login again

Hope this helps!


问:
Limit replicas per node on Kubernetes
Is there a way to limit the number os replicas per node in Kubernetes? I found some info about Spreading Constraints but didn't understand if this is possible.

Example: I want to have only 1 replica per node on the cluster.

I know that K8S automatically balances the replicas spreading across the nodes, but I want to enforce a specific limit in each node.

Is this possible?

答: The scheduler has many ways to just about everything but in the particular case of 1 replica per node you can use a required mode anti-affinity.

Title: Limit replicas per node on Kubernetes


问:
Issue with Update record in angular?
angular version:
Angular CLI: 9.0.0-rc.7

I want to update a record and when I click on edit icon and then my record is going to form and then I changes some filed of record and then click On Edit Button then My record is update in browser(console log) but not update in database??

backendservice.ts

```<code>       //when I click on edit icon then record going to form

public editpartymaster(PartyMstId) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster?PartyMstId=" + PartyMstId;

             this.httpClient.post<any>(url, options).subscribe(
                (res) => {
                    console.log(res);
                    resolve(res);
                },
                (err) => console.log(err)
            );
        });
    }

    //edit button click event

    public editpartymasterid(PartyMstId, PartyCode, PartyName, Address, PhNo1, SDate, PartyDate, RDType, Exchange) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster";

            const postdata = {
                'PartyMstId': PartyMstId,
                'PartyCode': PartyCode,
                'PartyName': PartyName,
                'Address': Address,
                'PhNo1': PhNo1,
                'SDate': SDate,
                'PartyDate': PartyDate,
                'RDType': RDType,
                'Exchange': Exchange
            }

            console.log("formdata", postdata)

            return this.httpClient.post<any>(url, postdata)
                .subscribe((res) => {
                    console.log("res partyadd add 198", res);
                    resolve(res);
                });
        });
    }
</code>```

partymaster.component.ts

```<code>
    PartyMstId: any;
    PartyCode: any;
    PartyName: any;
    Address: any;
    PhNo1: any;
    SDate: any;
    PartyDate: any;
    RDType: any;
    Exchange: any;
    x: any;
    y: any;
    c: any;
    partylist: any;

   constructor(public myservice: BackendService) {}
//edit icon click event

onGridRowClicked(e: any) {
        if (e.event.target !== undefined) {
            let actionType = e.event.target.getAttribute("data-action-type");
            if (actionType == "edit") {
                console.log("e", e.data.PartyMstId);
                console.log("View edit action clicked");
                this.myservice.editpartymaster(e.data.PartyMstId).then((data: any) => {
                    if (data.message == "your record update") {

                        this.PartyMstId = e.data.PartyMstId;
                        this.PartyCode = e.data.PartyCode;
                        this.PartyName = e.data.PartyName;
                        this.Address = e.data.Address;
                        this.PhNo1 = e.data.PhNo1;
                        this.SDate = e.data.SDate;
                        this.PartyDate = e.data.PartyDate;
                        this.RDType = e.data.RDType;
                        this.Exchange = e.data.Exchange;
                    }
                });
            }
            else if (actionType == "delete") {
                console.log("View delete action clicked");
            }

//edit button click event
    editbuttonclickevent() {
        console.log("---PartyMstId---", this.PartyMstId);
        console.log("---PartyCode---", this.PartyCode);
        console.log("---PartyName---", this.PartyName);
        console.log("---Address---", this.Address);
        console.log("---PhNo1---", this.PhNo1);
        console.log("---SDate---", this.SDate);
        console.log("---PartyDate---", this.PartyDate);
        console.log("---RDType---", this.RDType);
        console.log("---Exchange---", this.Exchange);

        this.myservice.editpartymasterid(this.PartyMstId, this.PartyCode,
            this.PartyName, this.Address, this.PhNo1, this.SDate, this.PartyDate,
            this.RDType, this.Exchange).then((data: any) => {
            console.log("list data")
            if (data.message == "your record update") {
                this.list();
            }
        });
    }

</code>```

partymastercomponent.html

```<code>
<ag-grid-angular style="width: 1000px; height: 500px;"
 (rowClicked)='onGridRowClicked($event)'>
    </ag-grid-angular>

<button type="button" (click)="editbuttonclickevent()">Edit</button>

</code>```

asp.net mvc service

```<code>        public ActionResult EditPatymaster(int PartyMstId)
        {
            var partymst = poly.PartyMsts.Find(PartyMstId);
            partymstmodel partymstupdate = new partymstmodel();

            partymstupdate.PartyCode = partymst.PartyCode;
            partymstupdate.PartyName = partymst.PartyName;
            partymstupdate.Address = partymst.Address;
            partymstupdate.PhNo1 = partymst.PhNo1;
            partymstupdate.SDate = partymst.SDate;
            partymstupdate.PartyDate = partymst.PartyDate;
            partymstupdate.RDType = partymst.RDType;
            return View(partymstupdate);
        }

        [HttpPost]
        public JsonResult EditPatymaster(partymstmodel partymst, int PartyMstId)
        {
            var partymstupdate = poly.PartyMsts.Find(PartyMstId);

            if(partymstupdate!=null)
            {
                partymstupdate.PartyCode = partymst.PartyCode;
                partymstupdate.PartyName = partymst.PartyName;
                partymstupdate.Address = partymst.Address;
                partymstupdate.PhNo1 = partymst.PhNo1;
                partymstupdate.SDate = partymst.SDate;
                partymstupdate.PartyDate = partymst.PartyDate;
                partymstupdate.RDType = partymst.RDType;

                HttpResponseMessage response = staticvariable.client.PutAsJsonAsync("PartyMsts", partymst).Result;

                var data = new
                {
                    message = "your record update",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = new
                {
                    message = "your record not updated",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }
</code>```

problem is my console log is display updated record but my database filed is not update that is my problem??

browserlog:

My record is not update but browser console log is updated?

Thank you for all the help

答:
you should install asp.net cors and also config it in your back end server.it meant you should enable cors like this :

```<code>using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}
</code>```

now you should enable your cors on your controller or method in back end like this

```<code>[EnableCors(origins: "*", headers: "*", methods: "*")]
</code>```

above way does not make any sense with origin * you can know about cors in  this link and custom it

Title: Issue with Update record in angular?

Body:
angular version:
Angular CLI: 9.0.0-rc.7

I want to update a record and when I click on edit icon and then my record is going to form and then I changes some filed of record and then click On Edit Button then My record is update in browser(console log) but not update in database??

backendservice.ts

       //when I click on edit icon then record going to form

public editpartymaster(PartyMstId) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster?PartyMstId=" + PartyMstId;

             this.httpClient.post<any>(url, options).subscribe(
                (res) => {
                    console.log(res);
                    resolve(res);
                },
                (err) => console.log(err)
            );
        });
    }

    //edit button click event

    public editpartymasterid(PartyMstId, PartyCode, PartyName, Address, PhNo1, SDate, PartyDate, RDType, Exchange) {
        return new Promise(resolve => {
            let headers = new HttpHeaders({ 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
            let options = { headers: headers, crossDomain: true, withCredentials: true };

            var url = "http://localhost:000/PartyMsts/EditPatymaster";

            const postdata = {
                'PartyMstId': PartyMstId,
                'PartyCode': PartyCode,
                'PartyName': PartyName,
                'Address': Address,
                'PhNo1': PhNo1,
                'SDate': SDate,
                'PartyDate': PartyDate,
                'RDType': RDType,
                'Exchange': Exchange
            }

            console.log("formdata", postdata)

            return this.httpClient.post<any>(url, postdata)
                .subscribe((res) => {
                    console.log("res partyadd add 198", res);
                    resolve(res);
                });
        });
    }

partymaster.component.ts

    PartyMstId: any;
    PartyCode: any;
    PartyName: any;
    Address: any;
    PhNo1: any;
    SDate: any;
    PartyDate: any;
    RDType: any;
    Exchange: any;
    x: any;
    y: any;
    c: any;
    partylist: any;

   constructor(public myservice: BackendService) {}
//edit icon click event

onGridRowClicked(e: any) {
        if (e.event.target !== undefined) {
            let actionType = e.event.target.getAttribute("data-action-type");
            if (actionType == "edit") {
                console.log("e", e.data.PartyMstId);
                console.log("View edit action clicked");
                this.myservice.editpartymaster(e.data.PartyMstId).then((data: any) => {
                    if (data.message == "your record update") {

                        this.PartyMstId = e.data.PartyMstId;
                        this.PartyCode = e.data.PartyCode;
                        this.PartyName = e.data.PartyName;
                        this.Address = e.data.Address;
                        this.PhNo1 = e.data.PhNo1;
                        this.SDate = e.data.SDate;
                        this.PartyDate = e.data.PartyDate;
                        this.RDType = e.data.RDType;
                        this.Exchange = e.data.Exchange;
                    }
                });
            }
            else if (actionType == "delete") {
                console.log("View delete action clicked");
            }

//edit button click event
    editbuttonclickevent() {
        console.log("---PartyMstId---", this.PartyMstId);
        console.log("---PartyCode---", this.PartyCode);
        console.log("---PartyName---", this.PartyName);
        console.log("---Address---", this.Address);
        console.log("---PhNo1---", this.PhNo1);
        console.log("---SDate---", this.SDate);
        console.log("---PartyDate---", this.PartyDate);
        console.log("---RDType---", this.RDType);
        console.log("---Exchange---", this.Exchange);

        this.myservice.editpartymasterid(this.PartyMstId, this.PartyCode,
            this.PartyName, this.Address, this.PhNo1, this.SDate, this.PartyDate,
            this.RDType, this.Exchange).then((data: any) => {
            console.log("list data")
            if (data.message == "your record update") {
                this.list();
            }
        });
    }

partymastercomponent.html

<ag-grid-angular style="width: 1000px; height: 500px;"
 (rowClicked)='onGridRowClicked($event)'>
    </ag-grid-angular>

<button type="button" (click)="editbuttonclickevent()">Edit</button>

asp.net mvc service

        public ActionResult EditPatymaster(int PartyMstId)
        {
            var partymst = poly.PartyMsts.Find(PartyMstId);
            partymstmodel partymstupdate = new partymstmodel();

            partymstupdate.PartyCode = partymst.PartyCode;
            partymstupdate.PartyName = partymst.PartyName;
            partymstupdate.Address = partymst.Address;
            partymstupdate.PhNo1 = partymst.PhNo1;
            partymstupdate.SDate = partymst.SDate;
            partymstupdate.PartyDate = partymst.PartyDate;
            partymstupdate.RDType = partymst.RDType;
            return View(partymstupdate);
        }

        [HttpPost]
        public JsonResult EditPatymaster(partymstmodel partymst, int PartyMstId)
        {
            var partymstupdate = poly.PartyMsts.Find(PartyMstId);

            if(partymstupdate!=null)
            {
                partymstupdate.PartyCode = partymst.PartyCode;
                partymstupdate.PartyName = partymst.PartyName;
                partymstupdate.Address = partymst.Address;
                partymstupdate.PhNo1 = partymst.PhNo1;
                partymstupdate.SDate = partymst.SDate;
                partymstupdate.PartyDate = partymst.PartyDate;
                partymstupdate.RDType = partymst.RDType;

                HttpResponseMessage response = staticvariable.client.PutAsJsonAsync("PartyMsts", partymst).Result;

                var data = new
                {
                    message = "your record update",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = new
                {
                    message = "your record not updated",
                };
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }

problem is my console log is display updated record but my database filed is not update that is my problem??

browserlog:

My record is not update but browser console log is updated?

Thank you for all the help

Body:
you should install asp.net cors and also config it in your back end server.it meant you should enable cors like this :

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

now you should enable your cors on your controller or method in back end like this

[EnableCors(origins: "*", headers: "*", methods: "*")]

above way does not make any sense with origin * you can know about cors in  this link and custom it


问:
How to plot last Open or Close on current candle as a Circle by checking candle[1] for signal
I have been working on an algorithm for pinescript and I am stuck with some logic relating to hypothetically entering the position.

First of all bullPlot and bearPlot are either true or false which is where the long and short signals are painted on the chart. Relating to my strategy, once a long/short signal is plotted you then wait for price to go beyond the close for long/short depending on red/green candle

How can I create a statement which checks if there is a signal on the previous candle, if true, plot a circle based on last close. This is merely to help with the manual trading side of the algorithm.

example of the chart/algo

example of entry dot

答:
You can create a series that holds your trigger result on each bar.

Then you can just reference the trigger value on the previous bar by using the [1] construct, and plot close[1] on the current bar.

When you don't want a value in a series plotted, you can make it plot the na value, like this:

```<code>signal_on_previous_candle ? previousClose : na
</code>```

The ?: is a ternary operator, which is a shortend if-then-else statement.

The above code can also be written as

```<code>if signal_on_previous_candle
    previousClose
else
    na
</code>```

I think this what you're looking for

```<code>//@version=4
study("bullPlot", overlay=true)

var bool signal_on_candle = false
signal_trigger_time = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 11, 30, 0)

signal_triggered = time == signal_trigger_time

if signal_triggered
    signal_on_candle := true
else
    signal_on_candle := false

signal_on_previous_candle = signal_on_candle[1]

previousClose = close[1]

plot(signal_on_previous_candle ? previousClose : na, title="Dot",style=plot.style_circles, color=color.yellow, linewidth=5)
</code>```

This code could be shorter, but it's for illustration purposes.

Body:
You can create a series that holds your trigger result on each bar.

Then you can just reference the trigger value on the previous bar by using the [1] construct, and plot close[1] on the current bar.

When you don't want a value in a series plotted, you can make it plot the na value, like this:

signal_on_previous_candle ? previousClose : na

The ?: is a ternary operator, which is a shortend if-then-else statement.

The above code can also be written as

if signal_on_previous_candle
    previousClose
else
    na

I think this what you're looking for

//@version=4
study("bullPlot", overlay=true)

var bool signal_on_candle = false
signal_trigger_time = timestamp(year(timenow), month(timenow), dayofmonth(timenow), 11, 30, 0)

signal_triggered = time == signal_trigger_time

if signal_triggered
    signal_on_candle := true
else
    signal_on_candle := false

signal_on_previous_candle = signal_on_candle[1]

previousClose = close[1]

plot(signal_on_previous_candle ? previousClose : na, title="Dot",style=plot.style_circles, color=color.yellow, linewidth=5)

This code could be shorter, but it's for illustration purposes.


答: If you want to ensure that all nodes have single replica on them you can use a DaemonSet.</p>

Title: Limit replicas per node on Kubernetes

Body:
Is there a way to limit the number os replicas per node in Kubernetes? I found some info about Spreading Constraints but didn't understand if this is possible.

Example: I want to have only 1 replica per node on the cluster.

I know that K8S automatically balances the replicas spreading across the nodes, but I want to enforce a specific limit in each node.

Is this possible?


问:
Sort an array to have specific items first in the array
I've got an array as such:

```<code>[{flag: true, other: 1},
 {flag: true, other: 2},
 {flag: false, other: 3},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6},
 {flag: false, other: 7}]
</code>```

I want to have this:

```<code>[{flag: false, other: 3},
 {flag: false, other: 7},
 {flag: true, other: 1},
 {flag: true, other: 2},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6}]
</code>```

Basically I want that if array[2].flag === false (or any other value I choose) the matching element gets placed first in the array, but after previous matching elements.
The elements that do not match, remain in the same order they were in originally.

Order of appearance is important.

How to do this best in JavaScript?

答:
A simpler and more elegant way to do is by building a new array by filtering the old one twice: once filtered by flag: true and once by flag: false. All together it would look like:

```<code>// THE INITIAL ARRAY:
const originalArray = [
    {flag: true, other: 1},
    {flag: true, other: 2},
    {flag: false, other: 3},
    {flag: true, other: 4},
    {flag: true, other: 5},
    {flag: true, other: 6},
    {flag: false, other: 7}
];

// THE SORTED ARRAY:
const sortedArray = [
    ...originalArray.filter(({flag}) => flag),
    ...originalArray.filter(({flag}) => !flag)
];
</code>```

In my opinion it is way easier for a human to read than using comparer or reducer functions, and (based on measurements) it is also a pretty well-performing solution.

A performance comparison:

I saw that the most upvoted answer using arr.reduce() performs around 20x slower than this solution. I used ES6 Console for comparison, feel free to test it yourself too!

Measuring the array.reduce() way:

```<code>const arr = [
  { flag: true, other: 1 },
  { flag: true, other: 2 },
  { flag: false, other: 3 },
  { flag: true, other: 4 },
  { flag: true, other: 5 },
  { flag: true, other: 6 },
  { flag: false, other: 7 }
];

// Lets multiple the array items 11 times to increase the looping process:
new Array(11).fill().forEach(x => arr.push(...arr));

console.time();

const reducedArr = arr.reduce((acc, element) => {
  if (element.flag === false) {
    return [element, ...acc];
  }
  return [...acc, element];
}, []);

console.timeEnd(); // RESULTS: between 285-350ms
</code>```

Measuring the array.filter() way:

```<code>const arr = [
  { flag: true, other: 1 },
  { flag: true, other: 2 },
  { flag: false, other: 3 },
  { flag: true, other: 4 },
  { flag: true, other: 5 },
  { flag: true, other: 6 },
  { flag: false, other: 7 }
];

// Lets multiple the array items 11 times to increase the looping process:
new Array(11).fill().forEach(x => arr.push(...arr));

console.time();

const rebuiltArray = [
  ...arr.filter(x => x.flag),
  ...arr.filter(x => !x.flag)
];

console.timeEnd(); // RESULTS: between 6-20ms
</code>```

Body:
I've got an array as such:

[{flag: true, other: 1},
 {flag: true, other: 2},
 {flag: false, other: 3},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6},
 {flag: false, other: 7}]

I want to have this:

[{flag: false, other: 3},
 {flag: false, other: 7},
 {flag: true, other: 1},
 {flag: true, other: 2},
 {flag: true, other: 4},
 {flag: true, other: 5},
 {flag: true, other: 6}]

Basically I want that if array[2].flag === false (or any other value I choose) the matching element gets placed first in the array, but after previous matching elements.
The elements that do not match, remain in the same order they were in originally.

Order of appearance is important.

How to do this best in JavaScript?

Body:
A simpler and more elegant way to do is by building a new array by filtering the old one twice: once filtered by flag: true and once by flag: false. All together it would look like:

// THE INITIAL ARRAY:
const originalArray = [
    {flag: true, other: 1},
    {flag: true, other: 2},
    {flag: false, other: 3},
    {flag: true, other: 4},
    {flag: true, other: 5},
    {flag: true, other: 6},
    {flag: false, other: 7}
];

// THE SORTED ARRAY:
const sortedArray = [
    ...originalArray.filter(({flag}) => flag),
    ...originalArray.filter(({flag}) => !flag)
];

In my opinion it is way easier for a human to read than using comparer or reducer functions, and (based on measurements) it is also a pretty well-performing solution.

A performance comparison:

I saw that the most upvoted answer using arr.reduce() performs around 20x slower than this solution. I used ES6 Console for comparison, feel free to test it yourself too!

Measuring the array.reduce() way:

const arr = [
  { flag: true, other: 1 },
  { flag: true, other: 2 },
  { flag: false, other: 3 },
  { flag: true, other: 4 },
  { flag: true, other: 5 },
  { flag: true, other: 6 },
  { flag: false, other: 7 }
];

// Lets multiple the array items 11 times to increase the looping process:
new Array(11).fill().forEach(x => arr.push(...arr));

console.time();

const reducedArr = arr.reduce((acc, element) => {
  if (element.flag === false) {
    return [element, ...acc];
  }
  return [...acc, element];
}, []);

console.timeEnd(); // RESULTS: between 285-350ms

Measuring the array.filter() way:

const arr = [
  { flag: true, other: 1 },
  { flag: true, other: 2 },
  { flag: false, other: 3 },
  { flag: true, other: 4 },
  { flag: true, other: 5 },
  { flag: true, other: 6 },
  { flag: false, other: 7 }
];

// Lets multiple the array items 11 times to increase the looping process:
new Array(11).fill().forEach(x => arr.push(...arr));

console.time();

const rebuiltArray = [
  ...arr.filter(x => x.flag),
  ...arr.filter(x => !x.flag)
];

console.timeEnd(); // RESULTS: between 6-20ms


答:
With exact that code...</p>

```<code>$string='[157966745,275000353,43192565,305328212]';
$newString=str_replace(array('[', ']'), '', $string); // remove the brackets
$createArray=explode(',', $newString); // explode the commas to create an array

print_r($createArray);
</code>```

Title: Convert basic array to PHP array

Body:
I have an array that I pull that looks like this:

[157966745,275000353,43192565,305328212]...

How do I go about taking that "string" and converting it to a PHP array which I can then manipulate.

Body:
With exact that code...

$string='[157966745,275000353,43192565,305328212]';
$newString=str_replace(array('[', ']'), '', $string); // remove the brackets
$createArray=explode(',', $newString); // explode the commas to create an array

print_r($createArray);


问:
FindByIdAndUpdate is updating but returning null
This is the first time I come here for some guidance, but I dont know what else to try.

I have a household collection that contains a member collection in it. When new members sign in, I need to be able to update the household collection with the new members.

This is what my household controler looks like:

```<code>update: function(req, res) {
  db.Household
    .findByIdAndUpdate(
      {_id: req.params.id},
      {$push: {members: req.body.id}},
      {new: true, useFindAndModify: false})
    .then(dbModel => { return res.json(dbModel); })
    .catch(console.log)
  ;
}
</code>```

On the frontend I just hardcoded the new member id from our seed, since I am waiting to finish up passport authentication and incorporate it to this). I looks like this:

```<code>const memberData = '5ecdc629e77964b5b474c19f'
</code>```

I would appreciate if someone could let me know why is it being added as a member with the update but saved as null.

Thank you!

答:
```<code>update: function(req, res) {
  db.Household
    .findByIdAndUpdate(
      {req.params.id},
      {"members": req.body.id},
      {new: true, useFindAndModify: false})
    .then(dbModel => { return res.json(dbModel); })
    .catch(console.log)
  ;
}
</code>```

try this

Body:
This is the first time I come here for some guidance, but I dont know what else to try.

I have a household collection that contains a member collection in it. When new members sign in, I need to be able to update the household collection with the new members.

This is what my household controler looks like:

update: function(req, res) {
  db.Household
    .findByIdAndUpdate(
      {_id: req.params.id},
      {$push: {members: req.body.id}},
      {new: true, useFindAndModify: false})
    .then(dbModel => { return res.json(dbModel); })
    .catch(console.log)
  ;
}

On the frontend I just hardcoded the new member id from our seed, since I am waiting to finish up passport authentication and incorporate it to this). I looks like this:

const memberData = '5ecdc629e77964b5b474c19f'

I would appreciate if someone could let me know why is it being added as a member with the update but saved as null.

Thank you!

Body:
update: function(req, res) {
  db.Household
    .findByIdAndUpdate(
      {req.params.id},
      {"members": req.body.id},
      {new: true, useFindAndModify: false})
    .then(dbModel => { return res.json(dbModel); })
    .catch(console.log)
  ;
}

try this


问:
laravel 2 tables have 1:n relationship with the same table
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like, </p>

```<code>ID, type, file_path, ownable_id, ownable_type
</code>```

答:
I think your assets table columns should be

id, type, file_path,  assetable_id, assetable_type

Add this relation to your user and product model

```<code>    public function assets()
    {
        return $this->morphMany(Asset::class, 'assetable');
    }
</code>```

Next, add this relation to your asset model

```<code>public function assetable()
{
    return $this->morphTo();
}
</code>```

Body:
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like,

ID, type, file_path, ownable_id, ownable_type

Body:
I think your assets table columns should be

id, type, file_path,  assetable_id, assetable_type

Add this relation to your user and product model

    public function assets()
    {
        return $this->morphMany(Asset::class, 'assetable');
    }

Next, add this relation to your asset model

public function assetable()
{
    return $this->morphTo();
}


问:
View removed VBA code after repair of Excel file
I am getting an error when opening excel: We found a problem with some content in XXX. Do you want us to try and recover as much as we can? if you trust he source of this workbook, click Yes."
clicking Yes, "fixes" the issue but deletes a lot of VBA code, two weeks worth.
Whatever the issue it was introduced yesterday, I do not want to redo two weeks worth of coding. Is there anyway I can view what was removed, or open the VBA in notepad++ or something without opening the excel?</p>

答:
I opened another excel workbook and tried all the different options for the argument XlCorruptLoad in the Workbooks.Open to open the corrupt workbook. I noticed that there were two non existing sheets created in the project explroer of the corrupt workbook that had the code in there. I am not sure if it did that s a result of what I did or it was there all along and I did not notice it
Note that the reason I had a corrupted data is because the code was extracting a list and putting it in a cell validation formula..i guess I overloaded it.</p>


问:
Splunk query does not return multiple instances of the field values
I have a Splunk query that identifies all of the fields extracted from the xml file but not all of the instances of the data.
There is a huge xml file that has multiple instances of the result but only identifies 1 result in the field list.
This is the query:

```<code>source="service.log" sourcetype="dispatchapp" "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" "<purchCostReference>2618252</purchCostReference>" "<eventType>DISPATCH</eventType>" | xmlkv
</code>```

This is the result:

The highlighted fields are the ones I am interested in.  There are 3 carrier tags and many ns:numberCodes.  But it is only showing 1.
Below is the xml that has the data

```<code><purchasedCost>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>NS</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4061</ns2:numberCode>
            <ns2:locAbbr>NSAU</ns2:locAbbr>
            <ns2:address1>6300 SOUTH INDIANA AVENUE</ns2:address1>
            <ns2:city>CHICAGO</ns2:city>
            <ns2:stateProvince>IL</ns2:stateProvince>
            <ns2:postalCode>60637</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>CST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>4040</ns2:numberCode>
               <ns2:locAbbr>CROX</ns2:locAbbr>
               <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
               <ns2:address2>125 COUNTY ROAD</ns2:address2>
               <ns2:city>CROXTON</ns2:city>
               <ns2:stateProvince>NJ</ns2:stateProvince>
               <ns2:postalCode>07307</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>8</ns2:numberType>
               <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:18:53.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>BNSF</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4022</ns2:numberCode>
            <ns2:locAbbr>BNSF</ns2:locAbbr>
            <ns2:address1>3770 EAST WASHINGTON AVENUE</ns2:address1>
            <ns2:city>LOS ANGELES</ns2:city>
            <ns2:stateProvince>CA</ns2:stateProvince>
            <ns2:postalCode>90040</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>PST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>9996</ns2:numberCode>
               <ns2:stateProvince>DU</ns2:stateProvince>
               <ns2:postalCode>00000</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>1</ns2:numberType>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:19:53.000Z</estimatedArrivalDate>
         <billingMethod>RULE</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>NS</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4061</ns2:numberCode>
            <ns2:locAbbr>NSAU</ns2:locAbbr>
            <ns2:address1>6300 SOUTH INDIANA AVENUE</ns2:address1>
            <ns2:city>CHICAGO</ns2:city>
            <ns2:stateProvince>IL</ns2:stateProvince>
            <ns2:postalCode>60637</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>CST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>4040</ns2:numberCode>
               <ns2:locAbbr>CROX</ns2:locAbbr>
               <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
               <ns2:address2>125 COUNTY ROAD</ns2:address2>
               <ns2:city>CROXTON</ns2:city>
               <ns2:stateProvince>NJ</ns2:stateProvince>
               <ns2:postalCode>07307</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>8</ns2:numberType>
               <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:20:53.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
   </purchasedCost>
</code>```

How to extract the numberCode and carrier instances for each of the purchase cost segments?

答:
This is how I was able to get multiple instances of a value in an xml file...

You can tell rex to return both of them using the max_match option.

```<code>| rex max_match=0 "\<ns2\:numberCode\>(?P<origin>[^\<]+)"
| eval originCode = mvindex(origin, 0), destCode = mvindex(origin, 1)
</code>```

Unfortunately, there's no way to know the order of the matches so this fails if destination precedes origin in the XML.

You should be able to use spath to extract the entire XML and refer to "origin.numberCode" and "destination.numberCode", but I don't have enough experience with that command to offer much guidance.

Body:
I have a Splunk query that identifies all of the fields extracted from the xml file but not all of the instances of the data.
There is a huge xml file that has multiple instances of the result but only identifies 1 result in the field list.
This is the query:

source="service.log" sourcetype="dispatchapp" "<billingMethod>RULE</billingMethod>" "createMessage MsgSource" "<purchCostReference>2618252</purchCostReference>" "<eventType>DISPATCH</eventType>" | xmlkv

This is the result:

The highlighted fields are the ones I am interested in.  There are 3 carrier tags and many ns:numberCodes.  But it is only showing 1.
Below is the xml that has the data

<purchasedCost>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>NS</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4061</ns2:numberCode>
            <ns2:locAbbr>NSAU</ns2:locAbbr>
            <ns2:address1>6300 SOUTH INDIANA AVENUE</ns2:address1>
            <ns2:city>CHICAGO</ns2:city>
            <ns2:stateProvince>IL</ns2:stateProvince>
            <ns2:postalCode>60637</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>CST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>4040</ns2:numberCode>
               <ns2:locAbbr>CROX</ns2:locAbbr>
               <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
               <ns2:address2>125 COUNTY ROAD</ns2:address2>
               <ns2:city>CROXTON</ns2:city>
               <ns2:stateProvince>NJ</ns2:stateProvince>
               <ns2:postalCode>07307</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>8</ns2:numberType>
               <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:18:53.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>BNSF</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4022</ns2:numberCode>
            <ns2:locAbbr>BNSF</ns2:locAbbr>
            <ns2:address1>3770 EAST WASHINGTON AVENUE</ns2:address1>
            <ns2:city>LOS ANGELES</ns2:city>
            <ns2:stateProvince>CA</ns2:stateProvince>
            <ns2:postalCode>90040</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>PST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>9996</ns2:numberCode>
               <ns2:stateProvince>DU</ns2:stateProvince>
               <ns2:postalCode>00000</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>1</ns2:numberType>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:19:53.000Z</estimatedArrivalDate>
         <billingMethod>RULE</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
      <purchasedCostTripSegment>
         <purchCostReference>2618252</purchCostReference>
         <carrier>NS</carrier>
         <vendorType>RAIL</vendorType>
         <carrierTrailerType>53RP</carrierTrailerType>
         <origin>
            <ns2:numberCode>4061</ns2:numberCode>
            <ns2:locAbbr>NSAU</ns2:locAbbr>
            <ns2:address1>6300 SOUTH INDIANA AVENUE</ns2:address1>
            <ns2:city>CHICAGO</ns2:city>
            <ns2:stateProvince>IL</ns2:stateProvince>
            <ns2:postalCode>60637</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>CST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </origin>
         <destination>
            <ns2:numberCode>4040</ns2:numberCode>
            <ns2:locAbbr>CROX</ns2:locAbbr>
            <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
            <ns2:address2>125 COUNTY ROAD</ns2:address2>
            <ns2:city>CROXTON</ns2:city>
            <ns2:stateProvince>NJ</ns2:stateProvince>
            <ns2:postalCode>07307</ns2:postalCode>
            <ns2:locType>FDEG</ns2:locType>
            <ns2:numberType>8</ns2:numberType>
            <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
            <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
         </destination>
         <stopOff>
            <ns2:stopOffLocation>
               <ns2:numberCode>4040</ns2:numberCode>
               <ns2:locAbbr>CROX</ns2:locAbbr>
               <ns2:address1>NORFOLK SOUTHERN RAILROAD</ns2:address1>
               <ns2:address2>125 COUNTY ROAD</ns2:address2>
               <ns2:city>CROXTON</ns2:city>
               <ns2:stateProvince>NJ</ns2:stateProvince>
               <ns2:postalCode>07307</ns2:postalCode>
               <ns2:locType>FDEG</ns2:locType>
               <ns2:numberType>8</ns2:numberType>
               <ns2:timeZoneAbbr>EST</ns2:timeZoneAbbr>
               <ns2:daylightSavingsFlag>true</ns2:daylightSavingsFlag>
            </ns2:stopOffLocation>
         </stopOff>
         <schedDispatchDate>2020-05-20T05:00:00.000Z</schedDispatchDate>
         <actualDispatchDate>2020-05-21T08:20:53.000Z</actualDispatchDate>
         <estimatedArrivalDate>2020-05-25T08:20:53.000Z</estimatedArrivalDate>
         <billingMethod>LOCAL</billingMethod>
         <STCCCode>4711110</STCCCode>
         <planNumber>065</planNumber>
         <powerType>1X</powerType>
         <powerOnlyFlag>false</powerOnlyFlag>
      </purchasedCostTripSegment>
   </purchasedCost>

How to extract the numberCode and carrier instances for each of the purchase cost segments?

Body:
This is how I was able to get multiple instances of a value in an xml file...

You can tell rex to return both of them using the max_match option.

| rex max_match=0 "\<ns2\:numberCode\>(?P<origin>[^\<]+)"
| eval originCode = mvindex(origin, 0), destCode = mvindex(origin, 1)

Unfortunately, there's no way to know the order of the matches so this fails if destination precedes origin in the XML.

You should be able to use spath to extract the entire XML and refer to "origin.numberCode" and "destination.numberCode", but I don't have enough experience with that command to offer much guidance.