问:
How to customize the Gantt chart using matplotlib and display the vertical line indicating current time on a graph?
Here is my Python code which basically plots a Gantt chart:

```<code>import pandas as pd
import random
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
%matplotlib inline
import math
plt.style.use('ggplot')

df = pd.read_csv('zpp00141_new.csv')

def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))

df.rename(columns={"Earl. start / time": "start", "Latest finish / time": "finish"}, inplace = True)

df['Operation/Activity'] = df['Operation/Activity'].astype(str)

fig, ax = plt.subplots(figsize=(10, 5))
operations = pd.unique(df['Operation/Activity'])
#df.assign(start=df['Earl. start / time'])
colors = plt.cm.tab10.colors  # get a list of 10 colors
colors *= math.ceil(len(operations) / (len(colors)))  # repeat the list as many times as needed
for operation, color in zip(operations, colors):
    for row in df[df['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=3, color=color)
ax.set_xlim(timestr_to_num('07:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
ax.set_xlabel('Time')
ax.set_ylabel('Operation')
plt.tight_layout()
plt.show()
</code>```

You can see the output on the attached picture:

I would like to plot a vertical straight line that would correspond with a current time on the x-axis. I tried to add this to my code to plot it but I can't figure out how to make it work. I assume there might an issue with my time formatting or something like that:

```<code>plt.axvline(pd.Timestamp.now(),color='r')
</code>```

I would really appreciate any assistance in this matter.
Here is a picture of the desired output, I want my plot to be alike:

Also, I would like to add/append another category to my y-axis "Operation short text" along with the "Operation/Activity"# so it would not only show the operation number, but would also reflect the description of the operation next to it.
To have a grasp of what my data looks like,see below (first row is a header):

```<code>Operation short text,Operation/Activity,Earl. start / time,Latest finish / time
Mount right racks,0250,7:00:00 AM,9:22:00 AM
Mount right side motion unit carriage,0251,9:22:00 AM,10:30:00 AM
Mount left side motion unit carriage,0252,10:30:00 AM,11:17:00 AM
Install motion unit complete,0253,11:17:00 AM,1:01:00 PM
Move machine to next step + EPA,0254,1:01:00 PM,3:30:00 PM
Mount Left Racks,0200,7:00:00 AM,9:12:00 AM
Mount cable motor & Lubricate guide carr,0201,9:12:00 AM,9:44:00 AM
Mount suction components,0202,9:44:00 AM,11:04:00 AM
Mount extraction,0203,11:04:00 AM,12:34:00 PM
Mount temporary diamond plates,0204,12:34:00 PM,1:04:00 PM
Mount piping inside,0205,1:04:00 PM,1:44:00 PM
Move Machine to next step + EPA,0206,1:44:00 PM,3:30:00 PM
</code>```

答:
The easiest seems to sort the dataframe by operation and then plot the horizontal bars using the index of the dataframe as the y-coordinate. Then, reversing the limits of the y-axis (setting it from high to low), gets the lowest numbered operation on top. (The code now assumes that each bar will be on a new line, while the old code assumed there would be more bars for one operation).

As the operations now seem to belong together, a colormap with sequential colors is choosen, and the colors are started again each time an operation starts earlier than the previous. Feel free to use any scheme that suits your goals.

As the datetime.strptime only looks to the time, it gets a default date (January 1st, 1900). So your approach to use the same conversion for the 'now' time is very adecuate.

Note that pd.read_csv's type sniffer gives a float format to the operations column. You could prevent this giving it explicit conversion information. E.g. pd.read_csv(..., converters={1: str}) to have the second column as string.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from datetime import datetime
import pandas as pd
import math
# % matplotlib inline

def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))

plt.style.use('ggplot')
# df = pd.read_csv('zpp00141_new.csv')
columns = ['Operation short text', 'Operation/Activity', 'Earl. start / time', 'Latest finish / time']
rows = [['Mount right racks', '0250', '7:00:00 AM', '9:22:00 AM'],
        ['Mount right side motion unit carriage', '0251', '9:22:00 AM', '10:30:00 AM'],
        ['Mount left side motion unit carriage', '0252', '10:30:00 AM', '11:17:00 AM'],
        ['Install motion unit complete', '0253', '11:17:00 AM', '1:01:00 PM'],
        ['Move machine to next step + EPA', '0254', '1:01:00 PM', '3:30:00 PM'],
        ['Mount Left Racks', '0200', '7:00:00 AM', '9:12:00 AM'],
        ['Mount cable motor & Lubricate guide carr', '0201', '9:12:00 AM', '9:44:00 AM'],
        ['Mount suction components', '0202', '9:44:00 AM', '11:04:00 AM'],
        ['Mount extraction', '0203', '11:04:00 AM', '12:34:00 PM'],
        ['Mount temporary diamond plates', '0204', '12:34:00 PM', '1:04:00 PM'],
        ['Mount piping inside', '0205', '1:04:00 PM', '1:44:00 PM'],
        ['Move Machine to next step + EPA', '0206', '1:44:00 PM', '3:30:00 PM']]
df = pd.DataFrame(data=rows, columns=columns)
df.rename(columns={"Earl. start / time": "start", "Latest finish / time": "finish"}, inplace=True)

df['Operation/Activity'] = df['Operation/Activity'].astype(int)
df.sort_values('Operation/Activity', ascending=True, inplace=True, ignore_index=True)

fig, ax = plt.subplots(figsize=(10, 5))

#colors = plt.cm.tab10.colors  # get a list of 10 colors
cmap = plt.cm.get_cmap('plasma_r')
colors = [cmap(i/9) for i in range(10)]   # get a list of 10 colors

previous_start = math.inf  # 'previous_start' helps to indicate we're starting again from the left
color_start = 0
for row in df.itertuples():
    left = timestr_to_num(row.start)
    right = timestr_to_num(row.finish)
    if left <= previous_start:
        color_start = row.Index
    ax.barh(row.Index, left=left, width=right - left, height=1, color=colors[(row.Index - color_start) % len(colors)])
    previous_start = left
ax.set_xlim(timestr_to_num('7:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
ax.set_xlabel('Time')
ax.set_ylabel('Operation')
ax.set_ylim(len(df), -1)  # set the limits and reverse the order
ax.set_yticks(range(len(df)))
# ax.set_yticklabels(list(df['Operation/Activity']))
ax.set_yticklabels(list(df['Operation short text']))

now = datetime.now().strftime('%I:%M:%S %p')
ax.axvline(x=timestr_to_num(now),color='r')

plt.tight_layout()
plt.show()
```

Body:
Here is my Python code which basically plots a Gantt chart:

import pandas as pd
import random
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
%matplotlib inline
import math
plt.style.use('ggplot')

df = pd.read_csv('zpp00141_new.csv')

def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))

df.rename(columns={"Earl. start / time": "start", "Latest finish / time": "finish"}, inplace = True)

df['Operation/Activity'] = df['Operation/Activity'].astype(str)

fig, ax = plt.subplots(figsize=(10, 5))
operations = pd.unique(df['Operation/Activity'])
#df.assign(start=df['Earl. start / time'])
colors = plt.cm.tab10.colors  # get a list of 10 colors
colors *= math.ceil(len(operations) / (len(colors)))  # repeat the list as many times as needed
for operation, color in zip(operations, colors):
    for row in df[df['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=3, color=color)
ax.set_xlim(timestr_to_num('07:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
ax.set_xlabel('Time')
ax.set_ylabel('Operation')
plt.tight_layout()
plt.show()

You can see the output on the attached picture:

I would like to plot a vertical straight line that would correspond with a current time on the x-axis. I tried to add this to my code to plot it but I can't figure out how to make it work. I assume there might an issue with my time formatting or something like that:

plt.axvline(pd.Timestamp.now(),color='r')

I would really appreciate any assistance in this matter.
Here is a picture of the desired output, I want my plot to be alike:

Also, I would like to add/append another category to my y-axis "Operation short text" along with the "Operation/Activity"# so it would not only show the operation number, but would also reflect the description of the operation next to it.
To have a grasp of what my data looks like,see below (first row is a header):

Operation short text,Operation/Activity,Earl. start / time,Latest finish / time
Mount right racks,0250,7:00:00 AM,9:22:00 AM
Mount right side motion unit carriage,0251,9:22:00 AM,10:30:00 AM
Mount left side motion unit carriage,0252,10:30:00 AM,11:17:00 AM
Install motion unit complete,0253,11:17:00 AM,1:01:00 PM
Move machine to next step + EPA,0254,1:01:00 PM,3:30:00 PM
Mount Left Racks,0200,7:00:00 AM,9:12:00 AM
Mount cable motor & Lubricate guide carr,0201,9:12:00 AM,9:44:00 AM
Mount suction components,0202,9:44:00 AM,11:04:00 AM
Mount extraction,0203,11:04:00 AM,12:34:00 PM
Mount temporary diamond plates,0204,12:34:00 PM,1:04:00 PM
Mount piping inside,0205,1:04:00 PM,1:44:00 PM
Move Machine to next step + EPA,0206,1:44:00 PM,3:30:00 PM


来源: stackexchange

问:
JDK flight recorder backport in RedHat OpenJDK 8
I would like to ask, if anybody knows date or more informations about JDK flight recorder backport in the RedHat OpenJDK 8 production release (for RHEL 7)? I've tried the last build (1.8.0_242-b08) that doesn't contain it yet, and based on this article (https://www.i-programmer.info/news/80-java/13279-openjdk-8-to-get-jdk-flight-recorder.html) I thought that it will contain and nowhere can not find more information. Best regards and thanks for your answers.</p>

答: Thank you for your answers. I also got answers directly from Red Hat: We plan to release Java Flight Recorder / Mission Control for OpenJDK 8 for Q3 2020 (July 2020). Have a nice day</p>

ContentLicense: CC BY-SA 4.0


问:
Could not find com.android.tools.lint:lint-gradle:26.1.4. Searched in the following locations
please help I have this error in android studio</p>

```<code>Could not find com.android.tools.lint:lint-gradle:26.1.4.
Searched in the following locations:
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/Desktop/webviewapp-2.2.0/mobile/libs/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/Desktop/webviewapp-2.2.0/mobile/libs/lint-gradle.jar
Required by:
    project :mobile here
</code>```

答:
1- close unity

2- go to "C:\Users(user name)"

3- delete ".gradle" folder

try bulid project now

Body:
please help I have this error in android studio

Could not find com.android.tools.lint:lint-gradle:26.1.4.
Searched in the following locations:
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/google/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    file:/C:/Users/samir/AppData/Local/Android/Sdk/extras/android/m2repository/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.pom
    https://jcenter.bintray.com/com/android/tools/lint/lint-gradle/26.1.4/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/Desktop/webviewapp-2.2.0/mobile/libs/lint-gradle-26.1.4.jar
    file:/C:/Users/samir/Desktop/webviewapp-2.2.0/mobile/libs/lint-gradle.jar
Required by:
    project :mobile here


问:
spring json date to java date object
In my Spring[3.0] application, </p>

<p>I want to submit data using jquery.ajax. Spring is interpreting this request and converting to appropriate Object. however, it is unable to parse the date attributes. How do I pass them from my JSON request to java? please help... </p>

```<code>public class MyUser{
    public String name;
    public Date birth;
}

@RequestMapping("/app/saveuser")
public String save(@ModelAttribute MyUser user)
{
    //User has NO date.. :(
}

Front end code...
jQuery.post("/app/saveuser",
{name:"myName", birth:new Date()},
function(data){
    alert(data);
} );
</code>```

答: Dates cannot be bound to a command object unless you specify a PropertyEditor or a Conversion service that can read some date format (this is a limitation by design, as you cannot tell what '01/02/03' means without knowing the format); try to write some @InitBinder method and there register a CustomDateEditor for the format you're expecting.

ContentLicense: CC BY-SA 3.0

Title: spring json date to java date object

Body:
In my Spring[3.0] application,

I want to submit data using jquery.ajax. Spring is interpreting this request and converting to appropriate Object. however, it is unable to parse the date attributes. How do I pass them from my JSON request to java? please help...

public class MyUser{
    public String name;
    public Date birth;
}

@RequestMapping("/app/saveuser")
public String save(@ModelAttribute MyUser user)
{
    //User has NO date.. :(
}

Front end code...
jQuery.post("/app/saveuser",
{name:"myName", birth:new Date()},
function(data){
    alert(data);
} );


问:
C++ raytracer ppm says not enough data to display the image
Making a ray tracer and the code was failing so I decided to redo the whole thing and change the logic of the object but now for some reason, it keeps giving me an error and I've already tried editing it multiple times. ImageMagick give me an error saying that there isn't enough data to produce the ppm
other than the bit about the object the main logic how the ppm is produced hasn't changed much so I can't really figure out where the error is.
main.cpp  </p>

```<code>vec color(const ray& r, float t, vec a, vec centre)
{
    vector <Light> lighting;
    lighting.push_back(Light(vec(0, 0, 50), vec(0, 0, -1)));
    vec totalLight{0, 0, 0};
    for(int i = 0; i <lighting.size(); i++){
        if(t > 0.0){
                vec hit = unit_vector(r.p_at_par(t) - centre);
                vec L = unit_vector(lighting[i].position() - r.p_at_par(t));
                vec R = L - 2.0*dot(L, hit)*hit;
                vec S = vec(1, 1, 1)*pow(max(0.f, dot(R, vec(0, 0, -1))), 50);//Specular component
                vec D = (a * max(0.f, dot(L, hit)) * 1.0);//Diffuse component
                totalLight += S + D;
                return totalLight;
            }
        }
}

float clamp(float a)
{
    return (a > 255)? 255: (a < 0)? 0: a;
}

int main()
{
    const int w = 200, h = 100;
    FILE *fp;
    fp = fopen("img.ppm", "wb");
    fprintf(fp, "P6\n%d %d\n255\n", w, h);
    vec lower_corner(-2.0, -1.0, -1.0);
    vec horizontal(4.0, 0.0, 0.0);
    vec vertical(0.0, 2.0, 0.0);
    vec origin(0.0, 0.0, 0.0);
    vector <sphere> objects;
    objects.push_back(sphere(vec(0,-100.5,-1), 100, vec(0, 1, 0)));
    objects.push_back(sphere(vec(0, 0, -1), 0.5, vec(1, 0, 0)));
    objects.push_back(sphere(vec(5, 5,-2), 3, vec(1, 0, 0)));
    for(int j = h - 1; j >= 0; j--)
    {
        for(int i = 0; i < w; i++)
        {
            vec col(0, 0, 0);
            static unsigned char pixel[3];
            sphere* ClosestObject = NULL;
            float u = float(i + random_double())/float(w);
            float v = float(j + random_double())/float(h);
            ray r(origin, lower_corner + u*horizontal + v*vertical);
            float t = 0.0;
            float t_near = 200000.0;
            vec pixelColor(0.52 , 0.52 ,0.48);
            for(int j = 0; j < objects.size(); j++)
            {
                if(t = objects[j].intersect(r))
                {
                    if(t < t_near)
                    {
                        ClosestObject = &objects[j];
                        t_near = t;
                    }
                }
                if( t = 200000.0)
                    col = pixelColor;
                else
                    col = color(r, t, ClosestObject->color, ClosestObject->centre);
                pixel[0] = int(clamp(col.r() * 255));
                pixel[1] = int(clamp(col.g() * 255));
                pixel[2] = int(clamp(col.b() * 255));
                fwrite(pixel, 3, 1, fp);
        }

    }
    fclose(fp);
    return 0;
    }
}
</code>```

答:
Actually, a comment but too much text for that…

Your indentation is broken.

Hence, you didn't notice that the return 0; appears in the outer for loop, this one:

```<code>  for(int j = h - 1; j >= 0; j--)
  {
</code>```

ends with:

```<code>    fclose(fp);
    return 0;
  }
</code>```

Additionally, the

```<code>        fwrite(pixel, 3, 1, fp);
</code>```

appears in the most inner loop

```<code>      for (int j = 0; j < objects.size(); j++)
</code>```

which is IMHO wrong as well.

So, the produced .ppm file claims to have w×h pixels but instead it provides w×objects.size() pixels.

If objects.size() < h (what I would expect) then you will have too less pixels in the .ppm file and ImageMagick will notice and complain.

Your source code, auto-formatted in my VS2017:

int main()
{
  const int w = 200, h = 100;
  FILE *fp;
  fp = fopen("img.ppm", "wb");
  fprintf(fp, "P6\n%d %d\n255\n", w, h);
  vec lower_corner(-2.0, -1.0, -1.0);
  vec horizontal(4.0, 0.0, 0.0);
  vec vertical(0.0, 2.0, 0.0);
  vec origin(0.0, 0.0, 0.0);
  vector <sphere> objects;
  objects.push_back(sphere(vec(0, -100.5, -1), 100, vec(0, 1, 0)));
  objects.push_back(sphere(vec(0, 0, -1), 0.5, vec(1, 0, 0)));
  objects.push_back(sphere(vec(5, 5, -2), 3, vec(1, 0, 0)));
  for (int j = h - 1; j >= 0; j--)
  {
    for (int i = 0; i < w; i++)
    {
      vec col(0, 0, 0);
      static unsigned char pixel[3];
      sphere* ClosestObject = NULL;
      float u = float(i + random_double()) / float(w);
      float v = float(j + random_double()) / float(h);
      ray r(origin, lower_corner + u * horizontal + v * vertical);
      float t = 0.0;
      float t_near = 200000.0;
      vec pixelColor(0.52, 0.52, 0.48);
      for (int j = 0; j < objects.size(); j++)
      {
        if (t = objects[j].intersect(r))
        {
          if (t < t_near)
          {
            ClosestObject = &objects[j];
            t_near = t;
          }
        }
        if (t = 200000.0)
          col = pixelColor;
        else
          col = color(r, t, ClosestObject->color, ClosestObject->centre);
        pixel[0] = int(clamp(col.r() * 255));
        pixel[1] = int(clamp(col.g() * 255));
        pixel[2] = int(clamp(col.b() * 255));
        fwrite(pixel, 3, 1, fp);
      }

    }
    fclose(fp);
    return 0;
  }
}
```

Please, check indentation and place closing curly-brackets correctly. Then it should work as before…

Body:
Making a ray tracer and the code was failing so I decided to redo the whole thing and change the logic of the object but now for some reason, it keeps giving me an error and I've already tried editing it multiple times. ImageMagick give me an error saying that there isn't enough data to produce the ppm
other than the bit about the object the main logic how the ppm is produced hasn't changed much so I can't really figure out where the error is.
main.cpp

vec color(const ray& r, float t, vec a, vec centre)
{
    vector <Light> lighting;
    lighting.push_back(Light(vec(0, 0, 50), vec(0, 0, -1)));
    vec totalLight{0, 0, 0};
    for(int i = 0; i <lighting.size(); i++){
        if(t > 0.0){
                vec hit = unit_vector(r.p_at_par(t) - centre);
                vec L = unit_vector(lighting[i].position() - r.p_at_par(t));
                vec R = L - 2.0*dot(L, hit)*hit;
                vec S = vec(1, 1, 1)*pow(max(0.f, dot(R, vec(0, 0, -1))), 50);//Specular component
                vec D = (a * max(0.f, dot(L, hit)) * 1.0);//Diffuse component
                totalLight += S + D;
                return totalLight;
            }
        }
}

float clamp(float a)
{
    return (a > 255)? 255: (a < 0)? 0: a;
}

int main()
{
    const int w = 200, h = 100;
    FILE *fp;
    fp = fopen("img.ppm", "wb");
    fprintf(fp, "P6\n%d %d\n255\n", w, h);
    vec lower_corner(-2.0, -1.0, -1.0);
    vec horizontal(4.0, 0.0, 0.0);
    vec vertical(0.0, 2.0, 0.0);
    vec origin(0.0, 0.0, 0.0);
    vector <sphere> objects;
    objects.push_back(sphere(vec(0,-100.5,-1), 100, vec(0, 1, 0)));
    objects.push_back(sphere(vec(0, 0, -1), 0.5, vec(1, 0, 0)));
    objects.push_back(sphere(vec(5, 5,-2), 3, vec(1, 0, 0)));
    for(int j = h - 1; j >= 0; j--)
    {
        for(int i = 0; i < w; i++)
        {
            vec col(0, 0, 0);
            static unsigned char pixel[3];
            sphere* ClosestObject = NULL;
            float u = float(i + random_double())/float(w);
            float v = float(j + random_double())/float(h);
            ray r(origin, lower_corner + u*horizontal + v*vertical);
            float t = 0.0;
            float t_near = 200000.0;
            vec pixelColor(0.52 , 0.52 ,0.48);
            for(int j = 0; j < objects.size(); j++)
            {
                if(t = objects[j].intersect(r))
                {
                    if(t < t_near)
                    {
                        ClosestObject = &objects[j];
                        t_near = t;
                    }
                }
                if( t = 200000.0)
                    col = pixelColor;
                else
                    col = color(r, t, ClosestObject->color, ClosestObject->centre);
                pixel[0] = int(clamp(col.r() * 255));
                pixel[1] = int(clamp(col.g() * 255));
                pixel[2] = int(clamp(col.b() * 255));
                fwrite(pixel, 3, 1, fp);
        }

    }
    fclose(fp);
    return 0;
    }
}

Body:
Actually, a comment but too much text for that…

Your indentation is broken.

Hence, you didn't notice that the return 0; appears in the outer for loop, this one:

  for(int j = h - 1; j >= 0; j--)
  {

ends with:

    fclose(fp);
    return 0;
  }

Additionally, the

        fwrite(pixel, 3, 1, fp);

appears in the most inner loop

      for (int j = 0; j < objects.size(); j++)

which is IMHO wrong as well.

So, the produced .ppm file claims to have w×h pixels but instead it provides w×objects.size() pixels.

If objects.size() < h (what I would expect) then you will have too less pixels in the .ppm file and ImageMagick will notice and complain.

Your source code, auto-formatted in my VS2017:

int main()
{
  const int w = 200, h = 100;
  FILE *fp;
  fp = fopen("img.ppm", "wb");
  fprintf(fp, "P6\n%d %d\n255\n", w, h);
  vec lower_corner(-2.0, -1.0, -1.0);
  vec horizontal(4.0, 0.0, 0.0);
  vec vertical(0.0, 2.0, 0.0);
  vec origin(0.0, 0.0, 0.0);
  vector <sphere> objects;
  objects.push_back(sphere(vec(0, -100.5, -1), 100, vec(0, 1, 0)));
  objects.push_back(sphere(vec(0, 0, -1), 0.5, vec(1, 0, 0)));
  objects.push_back(sphere(vec(5, 5, -2), 3, vec(1, 0, 0)));
  for (int j = h - 1; j >= 0; j--)
  {
    for (int i = 0; i < w; i++)
    {
      vec col(0, 0, 0);
      static unsigned char pixel[3];
      sphere* ClosestObject = NULL;
      float u = float(i + random_double()) / float(w);
      float v = float(j + random_double()) / float(h);
      ray r(origin, lower_corner + u * horizontal + v * vertical);
      float t = 0.0;
      float t_near = 200000.0;
      vec pixelColor(0.52, 0.52, 0.48);
      for (int j = 0; j < objects.size(); j++)
      {
        if (t = objects[j].intersect(r))
        {
          if (t < t_near)
          {
            ClosestObject = &objects[j];
            t_near = t;
          }
        }
        if (t = 200000.0)
          col = pixelColor;
        else
          col = color(r, t, ClosestObject->color, ClosestObject->centre);
        pixel[0] = int(clamp(col.r() * 255));
        pixel[1] = int(clamp(col.g() * 255));
        pixel[2] = int(clamp(col.b() * 255));
        fwrite(pixel, 3, 1, fp);
      }

    }
    fclose(fp);
    return 0;
  }
}

Please, check indentation and place closing curly-brackets correctly. Then it should work as before…


问:
Service-to-service communication: API Gateway vs. Service Mesh
AFAIK:

API Gateway: user-to-service communication

Service Mesh: service-to-service communication

But I cannot find a good explanation (and bibliography) explaining why using API Gateway (such as Apigee) is not suitable for inter-process communication.

Thanks

答:
The difference is mainly a structural one as noted here:

"The service mesh pattern primarily focuses on handling traditionally what has been referred to as "east-west" remote procedure call (RPC)-based traffic: request/response type communication that originates internally within a datacenter and travels service-to-service. This is in contrast to an API gateway or edge proxy, which is designed to handle "north-south" traffic: Communication that originates externally and ingresses to an endpoint or service within the datacenter."

More information on this website


问:
Which methods should be inside a Page class in POM design pattern?
I am creating a UI test automation framework using POM design pattern. After reading SeleniumHQ page for Page Objects, I am contemplating what all methods should I create inside a Page Object.

Let's take a simple example of login page object consisting of username, password textboxes and submit button. SeleniumHQ link has created the below methods :

```<code>1. typeUsername(String username)
2. typePassword(String password)
3. submitLogin()
4. submitLoginExceptionFailure()
5. loginAs(String username, String password)
</code>```

I am a bit perplexed while looking at these methods. Why should I create first 3 methods(typeUsername, typePassword,submitLogin), when I already am creating a loginAs method. Any thoughts around it ?

SeleniumHQ Link - https://github.com/SeleniumHQ/selenium/wiki/PageObjects

Pasting the code PageObject code for LoginPage :

```<code>public class LoginPage {
    private final WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;

        // Check that we're on the right page.
        if (!"Login".equals(driver.getTitle())) {
            // Alternatively, we could navigate to the login page, perhaps logging out first
            throw new IllegalStateException("This is not the login page");
        }
    }

    // The login page contains several HTML elements that will be represented as WebElements.
    // The locators for these elements should only be defined once.
        By usernameLocator = By.id("username");
        By passwordLocator = By.id("passwd");
        By loginButtonLocator = By.id("login");

    // The login page allows the user to type their username into the username field
    public LoginPage typeUsername(String username) {
        // This is the only place that "knows" how to enter a username
        driver.findElement(usernameLocator).sendKeys(username);

        // Return the current page object as this action doesn't navigate to a page represented by another PageObject
        return this;
    }

    // The login page allows the user to type their password into the password field
    public LoginPage typePassword(String password) {
        // This is the only place that "knows" how to enter a password
        driver.findElement(passwordLocator).sendKeys(password);

        // Return the current page object as this action doesn't navigate to a page represented by another PageObject
        return this;
    }

    // The login page allows the user to submit the login form
    public HomePage submitLogin() {
        // This is the only place that submits the login form and expects the destination to be the home page.
        // A seperate method should be created for the instance of clicking login whilst expecting a login failure.
        driver.findElement(loginButtonLocator).submit();

        // Return a new page object representing the destination. Should the login page ever
        // go somewhere else (for example, a legal disclaimer) then changing the method signature
        // for this method will mean that all tests that rely on this behaviour won't compile.
        return new HomePage(driver);
    }

    // The login page allows the user to submit the login form knowing that an invalid username and / or password were entered
    public LoginPage submitLoginExpectingFailure() {
        // This is the only place that submits the login form and expects the destination to be the login page due to login failure.
        driver.findElement(loginButtonLocator).submit();

        // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials
        // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject.
        return new LoginPage(driver);
    }

    // Conceptually, the login page offers the user the service of being able to "log into"
    // the application using a user name and password.
    public HomePage loginAs(String username, String password) {
        // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here.
        typeUsername(username);
        typePassword(password);
        return submitLogin();
    }
}
</code>```

答:
You might want to check if typing the username only and then clicking the submit button shows a correct error message, or only the password, etc.

I usually look at the page and try to summarize what "actions" the user can do on that page, every action becomes a method. The different actions might be on different "levels". e.g. on a blog website, the user can enter the blog-title and the blog content, that are two actions the user can do, but looking from an other abstraction layer the user wants to "create" a post. So that function might again call other functions.

Basically its like any other programming, you have multiple abstraction layers, that is why you have Page Objects in the first place.

And just use iterative development, create a function that does what you want to test and if you find yourself reusing the same code (or identifier) in other functions, separate those out in a new function

Body:
I am creating a UI test automation framework using POM design pattern. After reading SeleniumHQ page for Page Objects, I am contemplating what all methods should I create inside a Page Object.

Let's take a simple example of login page object consisting of username, password textboxes and submit button. SeleniumHQ link has created the below methods :

1. typeUsername(String username)
2. typePassword(String password)
3. submitLogin()
4. submitLoginExceptionFailure()
5. loginAs(String username, String password)

I am a bit perplexed while looking at these methods. Why should I create first 3 methods(typeUsername, typePassword,submitLogin), when I already am creating a loginAs method. Any thoughts around it ?

SeleniumHQ Link - https://github.com/SeleniumHQ/selenium/wiki/PageObjects

Pasting the code PageObject code for LoginPage :

public class LoginPage {
    private final WebDriver driver;

    public LoginPage(WebDriver driver) {
        this.driver = driver;

        // Check that we're on the right page.
        if (!"Login".equals(driver.getTitle())) {
            // Alternatively, we could navigate to the login page, perhaps logging out first
            throw new IllegalStateException("This is not the login page");
        }
    }

    // The login page contains several HTML elements that will be represented as WebElements.
    // The locators for these elements should only be defined once.
        By usernameLocator = By.id("username");
        By passwordLocator = By.id("passwd");
        By loginButtonLocator = By.id("login");

    // The login page allows the user to type their username into the username field
    public LoginPage typeUsername(String username) {
        // This is the only place that "knows" how to enter a username
        driver.findElement(usernameLocator).sendKeys(username);

        // Return the current page object as this action doesn't navigate to a page represented by another PageObject
        return this;
    }

    // The login page allows the user to type their password into the password field
    public LoginPage typePassword(String password) {
        // This is the only place that "knows" how to enter a password
        driver.findElement(passwordLocator).sendKeys(password);

        // Return the current page object as this action doesn't navigate to a page represented by another PageObject
        return this;
    }

    // The login page allows the user to submit the login form
    public HomePage submitLogin() {
        // This is the only place that submits the login form and expects the destination to be the home page.
        // A seperate method should be created for the instance of clicking login whilst expecting a login failure.
        driver.findElement(loginButtonLocator).submit();

        // Return a new page object representing the destination. Should the login page ever
        // go somewhere else (for example, a legal disclaimer) then changing the method signature
        // for this method will mean that all tests that rely on this behaviour won't compile.
        return new HomePage(driver);
    }

    // The login page allows the user to submit the login form knowing that an invalid username and / or password were entered
    public LoginPage submitLoginExpectingFailure() {
        // This is the only place that submits the login form and expects the destination to be the login page due to login failure.
        driver.findElement(loginButtonLocator).submit();

        // Return a new page object representing the destination. Should the user ever be navigated to the home page after submiting a login with credentials
        // expected to fail login, the script will fail when it attempts to instantiate the LoginPage PageObject.
        return new LoginPage(driver);
    }

    // Conceptually, the login page offers the user the service of being able to "log into"
    // the application using a user name and password.
    public HomePage loginAs(String username, String password) {
        // The PageObject methods that enter username, password & submit login have already defined and should not be repeated here.
        typeUsername(username);
        typePassword(password);
        return submitLogin();
    }
}


问:
VB.net server not accessible from outside even when using a wildcard
I have set up a VB.NET server but it only responds to requests from it's own host. If I try to send a request from a different computer (on the same network) it does not respond to the request, it just times out. My application basically listens for a request on port 1212 then takes a screenshot and sends the response back.

I tried using both http://*:1212/ and http://+:1212/ but it only works if I issue the request from the computer where the server is hosted.

From the host, this works
http://192.168.1.150:1212/

From another computer on the network, this does not work
http://192.168.1.150:1212/ (the request times out)

Here is my application

```<code>Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Threading

Public Class Form1
    Private t As New Thread(AddressOf IncomingMessage)
    Private Const bufferSize As Integer = 1024 * 512
    Dim prefixes(0), Port, UserIP, UserIPPort As String
    Dim isWorking As Boolean = False

    ' From1_Load()
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
        prefixes(0) = "http://*:1212/"

        With t
            If (.ThreadState And ThreadState.Unstarted) <> 0 Then
                .IsBackground = True
                .Start()
            End If
        End With
    End Sub

    ' IncomingMessage()
    Private Sub IncomingMessage()
    Bgn:
        If prefixes(0) Is Nothing OrElse prefixes(0).Length = 0 Then
            Throw New ArgumentException("prefixes")
        End If

        Dim listener As HttpListener = New HttpListener()

        For Each s As String In prefixes
            listener.Prefixes.Add(s)
        Next

        Try
            listener.Start()

            Dim numRequestsToBeHandled As Integer = 10

            For i As Integer = 0 To numRequestsToBeHandled
                Dim response As HttpListenerResponse = Nothing
                Dim context As HttpListenerContext = listener.GetContext()
                Dim sr As StreamReader = New StreamReader(context.Request.InputStream)
                Dim URLRequestClient As String = sr.ReadToEnd()

                MessageBox.Show(URLRequestClient)

                Dim bmp As Bitmap = ScreenCap()
                bmp.Save(Application.StartupPath & "\screenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
                bmp.Dispose()

                context.Response.ContentType = "image/jpeg"

                Dim buffer = New Byte(bufferSize - 1) {}

                Using fs = File.OpenRead(Application.StartupPath & "\screenshot.jpg")
                    context.Response.ContentLength64 = fs.Length

                    Dim read As Integer

                    While (InlineAssignHelper(read, fs.Read(buffer, 0, buffer.Length))) > 0
                        context.Response.OutputStream.Write(buffer, 0, read)
                    End While
                End Using

                context.Response.OutputStream.Close()
            Next
        GoTo Bgn
    End Sub
</code>```

答: It turned out it was an issue with the Firewall on my Windows 10 laptop where I was running the server. I turned off firewall for private and public networks and it worked. I suppose a better solution would be to add my application to the allowed list of applications to go through the firewall. (But for some reason that didn't work, I had to turn off Firewall completely)

Body:
I have set up a VB.NET server but it only responds to requests from it's own host. If I try to send a request from a different computer (on the same network) it does not respond to the request, it just times out. My application basically listens for a request on port 1212 then takes a screenshot and sends the response back.

I tried using both http://*:1212/ and http://+:1212/ but it only works if I issue the request from the computer where the server is hosted.

From the host, this works
http://192.168.1.150:1212/

From another computer on the network, this does not work
http://192.168.1.150:1212/ (the request times out)

Here is my application

Imports System.IO
Imports System.Net
Imports System.Text
Imports System.Threading

Public Class Form1
    Private t As New Thread(AddressOf IncomingMessage)
    Private Const bufferSize As Integer = 1024 * 512
    Dim prefixes(0), Port, UserIP, UserIPPort As String
    Dim isWorking As Boolean = False

    ' From1_Load()
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
        prefixes(0) = "http://*:1212/"

        With t
            If (.ThreadState And ThreadState.Unstarted) <> 0 Then
                .IsBackground = True
                .Start()
            End If
        End With
    End Sub

    ' IncomingMessage()
    Private Sub IncomingMessage()
    Bgn:
        If prefixes(0) Is Nothing OrElse prefixes(0).Length = 0 Then
            Throw New ArgumentException("prefixes")
        End If

        Dim listener As HttpListener = New HttpListener()

        For Each s As String In prefixes
            listener.Prefixes.Add(s)
        Next

        Try
            listener.Start()

            Dim numRequestsToBeHandled As Integer = 10

            For i As Integer = 0 To numRequestsToBeHandled
                Dim response As HttpListenerResponse = Nothing
                Dim context As HttpListenerContext = listener.GetContext()
                Dim sr As StreamReader = New StreamReader(context.Request.InputStream)
                Dim URLRequestClient As String = sr.ReadToEnd()

                MessageBox.Show(URLRequestClient)

                Dim bmp As Bitmap = ScreenCap()
                bmp.Save(Application.StartupPath & "\screenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg)
                bmp.Dispose()

                context.Response.ContentType = "image/jpeg"

                Dim buffer = New Byte(bufferSize - 1) {}

                Using fs = File.OpenRead(Application.StartupPath & "\screenshot.jpg")
                    context.Response.ContentLength64 = fs.Length

                    Dim read As Integer

                    While (InlineAssignHelper(read, fs.Read(buffer, 0, buffer.Length))) > 0
                        context.Response.OutputStream.Write(buffer, 0, read)
                    End While
                End Using

                context.Response.OutputStream.Close()
            Next
        GoTo Bgn
    End Sub


问:
Upload images to Azure blob from front end (React)
The front end enables people to upload their photos, so i was sending the base64 to the server and working with it initially, but there are problems with firewall which blocks the request which contains base64. As an alternative solution I was trying to upload the image to azure blob get the file name and then send that to the server for processing where I generate a sas token for the blob validation and processing.

This works perfectly fine when I work locally and the front end connection works with @azure/storage-blob
and uploadBrowserData() when I send the arrayBuffer as the param

```<code>export const uploadSelfieToBlob = async arrayBuffer => {
    try {
        const blobURL = `https://${accountName}.blob.core.windows.net${sasString}`;
        const blobServiceClient = new BlobServiceClient(blobURL, anonymousCredential);
        const containerClient = blobServiceClient.getContainerClient(containerName);
        let randomString = Math.random().toString(36).substring(7);
        const blobName = `${randomString}_${new Date().getTime()}.jpg`;
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.uploadBrowserData(arrayBuffer);
        return { blobName, blobId: uploadBlobResponse.requestId };
    } catch (error) {
        console.log('error when uploading to blob', error);
        throw new Error('Error Uploading the selfie to blob');
    }
};
</code>```

When I deploy this is not working, the front is deployed in the EastUs2 location and the local development location is different.

I thought the sasString generated for anonymous access had the timezone option so I generated 2 different one's one for local and one for hosted server with the same location selected.

```<code> Failed to send request to https://xxxx.blob.core.windows.net/contanainer-name/26pcie_1582087489288.jpg?sv=2019-02-02&ss=b&srt=c&sp=rwdlac&se=2023-09-11T07:57:29Z&st=2020-02-18T00:57:29Z&spr=https&sig=9IWhXo5i%2B951%2F8%2BTDqIY5MRXbumQasOnY4%2Bju%2BqF3gw%3D
</code>```

What am I missing any lead would be helpful thanks

答:
First, as mentioned in the comments there was an issue with the CORS Settings because of which you're getting the initial error.

AuthorizationResourceTypeMismatchThis
  request is not authorized to perform this operation using this
  resource type. RequestId:7ec96c83-101e-0001-4ef1-e63864000000
  Time:2020-02-19T06:57:31.2867563Z

I looked up this error code here and then closely looked at your SAS URL.

One thing I noticed in your SAS URL is that you have set the signed resource type (srt) as c (container) and trying to upload the blob. If you look at the description of the kind of operations you can do using srt=c here, you will notice that blob related operations are not supported.

In order to perform blob related operations (like blob upload), you would need to set signed resource type value to o (for object).

Please regenerate your SAS Token and include signed resource type as object (you can also include container and/or service in there as well) and then your request should work. So essentially your srt in your SAS URL should be something like srt=o or srt=co or srt=sco.

Body:
The front end enables people to upload their photos, so i was sending the base64 to the server and working with it initially, but there are problems with firewall which blocks the request which contains base64. As an alternative solution I was trying to upload the image to azure blob get the file name and then send that to the server for processing where I generate a sas token for the blob validation and processing.

This works perfectly fine when I work locally and the front end connection works with @azure/storage-blob
and uploadBrowserData() when I send the arrayBuffer as the param

export const uploadSelfieToBlob = async arrayBuffer => {
    try {
        const blobURL = `https://${accountName}.blob.core.windows.net${sasString}`;
        const blobServiceClient = new BlobServiceClient(blobURL, anonymousCredential);
        const containerClient = blobServiceClient.getContainerClient(containerName);
        let randomString = Math.random().toString(36).substring(7);
        const blobName = `${randomString}_${new Date().getTime()}.jpg`;
        const blockBlobClient = containerClient.getBlockBlobClient(blobName);
        const uploadBlobResponse = await blockBlobClient.uploadBrowserData(arrayBuffer);
        return { blobName, blobId: uploadBlobResponse.requestId };
    } catch (error) {
        console.log('error when uploading to blob', error);
        throw new Error('Error Uploading the selfie to blob');
    }
};

When I deploy this is not working, the front is deployed in the EastUs2 location and the local development location is different.

I thought the sasString generated for anonymous access had the timezone option so I generated 2 different one's one for local and one for hosted server with the same location selected.

 Failed to send request to https://xxxx.blob.core.windows.net/contanainer-name/26pcie_1582087489288.jpg?sv=2019-02-02&ss=b&srt=c&sp=rwdlac&se=2023-09-11T07:57:29Z&st=2020-02-18T00:57:29Z&spr=https&sig=9IWhXo5i%2B951%2F8%2BTDqIY5MRXbumQasOnY4%2Bju%2BqF3gw%3D

What am I missing any lead would be helpful thanks


问:
How to Insert & Update Multiple Record in Django
I want to know how to deal with this task.
here are the details:
this is product_feature model

```<code>class Feature(models.Model):
    has_value_choice = [
        ('y', 'Yes'),
        ('n', 'No'),
    ]
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

</code>```

here, I'm passing features data to the template to save features of the specific product in the product_feature model.

```<code>                  <form>
                        <table class="table table-bordered">
                            <thead>
                              <tr>
                                <th>Features</th>
                                <th>Value</th>
                              </tr>
                            </thead>
                            <tbody>
                                {% for data in features_data %}
                                    <tr>
                                        {% if data.feature_has_value != 'n' %}
                                            <td>{{ data.feature_name }}</td>
                                            <td><input type="text" name="{{ data.feature_name }}" id="{{ data.feature_name }}" placeholder="Enter {{ data.feature_name }}" class="form-control" required/></td>
                                        {% else %}
                                            <td>{{ data.feature_name }}</td>
                                            <td>
                                                <select id="{{ data.feature_name }}" name="{{ data.feature_name }}" class="form-control" required>
                                                    <option selected id="select" value="yes">Yes</option>
                                                    <option value="no">No</option>
                                                </select>
                                            </td>
                                        {% endif %}
                                    </tr>
                                {% endfor %}
                            </tbody>
                          </table>
                       </form>
</code>```

Now, the thing is how to insert this form data to the product features table( product_feature model at the starting of the question).

I want to insert multiple records in the product features a table with each record have it's feature_id, product_id & product_feature value.

I'm really confused about how to do this I'm new in Django development.

答: I think what you're looking for is a ModelFormSet of feature forms. This allows you to duplicate one form for multiple objects. The documentation is a good on-ramp: https://docs.djangoproject.com/en/3.0/topics/forms/formsets/

Body:
I want to know how to deal with this task.
here are the details:
this is product_feature model

class Feature(models.Model):
    has_value_choice = [
        ('y', 'Yes'),
        ('n', 'No'),
    ]
    feature_id = models.AutoField(primary_key=True)
    feature_name = models.CharField(max_length=255, null = False)
    product_type = models.ForeignKey(Product_type, on_delete=models.SET_NULL, null=True)
    feature_has_value = models.CharField(choices=has_value_choice, max_length = 1, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

class Product_feature(models.Model):
    product_feature_id = models.AutoField(primary_key=True)
    feature = models.ForeignKey(Feature, on_delete=models.SET_NULL, null=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
    product_feature_value = models.CharField(max_length=255, null = False)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

here, I'm passing features data to the template to save features of the specific product in the product_feature model.

                  <form>

                                Features
                                Value

                                {% for data in features_data %}

                                        {% if data.feature_has_value != 'n' %}
                                            {{ data.feature_name }}
                                            <input type="text" name="{{ data.feature_name }}" id="{{ data.feature_name }}" placeholder="Enter {{ data.feature_name }}" class="form-control" required/>
                                        {% else %}
                                            {{ data.feature_name }}

                                                <select id="{{ data.feature_name }}" name="{{ data.feature_name }}" class="form-control" required>
                                                    <option selected id="select" value="yes">Yes</option>
                                                    <option value="no">No</option>
                                                </select>

                                        {% endif %}

                                {% endfor %}

                       </form>

Now, the thing is how to insert this form data to the product features table( product_feature model at the starting of the question).

I want to insert multiple records in the product features a table with each record have it's feature_id, product_id & product_feature value.

I'm really confused about how to do this I'm new in Django development.


答:
I believe that this should work if I understand your question

```<code>CREATE TABLE #DATE ([USER] VARCHAR(5),  [TIME] DATETIME2)
INSERT INTO #DATE VALUES
('A','2020-02-18 12:00:13.037'),('B','2020-02-19 12:00:13.037'),
('B','2020-02-11 11:00:13.037'),('B','2020-02-11 14:00:13.037'),
('B','2020-02-11 08:00:13.037'),('C','2020-02-09 12:00:13.037')

SELECT
    [USER],
    [TIME],
    FORMAT([TIME],'MM-dd')
FROM #DATE
WHERE FORMAT([TIME],'MM-dd')='02-11'

DROP TABLE #DATE
</code>```

NOTE that the format function only work for SQL Server version 2012 and above.

Title: How to DATETIME regex and split

Body:
USER  TIME
 A     2020-02-18 12:00:13.037
 B     2020-02-19 12:00:13.037
 B     2020-02-11 11:00:13.037
 B     2020-02-11 14:00:13.037
 B     2020-02-11 08:00:13.037
 C     2020-02-09 12:00:13.037

I want result like this:

USER  TIME
 B     02-11
 B     02-11
 B     02-11

Query time is 02-11 and split time to month and data

How can I do? My query:

SELECT * FROM my_table WHERE USER = 'B' AND TIME REGEXP '02/11"

Body:
I believe that this should work if I understand your question

CREATE TABLE #DATE ([USER] VARCHAR(5),  [TIME] DATETIME2)
INSERT INTO #DATE VALUES
('A','2020-02-18 12:00:13.037'),('B','2020-02-19 12:00:13.037'),
('B','2020-02-11 11:00:13.037'),('B','2020-02-11 14:00:13.037'),
('B','2020-02-11 08:00:13.037'),('C','2020-02-09 12:00:13.037')

SELECT
    [USER],
    [TIME],
    FORMAT([TIME],'MM-dd')
FROM #DATE
WHERE FORMAT([TIME],'MM-dd')='02-11'

DROP TABLE #DATE

NOTE that the format function only work for SQL Server version 2012 and above.


问:
Convert mySQL query to KNEX
I am converting series of queries to Knex syntax.
I am having problem with this query:

```<code>SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();
</code>```

More precisely this line:

```<code>SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
</code>```

I have this Knex in place:

```<code>knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))
</code>```

that produces this sql query:

```<code>select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()
</code>```

Problem is in the: Convert(notification USING utf8).

The query is not valid, since the Convert is in parentheses. How can I write it with the knex?

In general how do I include SQL function calls in the KNEX syntax?

答:
Here is fixed version of @Veve's answer with correct quoting of identifiers and knex.raw syntax:

```<code>knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', knex.raw('CONVERT(?? USING utf8)', ['notification']), 'create_time', 'update_time', 'store', 'user_id')
        .where('reviewed', 0)
        .where(knex.raw('?? BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()', ['create_time']))
</code>```

https://runkit.com/embed/lh2i1qif7obx

Title: Convert mySQL query to KNEX

Body:
I am converting series of queries to Knex syntax.
I am having problem with this query:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id
FROM store_failure_log
WHERE reviewed = 0
AND create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW();

More precisely this line:

SELECT id,reviewed,log_reference,CONVERT(notification USING utf8),create_time,update_time,store,user_id

I have this Knex in place:

knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', 'CONVERT(notification USING utf8)', 'create_time', 'update_time', 'store', 'user_id').convert('notification USING utf8')
        .where('reviewed', 0)
        .where(knex.raw('create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()'))

that produces this sql query:

select `id`, `reviewed`, `log_reference`, `CONVERT(notification USING utf8)`, `create_time`, `update_time`, `store`, `user_id` from `store_failure_log` where `reviewed` = 0 and create_time BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()

Problem is in the: Convert(notification USING utf8).

The query is not valid, since the Convert is in parentheses. How can I write it with the knex?

In general how do I include SQL function calls in the KNEX syntax?

Body:
Here is fixed version of @Veve's answer with correct quoting of identifiers and knex.raw syntax:

knex('store_failure_log')
        .select('id', 'reviewed', 'log_reference', knex.raw('CONVERT(?? USING utf8)', ['notification']), 'create_time', 'update_time', 'store', 'user_id')
        .where('reviewed', 0)
        .where(knex.raw('?? BETWEEN NOW() - INTERVAL 18 HOUR AND NOW()', ['create_time']))

https://runkit.com/embed/lh2i1qif7obx


问:
how to add tablet resolution support in Android Studio
Using ConstraintLayout I saw this problem: on phones, the resolution of my widgets is normal and takes up almost all of the
screen space:

But when I switch to the resolution of the tablets, all the widgets become small and cannot be viewed on the screen:

How to make the resolution of widgets look normal on all resolutions and devices?

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TableLayout
        android:id="@+id/table_l"
        android:layout_width="297dp"
        android:layout_height="329dp"
        android:layout_weight="1"
        android:layout_x="57dp"
        android:layout_y="202dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1" />

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1">

        </TableRow>
    </TableLayout>

    <Button
        android:id="@+id/st"
        android:layout_width="178dp"
        android:layout_height="wrap_content"
        android:layout_x="120dp"
        android:layout_y="112dp"
        android:text="start"
        app:layout_constraintBottom_toTopOf="@+id/table_l"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_weight="1"
        app:layout_constraintVertical_bias="0.647" />

    <TextView
        android:id="@+id/X_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="48dp"
        android:layout_x="118dp"
        android:layout_y="608dp"
        android:text="x:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/O_text"
        app:layout_constraintStart_toStartOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/O_text" />

    <TextView
        android:id="@+id/O_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:layout_x="116dp"
        android:layout_y="661dp"
        android:text="o:"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/table_l"
        app:layout_constraintHorizontal_bias="0.153"
        app:layout_constraintStart_toStartOf="@+id/table_l"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="27dp"
        android:layout_height="47dp"
        android:layout_marginTop="36dp"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.139"
        app:layout_constraintStart_toEndOf="@+id/O_text"
        app:layout_constraintTop_toBottomOf="@+id/table_l"
        app:layout_constraintVertical_bias="0.0" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="25dp"
        android:layout_height="45dp"
        android:layout_marginBottom="52dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.151"
        app:layout_constraintStart_toEndOf="@+id/X_text"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        app:layout_constraintVertical_bias="0.571" />

</androidx.constraintlayout.widget.ConstraintLayout>```

答:
You should stop using fixed sizes and x/y positions for layouts. There might be exceptions, but in general, all views should be able to dynamically resize themselves. That means, you almost never use fixed values for widths but instead wrap_content or match_parent. After 4 years of android development I also have to find one case where I ever needed the layout_x and layout_y XML tags.

Otherwise, this layout will be small on big screens and it won't fit on small screens.

For 90% of layouts, all you need is ConstraintLayout and maybe LinearLayout. RelativeLayouts have become mostly obsolete.

Explaining how to properly arrange your ui would be to exhaustive here. Instead, I recommend you to take the time to go through a tutorial like this google codelab on building a responsive UI with constraintlayouts. If done correctly, you can build one UI which looks good an smartphones and tablets.

But if you want to have an entirely different layout for tablets, then @Mustafa Yanık's approach is correct. Then you need to create a second layout in a different subfolder.


问:
GCP: Allowing Public Ingress Web Traffic from the Load Balancer ONLY
Disclaimers: I come from AWS background but relatively very new to GCP. I know there are a number of existing similar questions (e.g, here and here etc) but I still cannot get it work since the exact/detailed instructions are still missing. So please bear with me to ask this again.

My simple design:

Public HTTP/S Traffic (Ingress) >> GCP Load Balancer >> GCP Servers

GCP Load Balancer holds the SSL Cert. And then it uses Port 80 for downstream connections to the Servers. Therefore, LB to the Servers are just HTTP.

My question:

How do I prevent the incoming HTTP/S Public Traffic from reaching to the GCP Servers directly? Instead, only allow the Load Balancer (as well as it's Healthcheck Traffic)?

What I tried so far:

I went into Firewall Rules and removed the previously allowing rule of Ports 80/443 (Ingress Traffic) from 0.0.0.0/0. And then, added (allowed) the External IP address of Load Balancer.

At this point, I simply expected the Public Traffic should be rejected but the Load Balancer's. But in reality, both seemed to be rejected. Nothing reached the Servers anymore. The Load Balancer's External IP wasn't seemed to be recognised.

Later I also noticed the "Healthchecks" were also not recognised anymore. Therefore Healthchecks couldn't reach to Servers and then failed. Hence the Instances were dropped by Load Balancer.

Please also note that: I cannot pursue the approach of simply removing the External IPs on the Servers. (Although many people say this would work.) But we still want to maintain the direct SSH accesses to the Servers (by not using a Bastion Instance). Therefore I still need the External IPs, on each and every Web Servers.

Any clear (and kind) instructions will be very much appreciated. Thank you all.

答:
You're able to setup HTTPS connectivity between your load balancer and your back-end servers while using HTTP(S) load balancer. To achieve this goal you should install HTTPS certificates on your back-end servers and configure web-servers to use them. If you decided to completely switch to HTTPS and disable HTTP on your back-end servers you should switch your health check from HTTP to HTTPS also.

To make health check working again after removing default firewall rule that allow connection from 0.0.0.0/0 to ports 80 and 443 you need to whitelist subnets 35.191.0.0/16 and 130.211.0.0/22 which are source IP ranges for health checks. You can find step by step instructions how to do it in the documentation. After that, access to your web servers still be restricted but your load balancer will be able to use health check and serve your customers.


问:
typescript variable with generic extending
I have a predefined interface:

```<code>export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}
</code>```

I would like to have a class attribute that constraint the generic type. Something like this:

```<code>public componentType: Type<any extends MyComponentType>;
</code>```

Is it possible ? Because I did not find the solution on Typescript doc and I can't find a syntax that is working.

Thanks.

答:
The answer is the comment made by @Josh Wulf on the original post.</p>

```<code>public componentType: Type<MyComponentType>
</code>```

Body:
I have a predefined interface:

export declare interface Type<T> extends Function {
    new (...args: any[]): T;
}

I would like to have a class attribute that constraint the generic type. Something like this:

public componentType: Type<any extends MyComponentType>;

Is it possible ? Because I did not find the solution on Typescript doc and I can't find a syntax that is working.

Thanks.

Body:
The answer is the comment made by @Josh Wulf on the original post.

public componentType: Type<MyComponentType>


问:
What is the error in my code I am new in ajjax
I want to create a dependent dropdown select box using ajjax. I can not find out my error. Please help me to find out my error. Selecting the specialty show the doctor name according the specialty. But I can't do this.
This is my Route.php

```<code>Route::get('/admin/appointment/view/{id}', 'AppointmentController@appointmentView'); Route::get('/admin/appointment/speciality', 'AppointmentController@doctorView')->name('admin.appointment.speciality');
</code>```

My Appointment Controller

```<code>public function doctorView(Request $request)
    {
        $data=Doctor::select('doctor_name','doctor_specialty')->where('doctor_specialty',$request->speciality)->take(100)->get();
        return response()->json($data);//then sent this data to ajax success

    }
</code>```

View File :

```<code><div class="form-group">
     <label for="inputState" class="col-form-label">Doctor Speciality</label>
     <select name="speciality" id="speciality" class="form-control doctor_speciality" data-dependent="state">
      <option value="">Select Speciality</option>
       @foreach($specialityLists as $specialityList)
       <option value="{{$specialityList->speciality}}">{{$specialityList->speciality}}</option>
       @endforeach
        </select>
     </div>

 <div class="form-group">
   <label for="inputState" class="col-form-label">Doctor Name</label>
   <select name="doctors_name" id="doctors_name" class="form-control doctor_name " >
   <option value="0" selected="true">Choose Doctor Name</option>
       </select>
 </div>
</code>```

Script File :

```<code>$(document).ready(function(){

 $(document).on('change','.doctor_speciality',function(){
            // console.log("hmm its change");
            var speciality_id = $(this).val();
            // console.log(speciality_id);
            var div=$(this).parent();
            var op=" ";
            $.ajax({
                type:'get',
                url: '{!!URL::to('/admin/appointment/speciality')!!}',
                data:{'id':speciality_id},
                success:function(data){
                    // console.log('success');
                    // console.log(data);
                    // console.log(data.length);
                    op+='<option value="0" selected disabled>Choose Doctor</option>';
                    for(var i=0;i<data.length;i++){
                    op+='<option value="'+data[i].doctor_specialty+'">'+data[i].doctor_name+'</option>';
                         }
                    div.find('.doctor_name').html(" ");
                   div.find('.doctor_name').append(op);
                },
                error:function(){
                }

            });
    });

});
</code>```

答:
Let me clearify to you ....

Change your route with post

```<code>Route::post('/admin/appointment/speciality', 'AppointmentController@doctorView')->name('admin.appointment.speciality');
</code>```

Now your ajax part

```<code>$(document).ready(function(){

$(document).on('change','.doctor_speciality',function(){
        var speciality_id = $(this, 'option:selected').val();
        $.ajax({
            type:'post',
            url: "{{ route('admin.appointment.speciality') }}",
            data:{speciality:speciality_id,_token:@json(csrf_token())},
            success:function(data){
                // console.log(data);
                var op ='<option value="0" selected disabled>Choose Doctor</option>';
                $.each(data,function(key,value){
                  op+='<option value="'+value.doctor_specialty+'">'+value.doctor_name+'</option>';
                });
                $('.doctor_name').empty().append(op);
            },
            error:function(data){
             console.log(data);
            }

        });
   });

});
</code>```

If you have one to Many relation with doctor table then in your view change this.

```<code>   @foreach($specialityLists as $specialityList)
     <option value="{{$specialityList->id}}">{{$specialityList->speciality}}</option>
   @endforeach
</code>```

And in controller do something like this....

```<code>public function doctorView(Request $request)
{
    //Here doc_spec_id will be your foreign key
    //$request->speciality this will be your specialitylist primary key
    return Doctor::select('doctor_name','doctor_specialty')->where('doc_spec_id',$request->speciality)->take(100)->get();

    OR

    //If $request->speciality is like a name mean to say string then write LIKE Query
    return Doctor::select('doctor_name','doctor_specialty')->where('doctor_specialty','LIKE','%'.$request->speciality.'%')->take(100)->get();

}
</code>```

If the data is null ofcourse you can write checks etc...

Body:
I want to create a dependent dropdown select box using ajjax. I can not find out my error. Please help me to find out my error. Selecting the specialty show the doctor name according the specialty. But I can't do this.
This is my Route.php

Route::get('/admin/appointment/view/{id}', 'AppointmentController@appointmentView'); Route::get('/admin/appointment/speciality', 'AppointmentController@doctorView')->name('admin.appointment.speciality');

My Appointment Controller

public function doctorView(Request $request)
    {
        $data=Doctor::select('doctor_name','doctor_specialty')->where('doctor_specialty',$request->speciality)->take(100)->get();
        return response()->json($data);//then sent this data to ajax success

    }

View File :

     Doctor Speciality
     <select name="speciality" id="speciality" class="form-control doctor_speciality" data-dependent="state">
      <option value="">Select Speciality</option>
       @foreach($specialityLists as $specialityList)
       <option value="{{$specialityList->speciality}}">{{$specialityList->speciality}}</option>
       @endforeach
        </select>

   Doctor Name
   <select name="doctors_name" id="doctors_name" class="form-control doctor_name " >
   <option value="0" selected="true">Choose Doctor Name</option>
       </select>

Script File :

$(document).ready(function(){

 $(document).on('change','.doctor_speciality',function(){
            // console.log("hmm its change");
            var speciality_id = $(this).val();
            // console.log(speciality_id);
            var div=$(this).parent();
            var op=" ";
            $.ajax({
                type:'get',
                url: '{!!URL::to('/admin/appointment/speciality')!!}',
                data:{'id':speciality_id},
                success:function(data){
                    // console.log('success');
                    // console.log(data);
                    // console.log(data.length);
                    op+='<option value="0" selected disabled>Choose Doctor</option>';
                    for(var i=0;i<data.length;i++){
                    op+='<option value="'+data[i].doctor_specialty+'">'+data[i].doctor_name+'</option>';
                         }
                    div.find('.doctor_name').html(" ");
                   div.find('.doctor_name').append(op);
                },
                error:function(){
                }

            });
    });

});

Body:
Let me clearify to you ....

Change your route with post

Route::post('/admin/appointment/speciality', 'AppointmentController@doctorView')->name('admin.appointment.speciality');

Now your ajax part

$(document).ready(function(){

$(document).on('change','.doctor_speciality',function(){
        var speciality_id = $(this, 'option:selected').val();
        $.ajax({
            type:'post',
            url: "{{ route('admin.appointment.speciality') }}",
            data:{speciality:speciality_id,_token:@json(csrf_token())},
            success:function(data){
                // console.log(data);
                var op ='<option value="0" selected disabled>Choose Doctor</option>';
                $.each(data,function(key,value){
                  op+='<option value="'+value.doctor_specialty+'">'+value.doctor_name+'</option>';
                });
                $('.doctor_name').empty().append(op);
            },
            error:function(data){
             console.log(data);
            }

        });
   });

});

If you have one to Many relation with doctor table then in your view change this.

   @foreach($specialityLists as $specialityList)
     <option value="{{$specialityList->id}}">{{$specialityList->speciality}}</option>
   @endforeach

And in controller do something like this....

public function doctorView(Request $request)
{
    //Here doc_spec_id will be your foreign key
    //$request->speciality this will be your specialitylist primary key
    return Doctor::select('doctor_name','doctor_specialty')->where('doc_spec_id',$request->speciality)->take(100)->get();

    OR

    //If $request->speciality is like a name mean to say string then write LIKE Query
    return Doctor::select('doctor_name','doctor_specialty')->where('doctor_specialty','LIKE','%'.$request->speciality.'%')->take(100)->get();

}

If the data is null ofcourse you can write checks etc...


问:
How to set excel sheet name in BIRT API?
When I use birt api to export excel, the excel's sheet name is default set to Sheet0. Is there a way to custom sheet name in birt API?

答:
I had a report with two table and page break after the first one so each table made their own sheet. after selecting each table go to the script and in the "on create" script, code this:
this.name = "Sheet Name";


问:
Get 5 random instances from a queryset in Django
I have this view function that renders the first 5 articles in my Articles model

```<code>def home_page(request):
    qs = Article.objects.all()[:5]
    context = {'article_list': qs}
    return render(request, "home.html", context)
</code>```

How do i edit it to output any random 5?

I've tried this solution, but it didn't work. I don't know what I'm doing wrong.

Any help will be greatly appreciated.

Thanks

答:
I prefer to shuffle the entire queryset everytime page loads and slice the first 5 objects in the template. In the views:

ids = [i.id for i in Model.objects.filter(some_field=some_variable)] #list of the queryset's ids
random.shuffle(ids) # shuffle the ids
shuffled = [Model.objects.get(id=i) for i in ids] #map back the shuffled ids to corresponding objects
```

In the template, loop through the five random objects:

{% for i in shuffled|slice:'5' %}

Body:
I have this view function that renders the first 5 articles in my Articles model

def home_page(request):
    qs = Article.objects.all()[:5]
    context = {'article_list': qs}
    return render(request, "home.html", context)

How do i edit it to output any random 5?

I've tried this solution, but it didn't work. I don't know what I'm doing wrong.

Any help will be greatly appreciated.

Thanks

Body:
I prefer to shuffle the entire queryset everytime page loads and slice the first 5 objects in the template. In the views:

ids = [i.id for i in Model.objects.filter(some_field=some_variable)] #list of the queryset's ids
random.shuffle(ids) # shuffle the ids
shuffled = [Model.objects.get(id=i) for i in ids] #map back the shuffled ids to corresponding objects

In the template, loop through the five random objects:

{% for i in shuffled|slice:'5' %}


问:
Code crashes at iteration 86
```<code>static void Job47(Args _args)
 {
 str                                  path,stx;
 TreeNodeIterator                     iter;
 TreeNode                             treeNode, treeNodeToRelease;
 Map                                  dictMenuDisplay;
 FormName                             formName;
 MenuItemName                         menuItemName;
 container                            conMenu;
 int                                  i,n;
   ;

 for (n=1;n<=100;n++)
       {
        info(strfmt("iter:%1",n));
        path            ="Menu Items\\Display";
        dictMenuDisplay = new Map(Types::String,Types::Container);
        treenode        = Treenode::findNode(path);
        iter            = treenode.AOTiterator();
        treenode        = iter.next();

        while (treenode)
          {
          formName     = treenode.AOTgetProperty("Object");
          menuItemName = treenode.AOTname();

           if (dictMenuDisplay.exists(formName))
            {
             conMenu = dictMenuDisplay.lookup(formName);
             conMenu = conIns(conMenu,conlen(conMenu)+1,menuItemName);
             dictMenuDisplay.insert(formName,conMenu);
             }

           else
             dictMenuDisplay.insert(formName,[menuItemName]);
                      //  treenode = iter.next();

           if(treeNodeToRelease && SysTreeNode::isApplObject(treeNode))
            {
             treeNodeToRelease.treeNodeRelease();
             treeNodeToRelease=null;
            }

           if(SysTreeNode::isApplObject(treeNode))
            {
              treeNodeToRelease=treeNode;
            }

            treeNode=iter.next();
        }
    }
  }
</code>```

I get the error "overflow in internal run stack",the code runs till 86th iteration correctly, help...

答:
Quote from the manual:

If you run this method (treeNodeRelease()) on many tree nodes in the same execution, it can be demanding on resources. You should unload the tree nodes as you go along to give the garbage collector a chance to remove them.

Make sure to remove all references to the tree node and its subnodes before you call this method.

Also you have at least 85 references of the treeNodeToRelease (and treeNode!) floating around -> call treeNodeToRelease.treeNodeRelease() at the end of your outer loop.

ContentLicense: CC BY-SA 2.5

Title: Code crashes at iteration 86

Body:
static void Job47(Args _args)
 {
 str                                  path,stx;
 TreeNodeIterator                     iter;
 TreeNode                             treeNode, treeNodeToRelease;
 Map                                  dictMenuDisplay;
 FormName                             formName;
 MenuItemName                         menuItemName;
 container                            conMenu;
 int                                  i,n;
   ;

 for (n=1;n<=100;n++)
       {
        info(strfmt("iter:%1",n));
        path            ="Menu Items\\Display";
        dictMenuDisplay = new Map(Types::String,Types::Container);
        treenode        = Treenode::findNode(path);
        iter            = treenode.AOTiterator();
        treenode        = iter.next();

        while (treenode)
          {
          formName     = treenode.AOTgetProperty("Object");
          menuItemName = treenode.AOTname();

           if (dictMenuDisplay.exists(formName))
            {
             conMenu = dictMenuDisplay.lookup(formName);
             conMenu = conIns(conMenu,conlen(conMenu)+1,menuItemName);
             dictMenuDisplay.insert(formName,conMenu);
             }

           else
             dictMenuDisplay.insert(formName,[menuItemName]);
                      //  treenode = iter.next();

           if(treeNodeToRelease && SysTreeNode::isApplObject(treeNode))
            {
             treeNodeToRelease.treeNodeRelease();
             treeNodeToRelease=null;
            }

           if(SysTreeNode::isApplObject(treeNode))
            {
              treeNodeToRelease=treeNode;
            }

            treeNode=iter.next();
        }
    }
  }

I get the error "overflow in internal run stack",the code runs till 86th iteration correctly, help...


问:
Jmeter Microsoft Azure Authentication to login
Can someone help to login to an application having Microsoft OAuth authentication using JMeter? I'm having trouble to identify the unique token that is being used in the login call. Is there a way to identify?</p>

答:
Which exactly OAuth?

As of now the following OAuth 2.0 and OpenID Connect protocols are implemented/supported:

OpenID Connect

OAuth 2.0 implicit grant flow

OAuth 2.0 auth code grant

OAuth 2.0 on-behalf-of flow

OAuth 2.0 client credentials grant

The instructions will differ depending on your application authentication flow and covering all of them with examples in a single answer.

The universal way would be using i.e. MSAL library from the JSR223 Test Elements using Groovy language in order to get the access token.


问:
Using two array values in foreach loop
I have the following loop:

```<code>var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});
</code>```

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

```<code>$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');
</code>```

My output looks like this:

```<code><option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>
</code>```

Whereas I'm looking for:

```<code><option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</code>```

答:
You can use the function map for creating an array of Option objects and then append that array to the desired element.

This is a dry approach, and also you can use the Option object if you want to add some features/behavior, read the documentation for more detail.

let array = ["Value 1", "Value 2", "Value 3"];
let textArray = ["Text 1", "Text 2", "Text 3"];
$(".department").append(array.map((v, i) => new Option(textArray[i], v)));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="department">
<option value="">Please select</option>
</select></code>```

Title: Using two array values in foreach loop

Body:
I have the following loop:

var array = ["Value 1", "Value 2", "Value 3"];
var textArray = ["Text 1", "Text 2", "Text 3"];

array.forEach(function(arr) {
  $(".department").append('<option value="' + array + '">' + textArray + '</option>');
});

What I'm trying to achieve is the <option> label to use the text but its value to use the array array.

If I do the following:

$(".filterSection .department").append('<option value="'+array+'">'+textArray+'</option>');

My output looks like this:

<option value="Value 1,Value 2,Value 3">Text 1</option>
<option value="Value 1,Value 2,Value 3">Text 2</option>

Whereas I'm looking for:

<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>

Body:
You can use the function map for creating an array of Option objects and then append that array to the desired element.

This is a dry approach, and also you can use the Option object if you want to add some features/behavior, read the documentation for more detail.

let array = ["Value 1", "Value 2", "Value 3"];
let textArray = ["Text 1", "Text 2", "Text 3"];
$(".department").append(array.map((v, i) => new Option(textArray[i], v)));

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="department">
<option value="">Please select</option>
</select>


问:
How can I assign content to specific signed in user within Flamelink and React Native?
I am using Firebase with React Native and just started with Flamelink as my CMS.

Before using Flamelink, I was able to obtain specific content from a logged-in user via firebase realtime database because the schema was:

```<code>**fruits**
mwaKRypUrNb8rJdsj9YUxw0sA892
-M055RlZ7HBzgRD9LS1d
-M055Why2psB2kqE4mYO
-M05W3LK8C1kgFsPNRqa
-M05W47cbhJ2VA_Y2nnT
-M05W5Wu9Pp6TZJJPc8t
-M05W6Xc_iP1upbyENpj
-M05W7JnVt3t3DsjNaRT
-M05W8OuZph-1gDDY9UX
-M05W9Fws0_hsNCAyKDt
**users**
-zFWGnGhEmbfhjAJsUT99ZbkJBZ33
</code>```

As you can see, the fruits schema had user-specific content.

With Flamelink the schema looks like this:

```<code>**flamelink**
--environments
----production
------content
--------**fruitEntryForm**
----------en-US
------------1582070066847
------------1582074440836
------------1582080914427

**schemas**
**media**
**permissions**
**settings**
**users**
--zFWGnGhEmbfhjAJsUT99ZbkJBZ33
</code>```

My react native code is below:

```<code>const user = navigation.getParam("user");
     const currentUserData = await firebase
      .database()
      .ref("flamelink/users")
      .child(user.uid)
      .once("value");

const fruits = await app.content.get("content");
</code>```

How can I modify Flamelink so that I can manage content based on which user is signed in?

答:
From my understanding, your Fruits collection can be linked to multiple users and the main problem is that the Firebase Realtime Database does not allow querying for a value inside an array. Cloud Firestore is a bit better in that regard.

What I would suggest you do to simplify your queries is to turn the relationship on its head. I would have the Fruits collection that you currently have without a relationship to any users. Then I would create a "Users Fruit" collection that has a field for the user's UID with a relational select field that maps to multiple entries in your Fruits collection.

From your React Native app, you can then use our SDK to query the "Users Fruit" collection and expand the related Fruits.

Depending on the version of the SDK you are using, the syntax might differ a bit, but for the latest SDK it will look like this:

const userFruit = await app.content.get({
  schemaKey: 'usersFruit', // assuming schema key is this
  orderByChild: "user", // assuming your field is called 'user'
  equalTo: "mwaKRypUrNb8rJdsj9YUxw0sA892", // assuming this is your user's uid
  populate: ['fruits'] // assuming you called the select relational field 'fruits'
})
```

Body:
I am using Firebase with React Native and just started with Flamelink as my CMS.

Before using Flamelink, I was able to obtain specific content from a logged-in user via firebase realtime database because the schema was:

**fruits**
mwaKRypUrNb8rJdsj9YUxw0sA892
-M055RlZ7HBzgRD9LS1d
-M055Why2psB2kqE4mYO
-M05W3LK8C1kgFsPNRqa
-M05W47cbhJ2VA_Y2nnT
-M05W5Wu9Pp6TZJJPc8t
-M05W6Xc_iP1upbyENpj
-M05W7JnVt3t3DsjNaRT
-M05W8OuZph-1gDDY9UX
-M05W9Fws0_hsNCAyKDt
**users**
-zFWGnGhEmbfhjAJsUT99ZbkJBZ33

As you can see, the fruits schema had user-specific content.

With Flamelink the schema looks like this:

**flamelink**
--environments
----production
------content
--------**fruitEntryForm**
----------en-US
------------1582070066847
------------1582074440836
------------1582080914427

**schemas**
**media**
**permissions**
**settings**
**users**
--zFWGnGhEmbfhjAJsUT99ZbkJBZ33

My react native code is below:

const user = navigation.getParam("user");
     const currentUserData = await firebase
      .database()
      .ref("flamelink/users")
      .child(user.uid)
      .once("value");

const fruits = await app.content.get("content");

How can I modify Flamelink so that I can manage content based on which user is signed in?


问:
Django - Getting a list of fields in a queryset
I need help in getting a list of fields in a Queryset.

I am using Django shell to test, but I haven't had any luck.

If I do .values like below

```<code>abc = PrescribedMedsSchedule.objects.filter(medication_date=scheduled_date_obj, medication_time__time=scheduled_time_obj) \
        .select_related('prescribed_meds_id') \
        .select_related('prescribed_meds_id__childno') \
        .values(
            'prescribed_meds_id',
            'medication_date',
            'medication_time',
            'quantity',
            'form',
            'prescribed_meds_id__name_of_medication',
            'prescribed_meds_id__childno__child_name',
            'prescribed_meds_id__childno__group',
            'prescribed_meds_id__childno__line_no'
            ).order_by('prescribed_meds_id__name_of_medication')
</code>```

I get the exact column names that I can use in the template, when I type abc in shell.
QuerySet [{'prescribed_meds_id': 5731, 'medication_date': datetime.date(2020, 2, 4), ....

But if I use .only instead of .values,  when I type abc, I get a
QuerySet [<PrescribedMedsSchedule: PrescribedMedsSchedule object (6117) ....

How can I retrieve/display the fields/columns in this queryset?

The reason I am asking is that the fields in the select_related tables no longer appears in the HTML template when I use .only.

答:
Use QuerySet.values if you want the resulting queryset to contain dictionaries and QuerySet.only if you want the resulting queryset to contain model instances.

You can observe that the result query using values or orders are the same when you print it in terminal.

```<code>print(abc.query)
</code>```

If you like to still use QuerySet.only and retrieve queryset results as an iterable of model instances, then you can access the related fields using the dot operator. For example, to output child name in the template:

```<code>{% for a in abc %}
  {{ a.prescribed_meds_id.childno.child_name }}
{% endfor %}
</code>```

Body:
I need help in getting a list of fields in a Queryset.

I am using Django shell to test, but I haven't had any luck.

If I do .values like below

abc = PrescribedMedsSchedule.objects.filter(medication_date=scheduled_date_obj, medication_time__time=scheduled_time_obj) \
        .select_related('prescribed_meds_id') \
        .select_related('prescribed_meds_id__childno') \
        .values(
            'prescribed_meds_id',
            'medication_date',
            'medication_time',
            'quantity',
            'form',
            'prescribed_meds_id__name_of_medication',
            'prescribed_meds_id__childno__child_name',
            'prescribed_meds_id__childno__group',
            'prescribed_meds_id__childno__line_no'
            ).order_by('prescribed_meds_id__name_of_medication')

I get the exact column names that I can use in the template, when I type abc in shell.
QuerySet [{'prescribed_meds_id': 5731, 'medication_date': datetime.date(2020, 2, 4), ....

But if I use .only instead of .values,  when I type abc, I get a
QuerySet [<PrescribedMedsSchedule: PrescribedMedsSchedule object (6117) ....

How can I retrieve/display the fields/columns in this queryset?

The reason I am asking is that the fields in the select_related tables no longer appears in the HTML template when I use .only.

Body:
Use QuerySet.values if you want the resulting queryset to contain dictionaries and QuerySet.only if you want the resulting queryset to contain model instances.

You can observe that the result query using values or orders are the same when you print it in terminal.

print(abc.query)

If you like to still use QuerySet.only and retrieve queryset results as an iterable of model instances, then you can access the related fields using the dot operator. For example, to output child name in the template:

{% for a in abc %}
  {{ a.prescribed_meds_id.childno.child_name }}
{% endfor %}