问:
React onClick not changing color of item
I am trying to make it so that when  i click a note, the item should become selected and then it will change background color.
I have a console log statement inside the handleNoteClick function, but it is not logging, meaning that the function is not being called

```<code>import React, { useState } from "react";
import { NoteItems } from "../noteDisplay/noteDisplay";
import NavItems from "./navItems";
const NoteNav = () => {
  const [notes, setNotes] = useState(NoteItems);

  const handleNoteClick = (id) => {
    const newNoteItems = notes.map((item) => {
      if (item.id === id) return { ...item, selected: !item.selected };
      else {
        return item;
      }
    });
    console.log("yekaj;lksndf");
    setNotes(newNoteItems);
  };
  return (
    <nav className="nav-bar">
      <div className="nav-content">
        {NoteItems.map((items) => (
          <NavItems key={items.id} items={items} onClick={handleNoteClick} />
        ))}
      </div>
    </nav>
  );
};
export default NoteNav;
</code>```

Array of notes:

```<code>const NoteItems = [
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfffffffffffffffffffffffffffffffffffffff",
    title: "e"
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: true
  }
];

</code>```

The object that I pass each item of the array into

```<code>import React, { useState } from "react";

const NavItems = ({ items }) => {
  return (
    <div
      className={
        items.selected ? "second-note-box-selected" : "second-note-box"
      }
    >
      <h1 className="note-title">{items.title}</h1>
      <p className="note-content">{items.message}</p>
    </div>
  );
};
export default NavItems;
</code>```

答:
There are a couple of problems with your code.

The first and most important is that onClick only works on native DOM elements. What you are doing here <NavItems key={items.id} items={items} onClick={handleNoteClick}/> is passing a prop named onClick to NavItems.

That will not trigger an on click, you need to use that in the component and attach it to a div for instance.

The second is regarding the fact that you are updating notes, but you don't use it during the render.

The third could be that you are iterating over the entire array, just to update one value. You could easily do something like this:

```<code>const handleNoteClick =(item) => {
  item.selected = !item.selected
  console.log('yekaj;lksndf')
  setNotes([...notes])
}
</code>```

And pass item as the argument to handleNoteClick like this:

<NavItems onClick={() => handleNoteClick(item) />

Body:
I am trying to make it so that when  i click a note, the item should become selected and then it will change background color.
I have a console log statement inside the handleNoteClick function, but it is not logging, meaning that the function is not being called

import React, { useState } from "react";
import { NoteItems } from "../noteDisplay/noteDisplay";
import NavItems from "./navItems";
const NoteNav = () => {
  const [notes, setNotes] = useState(NoteItems);

  const handleNoteClick = (id) => {
    const newNoteItems = notes.map((item) => {
      if (item.id === id) return { ...item, selected: !item.selected };
      else {
        return item;
      }
    });
    console.log("yekaj;lksndf");
    setNotes(newNoteItems);
  };
  return (

        {NoteItems.map((items) => (
          <NavItems key={items.id} items={items} onClick={handleNoteClick} />
        ))}

  );
};
export default NoteNav;

Array of notes:

const NoteItems = [
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfffffffffffffffffffffffffffffffffffffff",
    title: "e"
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },

  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: false
  },
  {
    id: uuidv4(),
    message: "asdfasdfffffffffffffffffffffffffffffffffffffff",
    title: "New Note",
    selected: true
  }
];

The object that I pass each item of the array into

import React, { useState } from "react";

const NavItems = ({ items }) => {
  return (

{items.title}

{items.message}

  );
};
export default NavItems;

Body:
There are a couple of problems with your code.

The first and most important is that onClick only works on native DOM elements. What you are doing here <NavItems key={items.id} items={items} onClick={handleNoteClick}/> is passing a prop named onClick to NavItems.

That will not trigger an on click, you need to use that in the component and attach it to a div for instance.

The second is regarding the fact that you are updating notes, but you don't use it during the render.

The third could be that you are iterating over the entire array, just to update one value. You could easily do something like this:

const handleNoteClick =(item) => {
  item.selected = !item.selected
  console.log('yekaj;lksndf')
  setNotes([...notes])
}

And pass item as the argument to handleNoteClick like this:

<NavItems onClick={() => handleNoteClick(item) />


来源: stackexchange

问:
Strange "invalid conversion from <type> to <type>" error
Here is output:

```<code>g++ -DDEBUG -DUNITTEST -IC:/Users/Steven/Dropbox/Programming/entropy_p5_makefile/cpp/game/../include/ -O0 -g3 -Wall -c -fmessage-length=0 -o Input.o ..\Input.cpp
..\Input.cpp: In function 'void mousehookCustomRoutine(E_thread*, void*)':
..\Input.cpp:78:93: error: invalid conversion from 'LRESULT (*)(int, WPARAM, LPARAM)' to 'LRESULT (*)(int, WPARAM, LPARAM)'
..\Input.cpp:78:93: error:   initializing argument 2 of 'void* SetWindowsHookExA(int, LRESULT (*)(int, WPARAM, LPARAM), HINSTANCE__*, DWORD)'
Build error occurred, build is stopped
</code>```

This is the code:

```<code>LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    //...
}

void mousehookCustomRoutine(E_thread *me, void *arg = (void *)&MouseHookProc) {
    // arg is the ptr to LL Mouse Routine

    me->sendMessage(0x14,me,(void*)GetCurrentThreadId());
    // send message to self in order for my parent to know how to identify me via threadID
    HHOOK mousehook = SetWindowsHookEx(WH_MOUSE_LL, (LRESULT (*)(int,WPARAM,LPARAM))arg,NULL, 0); // I am line 78
    if (mousehook == NULL) printf("Mousehook error %lu\n",GetLastError());
    //...
}
</code>```

It makes no sense because I am casting to the exact type that it expects to receive, there aren't any qualifiers or anything that are different. What could possibly be going on here?

答:
First, don't cast function pointers to void *. It is never safe to invoke a function of one type after casting it to another, and so there's rarely, if ever, a need to make them void *.

Second, probably you're seeing a difference in calling conventions. The type of the hook parameter is, properly stated, (LRESULT (CALLBACK *) (int, WPARAM, LPARAM)), or simply HOOKPROC. The prototype of the function should look like LRESULT CALLBACK MouseHookProc(int, WPARAM, LPARAM). Most likely gcc doesn't pretty-print the calling-convention specifier, but does check for it when checking type equivalence. Subtle problems like this are another reason not to cast function pointers - had you used a (HOOKPROC) cast, you would have had no compile-time error, but could have crashed at runtime .... but only on certain versions of windows.

ContentLicense: CC BY-SA 3.0

Body:
Here is output:

g++ -DDEBUG -DUNITTEST -IC:/Users/Steven/Dropbox/Programming/entropy_p5_makefile/cpp/game/../include/ -O0 -g3 -Wall -c -fmessage-length=0 -o Input.o ..\Input.cpp
..\Input.cpp: In function 'void mousehookCustomRoutine(E_thread*, void*)':
..\Input.cpp:78:93: error: invalid conversion from 'LRESULT (*)(int, WPARAM, LPARAM)' to 'LRESULT (*)(int, WPARAM, LPARAM)'
..\Input.cpp:78:93: error:   initializing argument 2 of 'void* SetWindowsHookExA(int, LRESULT (*)(int, WPARAM, LPARAM), HINSTANCE__*, DWORD)'
Build error occurred, build is stopped

This is the code:

LRESULT CALLBACK MouseHookProc(int nCode, WPARAM wParam, LPARAM lParam) {
    //...
}

void mousehookCustomRoutine(E_thread *me, void *arg = (void *)&MouseHookProc) {
    // arg is the ptr to LL Mouse Routine

    me->sendMessage(0x14,me,(void*)GetCurrentThreadId());
    // send message to self in order for my parent to know how to identify me via threadID
    HHOOK mousehook = SetWindowsHookEx(WH_MOUSE_LL, (LRESULT (*)(int,WPARAM,LPARAM))arg,NULL, 0); // I am line 78
    if (mousehook == NULL) printf("Mousehook error %lu\n",GetLastError());
    //...
}

It makes no sense because I am casting to the exact type that it expects to receive, there aren't any qualifiers or anything that are different. What could possibly be going on here?


问:
R shiny - combining ggplot2 and plotly to stack vertically 2 subplots
I would like to stack vertically 2 plots in a shiny app and use plotly to make them interactive.

I have the following code:

```<code>library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(

  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')),
    tabPanel('Plot2', plotly::plotlyOutput('plot2')),
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {

    output$plot <- renderPlot({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
        geom_line()
      p1 / p2
    })

    output$plot2 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
    })

    output$plot3 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
        geom_line()
      p1 / p2
    })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

As you can see when only using ggplot2 with the patchwork package ("Plot") it works as intended and stacks p1 and p2 vertically. Additionally, in "Plot2" when only plotting p1 with ggplot2, it becomes interactive with plotly.

However, in "Plot3" when trying to convert the combined graph (p1 / p2) of "Plot" created with patchwork to interactive using plotly, it only plots the p2 graph as interactive.

Any suggestions on how to create vertically stacked graphs using ggplot2 and then make them interactive with plotly in a Shiny App?

答:
In R plotly you can achive this via the subplot function:

```<code>library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(

  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')),
    tabPanel('Plot2', plotly::plotlyOutput('plot2')),
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {

  output$plot <- renderPlot({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
      geom_line()
    p1 / p2
  })

  output$plot2 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
  })

  output$plot3 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
      geom_line()
    subplot(p1, p2, nrows = 2)
  })
}

# Run the application
shinyApp(ui = ui, server = server)
</code>```

Please see this for more information.

ContentLicense: CC BY-SA 4.0

Body:
I would like to stack vertically 2 plots in a shiny app and use plotly to make them interactive.

I have the following code:

library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(

  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')),
    tabPanel('Plot2', plotly::plotlyOutput('plot2')),
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {

    output$plot <- renderPlot({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
        geom_line()
      p1 / p2
    })

    output$plot2 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
    })

    output$plot3 <- renderPlotly({
      p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
        geom_line()
      p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
        geom_line()
      p1 / p2
    })
}

# Run the application
shinyApp(ui = ui, server = server)

As you can see when only using ggplot2 with the patchwork package ("Plot") it works as intended and stacks p1 and p2 vertically. Additionally, in "Plot2" when only plotting p1 with ggplot2, it becomes interactive with plotly.

However, in "Plot3" when trying to convert the combined graph (p1 / p2) of "Plot" created with patchwork to interactive using plotly, it only plots the p2 graph as interactive.

Any suggestions on how to create vertically stacked graphs using ggplot2 and then make them interactive with plotly in a Shiny App?

Body:
In R plotly you can achive this via the subplot function:

library(shiny)
library(tidyverse)
library(patchwork)
library(plotly)

ui <- fluidPage(

  tabsetPanel(
    tabPanel('Plot', plotOutput('plot')),
    tabPanel('Plot2', plotly::plotlyOutput('plot2')),
    tabPanel('Plot3', plotly::plotlyOutput('plot3'))
  )
)

server <- function(input, output) {

  output$plot <- renderPlot({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
      geom_line()
    p1 / p2
  })

  output$plot2 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
  })

  output$plot3 <- renderPlotly({
    p1 <- ggplot(data = mtcars, aes(x = mpg, y = cyl)) +
      geom_line()
    p2 <- ggplot(data = mtcars, aes(x = mpg, y = disp)) +
      geom_line()
    subplot(p1, p2, nrows = 2)
  })
}

# Run the application
shinyApp(ui = ui, server = server)

Please see this for more information.


问:
Python exercise: lists sorting removing the nums
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

```<code>def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))
</code>```

but gives me this output:

```<code>[1, 2, 4, 7, 3]
</code>```

what did I do wrong? (only list comprehension should be used)

答:
You could do it with a comprehension in a call to .extend():

```<code>L1 = [1, 2, 5, 4, 7, 8, 3, 9]

L2 = L1[:1]
L2.extend(n for n in L1[1:] if n > L2[-1])

print(L2)
[1, 2, 5, 7, 8, 9]
</code>```

If you're allowed to use libraries, you could use accumulate to get the running maximum and compare it to each position:

```<code>from itertools import accumulate
L2 = [n for n,m in zip(L1,accumulate(L1,max)) if n>=m]
</code>```

Body:
'Write a filter_ordered function that receives a list L1 of integers and returns a list L2 obtained starting from L1, eliminating all the elements that violate the growing order. In other words, an element of L1 must be inserted in L2 if and only if it is greater than all the elements that precede it in L1.

Example: If L1 = [1, 2, 5, 4, 7, 8, 3, 9] then filter_sorted (L1) returns the list L2 = [1, 2, 5, 7, 8, 9].'

this is my code:

def filtra_ordinati(l1):
    l2 = []
    for y in range(1,len(l1)):
        if l1[y-1] < l1[y]:
            l2.append(l1[y-1])
    return l2

L1 = [1, 2, 5, 4, 7, 8, 3, 9]
print(filtra_ordinati(L1))

but gives me this output:

[1, 2, 4, 7, 3]

what did I do wrong? (only list comprehension should be used)

Body:
You could do it with a comprehension in a call to .extend():

L1 = [1, 2, 5, 4, 7, 8, 3, 9]

L2 = L1[:1]
L2.extend(n for n in L1[1:] if n > L2[-1])

print(L2)
[1, 2, 5, 7, 8, 9]

If you're allowed to use libraries, you could use accumulate to get the running maximum and compare it to each position:

from itertools import accumulate
L2 = [n for n,m in zip(L1,accumulate(L1,max)) if n>=m]


问:
How do I make an html link look like a button?
I'm using ASP.NET, some of my buttons just do redirects.  I'd rather they were ordinary links, but I don't want my users to notice much difference in the appearance.  I considered images wrapped by anchors, i.e.  tags, but I don't want to have to fire up an image editor every time I change the text on a button.</p>

答:
```<code>a {
    display: block;
    height: 20px;
    width: auto;
    border: 1px solid #000;
}
</code>```

You can play with  tags like this if you give them a block display. You can adjust the border to give a shade like effect and the background color for that button feel :)

OwnerDisplayName: MatthewMartin

ContentLicense: CC BY-SA 2.5

Body:
a {
    display: block;
    height: 20px;
    width: auto;
    border: 1px solid #000;
}

You can play with <a> tags like this if you give them a block display. You can adjust the border to give a shade like effect and the background color for that button feel :)

OwnerDisplayName: Ólafur Waage


问:
Java application UI layout
Alright, basically I have this java program and I want to have a home screen of sorts. I want to be able to see the current progress in a scroll pane of sorts that has multiple panels that can be added and removed. These panels will contain a progress bar and a cancel button as well as a label to identify the task. How would I go about adding and removing these panels to this scroll pane? Should I have one panel and create the task progress panels within it? Would I be able to "stack" them vertically as I add them, with the oldest panel at the bottom?

Some help would be appreciated. I was thinking maybe a JTable with a custom cell editor, but it doesn't allow very big panels to be created. Should I go further and make a custom JTable class of sorts, and JList can have a bigger panel size but they are only painted and not intractable.

So as I said, any help would be appreciated. Please and thank you.

答:
Going with your original JPanel idea, you can have a scroll pane with a panel inside it. Then, you can create panels with your data and add the new panels to the main panel in the scroll pane. Your main JPanel (the one in the scroll pane) should use a BoxLayout with a vertical alignment, this will stack panels on top of each other.

If you want to use a JTable you can, and change the cells to a JTextArea instead of a JTextField. It's doable, but I'd have to dig up some old code to figure out how again.

Title: Java application UI layout


问:
c language fibonacci squence

#include<stdio.h>
void main()
{
    int fib1=0,fib2=1,fib3,limit,count = 0;
    printf("Enter the number uptill which the seriese has to be generated\n");
    scanf("%d",&limit);
    printf("===THE FIBONACCI SERIES IS===\n");
    printf("%d\n",&fib1);
    printf("%d\n",&fib2);
    count=2;
    while (count<limit){
        fib3=fib1 + fib2;
        count++;
        printf("%d\n",fib3);
        fib1=fib2;
        fib2=fib3;
    }
    return 0;

}
```

the &symbol after fib 1 variable is affecting the program but I don't know why any help will be greatly appreciated

答:
As noted in comments, you are printing the addresses of fib1 and fib2.

```<code>    printf("%d\n",&fib1);
    printf("%d\n",&fib2);
</code>```

You should be printing their values.

```<code>    printf("%d\n", fib1);
    printf("%d\n", fib2);
</code>```

You are likely confused because you would pass the address to scanf, but that is because scanf needs to modify the value of those variables, so it needs their address is memory. The printf function does not need to modify the data, so a copy of the value is all it needs.

Title: c language fibonacci squence

Body:
#include<stdio.h>
void main()
{
    int fib1=0,fib2=1,fib3,limit,count = 0;
    printf("Enter the number uptill which the seriese has to be generated\n");
    scanf("%d",&limit);
    printf("===THE FIBONACCI SERIES IS===\n");
    printf("%d\n",&fib1);
    printf("%d\n",&fib2);
    count=2;
    while (count<limit){
        fib3=fib1 + fib2;
        count++;
        printf("%d\n",fib3);
        fib1=fib2;
        fib2=fib3;
    }
    return 0;

}

the &symbol after fib 1 variable is affecting the program but I don't know why any help will be greatly appreciated

Body:
As noted in comments, you are printing the addresses of fib1 and fib2.

    printf("%d\n",&fib1);
    printf("%d\n",&fib2);

You should be printing their values.

    printf("%d\n", fib1);
    printf("%d\n", fib2);

You are likely confused because you would pass the address to scanf, but that is because scanf needs to modify the value of those variables, so it needs their address is memory. The printf function does not need to modify the data, so a copy of the value is all it needs.


问:
how fix cycle in django?
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again.

vds.html

```<code>{% for item in allobjects %}

  <div class="container-fluid">
        <div class="body2">
      <li class="title">{{item.title}}</li>
      <li class="listram">{{item.ram}}<small>ГБ(озу)</small></li>
      <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img>
      <li class="cpu">{{item.cpu}} vCore</li>
      <img class="cpu1"width="51px" height="50px"  src="/static/main/images/cpu.png" ></img>
     <li class="hdd">{{item.hdd}}<small> ГБ(ssd)</small></li>
     <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img>
     <li class="os">Установка любой ос</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/>
     <li class="os">Виртуализация KVM</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/>
     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>
     <li class= "prise">{{item.name}}₽/месяц</li>
  </div>
  </div>

  <div class="container-fluid">
        <div class="body3">
      <li class="title">{{item.title}}</li>
      <li class="listram"><small>ГБ(озу)</small></li>
      <img class="ram2"width="51px" height="49px" src="/static/main/images/ram.png" ></img>
      <li class="cpu">2 vCore</li>
      <img class="cpu1"width="51px" height="50px"  src="/static/main/images/cpu.png" ></img>
     <li class="hdd">40<small> ГБ(ssd)</small></li>
     <img class="hdd1"width="51px" height="50px" src="/static/main/images/hdd.png" ></img>
     <li class="os">Установка любой ос</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/os.png"/>
     <li class="os">Виртуализация KVM</li>
     <img  class="os1 " width="47px" height="49px"src="/static/main/images/vds.png"/>
     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>
     <li class= "prise">600 ₽/месяц</li>
  </div>
  </div>
{% endfor %}
</code>```

models.py

```<code>class VDSTARIFS( models.Model):
    id = models.CharField(max_length=40, primary_key= True,serialize=True)
    name = models.CharField(max_length=20, verbose_name = 'Цены')
    choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
    title = models.CharField(max_length= 15)
    ram = models.CharField(max_length=10)
    hdd = models.CharField(max_length= 10)
    cpu = models.CharField(max_length=10)

    def __str__(self):
        return str(self.title)

</code>```

views.py

```<code>def vds(request):
    servers = VDSTARIFS.objects.all() ##Maybe filter
    context1 = {
        'allobjects': servers
    }
    return render(request,'vds.html',context1)
</code>```

答:
Change your views.py to return values for id=1 as

```<code>def vds(request):
    servers = VDSTARIFS.objects.filter(id=1)
    context1 = {
        'allobjects': servers
    }
    return render(request, 'vds.html', context1)
</code>```

Title: how fix cycle in django?

Body:
I have problem with cycle in djano(Maybe I dont understand this).I have cycle in template and it must to output value from database,but Idk how I can create cycle,which may output value from (id = 1),because this cycle output value (id = 0) again and again.

vds.html

{% for item in allobjects %}

{{item.title}}

{{item.ram}}ГБ(озу)

{{item.cpu}} vCore

{{item.hdd}} ГБ(ssd)

Установка любой ос

Виртуализация KVM

     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>

{{item.name}}₽/месяц

{{item.title}}

ГБ(озу)

2 vCore

40 ГБ(ssd)

Установка любой ос

Виртуализация KVM

     <form action="https://billing.king-host.ru">
         <button type="submit" name="buy">Купить</button>
         </form>

600 ₽/месяц

{% endfor %}

models.py

class VDSTARIFS( models.Model):
    id = models.CharField(max_length=40, primary_key= True,serialize=True)
    name = models.CharField(max_length=20, verbose_name = 'Цены')
    choosen = models.CharField(max_length= 20, choices = CHOOSE, verbose_name = 'Тариф', help_text='Выбор тарифного плана.')
    title = models.CharField(max_length= 15)
    ram = models.CharField(max_length=10)
    hdd = models.CharField(max_length= 10)
    cpu = models.CharField(max_length=10)

    def __str__(self):
        return str(self.title)

views.py

def vds(request):
    servers = VDSTARIFS.objects.all() ##Maybe filter
    context1 = {
        'allobjects': servers
    }
    return render(request,'vds.html',context1)

Body:
Change your views.py to return values for id=1 as

def vds(request):
    servers = VDSTARIFS.objects.filter(id=1)
    context1 = {
        'allobjects': servers
    }
    return render(request, 'vds.html', context1)


问:
I How to make a static tooltip in bootstrap 4
On the Bootstrap web site there's a demonstration for static tooltips, I've copied the html generated to replicate the tooltip in my project but it didn't work.  Even though Bootstrap 4 is in development, the documentation could be much better.  static tooltip

I've tried

```<code><div  class="tooltip tooltip-right" role="tooltip"> <div class="tooltip-inner"> veicle code </div></div>
</code>```

I added

Obs: The dynamic examples work.

答:
If the goal is to show a tooltip, and make it always visible:

For anyone getting here working with more recent versions of Bootstrap, on Bootstrap 5 you can just define the trigger as manual, and all mouse events will be ignored. Then, just show the tooltip when you want, and it will stay there (until you remove it using Javascript).

Example tooltip (using bootstrap 5):

```<code><button id="example" type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" title="Tooltip on top" data-bs-trigger="manual">
  Example tooltip on button
</button>
</code>```

Javascript:

```<code>var exampleBtn = document.getElementById('example');
var tooltip = new bootstrap.Tooltip(exampleBtn);
tooltip.show();
</code>```

Body:
On the Bootstrap web site there's a demonstration for static tooltips, I've copied the html generated to replicate the tooltip in my project but it didn't work.  Even though Bootstrap 4 is in development, the documentation could be much better.  static tooltip

I've tried

 veicle code

I added

Obs: The dynamic examples work.

Body:
If the goal is to show a tooltip, and make it always visible:

For anyone getting here working with more recent versions of Bootstrap, on Bootstrap 5 you can just define the trigger as manual, and all mouse events will be ignored. Then, just show the tooltip when you want, and it will stay there (until you remove it using Javascript).

Example tooltip (using bootstrap 5):

<button id="example" type="button" class="btn btn-secondary" data-bs-toggle="tooltip" data-bs-placement="top" title="Tooltip on top" data-bs-trigger="manual">
  Example tooltip on button
</button>

Javascript:

var exampleBtn = document.getElementById('example');
var tooltip = new bootstrap.Tooltip(exampleBtn);
tooltip.show();


答:
in this line that you mapped your items into NavItem
{NoteItems.map((items)=><NavItems key={items.id} items={items} onClick={handleNoteClick}/>)}
the onClick just point to the function and you cant pass pointer like handleNoteClick(id) because its excuted not pointed and your not passing the id to the function though
do this i think it should work
{NoteItems.map((items)=><NavItems key={items.id} items={items} onClick={()=>handleNoteClick(items.id)}/>)}

and of course you should pass custom prop onClick to your custom component native onclick

Title: React onClick not changing color of item


问:
How to automate shadow DOM elements using selenium?
I am using Java Selenium project for web page automation. The web page contains lots of multi-level shadow-root DOM elements that I am not able to interact with using selenium findElement method.

I have tried the following solutions:

deep css (Don't work on latest chrome browser)

JS Executor. (This is really tedious and becomes complex to maintain)

Note:

If you know any other solution other than listed above that I can implement in Selenium Java framework , please pass on the solution. Thanks in advance !.

答:
With Selenium 4 there is now WebElement.getShadowRoot().  For example:

```<code>driver.findElement(By.id("parentId")).getShadowRoot().findElement(By.cssSelector("label")).findElement(By.tagName("input"))
</code>```

As normal with a #shadow-root, the navigation choices for the next hop are limited.  E.g. against Chrome By.cssSelector() and By.className() are valid, but By.id() and By.tagName() fail with org.openqa.selenium.InvalidArgumentException: invalid argument: invalid locator

Body:
With Selenium 4 there is now WebElement.getShadowRoot().  For example:

driver.findElement(By.id("parentId")).getShadowRoot().findElement(By.cssSelector("label")).findElement(By.tagName("input"))

As normal with a #shadow-root, the navigation choices for the next hop are limited.  E.g. against Chrome By.cssSelector() and By.className() are valid, but By.id() and By.tagName() fail with org.openqa.selenium.InvalidArgumentException: invalid argument: invalid locator


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

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

The commands I used:

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

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

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

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

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

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

The file looks like this:

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

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

答:
If you don't REALLY want the string /Components to be added in the middle of some output lines then this may be what you want, using any awk in any shell on every Unix box:

```<code>$ awk -v RS=' ' 'sub("^-I[./]*","")' file
Common/Component
Common/Component1
Common/Component2
Common/Component3
Common/Component4
Common/Component5
Common/Component6
Comp
App
</code>```

That would fail if any of the paths in your input contained blanks but you don't show that as a possibility in your question so I assume it can't happen.

Title: Combine multiple sed commands into one

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

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

The commands I used:

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

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

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

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

and then I'm deleting all the unnecessary files.

I'm trying to get the following result:

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

The file looks like this:

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

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

Body:
If you don't REALLY want the string /Components to be added in the middle of some output lines then this may be what you want, using any awk in any shell on every Unix box:

$ awk -v RS=' ' 'sub("^-I[./]*","")' file
Common/Component
Common/Component1
Common/Component2
Common/Component3
Common/Component4
Common/Component5
Common/Component6
Comp
App

That would fail if any of the paths in your input contained blanks but you don't show that as a possibility in your question so I assume it can't happen.


答: The compiler is omitting the calling convention from the error message -- SetWindowsHookEx wants a LRESULT (__stdcall *)(int,WPARAM,LPARAM), but you're passing it a LRESULT (__cdecl *)(int,WPARAM,LPARAM).

Title: Strange "invalid conversion from <type> to <type>" error


问:
Intellij - Not able to read a file from other package in the same module
I am using Intellij Idea - 2021.3.2 and Java 8. In Intellij, I am not able to read a file in another package in the same module. The file is under main and not resource folder. But in Eclipse, I am able to read.

For example. Below code prints different outputs in both eclipse and intellij.

```<code>    import java.net.URL;

public class TestMain {
    public static void main(String[] args) {
        URL resource = TestMain.class.getResource("/org/files/input.txt");
        if(resource == null) {
            System.out.println("Resource is null");
        } else {
            System.out.println("Resource found!!");
        }
    }
}
</code>```

In Intellij, the code prints "Resource is null", but in eclipse, the code prints "Resource found!!".

Is there any setting I need to enable/disable in intellij ? Why code is behaving different in Intellij Idea ?

答:
Move the file into resources/org/files.

.txt files are not copied to classpath from the source roots by Maven conventions.

If you want to copy these files from the source roots, you need to adjust pom.xml configuration: https://stackoverflow.com/a/23289401/104891.

Eclipse is not following the conventions and you will get different results in command line Maven and in the IDE, which is bad.

Body:
I am using Intellij Idea - 2021.3.2 and Java 8. In Intellij, I am not able to read a file in another package in the same module. The file is under main and not resource folder. But in Eclipse, I am able to read.

For example. Below code prints different outputs in both eclipse and intellij.

    import java.net.URL;

public class TestMain {
    public static void main(String[] args) {
        URL resource = TestMain.class.getResource("/org/files/input.txt");
        if(resource == null) {
            System.out.println("Resource is null");
        } else {
            System.out.println("Resource found!!");
        }
    }
}

In Intellij, the code prints "Resource is null", but in eclipse, the code prints "Resource found!!".

Is there any setting I need to enable/disable in intellij ? Why code is behaving different in Intellij Idea ?


问:
Spring integration: no such method exception for custom inbound channel adapter
I am trying to invoke processMessage method from my As2MessageHandler class as my entry point into spring integration using a custom inbound-channel-adapter. But I keep getting this error saying it can't find the method when it is clearly in the class:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'as2.source': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: no such method 'processMessage' is available on class com.as2example.myexample.handler.As2MessageHandler

as2MessageHandler class:

```<code>
@Component
public class As2MessageHandler extends AbstractProcessorModule implements IProcessorStorageModule {

    private static final Logger LOGGER = LoggerFactory.getLogger(As2MessageHandler.class);

    @Override
    public boolean canHandle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info(" Handle Info:" + s);

        return s.equals(DO_STORE);
    }

    @Override
    public void handle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) throws AS2Exception {

        LOGGER.info("----- AS2 MESSAGE RECEIVED !!! ------");

        LOGGER.info(iMessage.getContentType());
        LOGGER.info(iMessage.getContentDisposition());
        LOGGER.info(iMessage.getAsString());

        processMessage(iMessage);

    }

    public String processMessage(IMessage message) {

        LOGGER.info("BEGIN PROCESSING MESSAGE");

        return message.getAsString();
    }

}

</code>```

integration.xml file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
         https://www.springframework.org/schema/integration/spring-integration.xsd">

    <int:channel id="as2MessageChannel">
        <int:interceptors>
            <int:wire-tap channel="logger"/>
        </int:interceptors>
    </int:channel>

    <int:logging-channel-adapter id="logger" level="DEBUG"/>

    <int:inbound-channel-adapter id="as2" ref="as2MessageHandler" method="processMessage" channel="as2MessageChannel">

    </int:inbound-channel-adapter>

    <int:service-activator input-channel="as2MessageChannel" ref="orderServiceImpl" auto-startup="true"/>

</beans>
</code>```

MyApplication class:

```<code>@SpringBootApplication
@ImportResource("classpath:/integration/integration.xml")
public class MyApplication implements ServletContextListener {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);
    }

    @Override
    public void contextDestroyed (final ServletContextEvent sce)
    {
        ServletConfig.shutDown ();
        AS2WebAppListener.staticDestroy ();
    }

}
</code>```

Can anyone provide insight into why spring integration is not recognizing the processMethod from the As2MessageHandler class? I've tried changing the method to use messagebuilder and return a Message type but that wasn't the issue. Now I'm thinking it has to be something else.

答:
The error is correct. It might mislead a little bit since the signature of the method is wrong, not its presence. So, since an inbound channel adapter is a beginning of the flow, there really cannot be any input to the method to produce data for messages. Therefore it is not clear what is your expectation with that IMessage as an input for the method.

It is not clear what is your design, but the POJO method in the <int:inbound-channel-adapter> is invoked by the poller as a source of data for the message. In other words the POJO method as a source must not have arguments - only return. That's why that exception is thrown.

I don't see anything in your As2MessageHandler which could server as a source for messages in the inbound channel adapter. This one looks more like a service activator. Please, revise your design in favor of something else what really may be used as a source of data in that AS2 protocol.

Body:
I am trying to invoke processMessage method from my As2MessageHandler class as my entry point into spring integration using a custom inbound-channel-adapter. But I keep getting this error saying it can't find the method when it is clearly in the class:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'as2.source': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: no such method 'processMessage' is available on class com.as2example.myexample.handler.As2MessageHandler

as2MessageHandler class:

@Component
public class As2MessageHandler extends AbstractProcessorModule implements IProcessorStorageModule {

    private static final Logger LOGGER = LoggerFactory.getLogger(As2MessageHandler.class);

    @Override
    public boolean canHandle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) {
        LOGGER.info(" Handle Info:" + s);

        return s.equals(DO_STORE);
    }

    @Override
    public void handle(@Nonnull String s, @Nonnull IMessage iMessage, @Nullable Map<String, Object> map) throws AS2Exception {

        LOGGER.info("----- AS2 MESSAGE RECEIVED !!! ------");

        LOGGER.info(iMessage.getContentType());
        LOGGER.info(iMessage.getContentDisposition());
        LOGGER.info(iMessage.getAsString());

        processMessage(iMessage);

    }

    public String processMessage(IMessage message) {

        LOGGER.info("BEGIN PROCESSING MESSAGE");

        return message.getAsString();
    }

}

integration.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:int="http://www.springframework.org/schema/integration"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/integration
         https://www.springframework.org/schema/integration/spring-integration.xsd">

    <int:channel id="as2MessageChannel">
        <int:interceptors>
            <int:wire-tap channel="logger"/>
        </int:interceptors>
    </int:channel>

    <int:logging-channel-adapter id="logger" level="DEBUG"/>

    <int:inbound-channel-adapter id="as2" ref="as2MessageHandler" method="processMessage" channel="as2MessageChannel">

    </int:inbound-channel-adapter>

    <int:service-activator input-channel="as2MessageChannel" ref="orderServiceImpl" auto-startup="true"/>

</beans>

MyApplication class:

@SpringBootApplication
@ImportResource("classpath:/integration/integration.xml")
public class MyApplication implements ServletContextListener {

    public static void main(String[] args) {

        SpringApplication.run(MyApplication.class, args);
    }

    @Override
    public void contextDestroyed (final ServletContextEvent sce)
    {
        ServletConfig.shutDown ();
        AS2WebAppListener.staticDestroy ();
    }

}

Can anyone provide insight into why spring integration is not recognizing the processMethod from the As2MessageHandler class? I've tried changing the method to use messagebuilder and return a Message type but that wasn't the issue. Now I'm thinking it has to be something else.


问:
ROBOT FRAMEWORK: How to make test teardown execute only if test case fails?
I could use the "TEST TEARDOWN" keyword in the header but this gets executed after each test case. Is there any way I can do in the code so that it only executes if the test case fails and if otherwise, skips?</p>

答:
The keyword Run Keyword If Test Failed was created for that case.
Better have Robotframework documentation always at hand (and browse trough it at least once).

Here is a special note about it:

```<code>This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error.
</code>```

Body:
The keyword Run Keyword If Test Failed was created for that case.
Better have Robotframework documentation always at hand (and browse trough it at least once).

Here is a special note about it:

This keyword can only be used in a test teardown. Trying to use it anywhere else results in an error.


问:
Can I include the week number in a datetime value?
I have a dataset the includes a 'Year', 'Week' and 'Date' column. The Year and Week are redundant so I'm going to drop them, however I wanted to know if it was possible to include the week number within the datetime values currently formatted as %YYYY-%MM-%DD-%hh-%mm-%ss. I'm basically going for something like %YYYY-%MM-%WW-%DD-%hh-%mm-%ss. For example, I'm currently working with:

Year
Week
Date

2021
01
2021-01-01-00-00-01

2021
02
2021-01-08-00-00-01

But I'm trying to drop the 'Year' and Week' columns giventhat info is in the 'Date' column. It's no issue with the year since the datetime format already includes year, but I also want it to include the week number to have something like 2021-01-02-08-00-00-01 in the second row. Basically the final table should look like:

Date

2021-01-02-08-00-00-01

答:
Dropping the unwanted columns:

```<code>df = df.drop(columns=['Year', 'Week'])
</code>```

Formatting the date:

Use strftime to format the date (see the strftime documentation as reference for the format, in particulat %U for the week number)

```<code># format to %YYYY-%MM-%DD-%WW-%hh-%mm-%ss
df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d-%U-%H-%M-%S')
</code>```

output:

```<code>                     Date
0  2021-01-01-00-00-00-00
1  2021-01-08-01-00-00-00
</code>```

NB. I formatted to %YYYY-%MM-%DD-%WW-%hh-%mm-%ss, (not %YYYY-%MM-%WW-%DD-%hh-%mm-%ss) to match the provided output, but its easy enough to change if %YYYY-%MM-%WW-%DD-%hh-%mm-%ss is really what you need, just swap %d and %U

Body:
Dropping the unwanted columns:

df = df.drop(columns=['Year', 'Week'])

Formatting the date:

Use strftime to format the date (see the strftime documentation as reference for the format, in particulat %U for the week number)

# format to %YYYY-%MM-%DD-%WW-%hh-%mm-%ss
df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%Y-%m-%d-%U-%H-%M-%S')

output:

                     Date
0  2021-01-01-00-00-00-00
1  2021-01-08-01-00-00-00

NB. I formatted to %YYYY-%MM-%DD-%WW-%hh-%mm-%ss, (not %YYYY-%MM-%WW-%DD-%hh-%mm-%ss) to match the provided output, but its easy enough to change if %YYYY-%MM-%WW-%DD-%hh-%mm-%ss is really what you need, just swap %d and %U


问:
Make li element width the max of siblings, itself, and parent li
I've looked at several related posts here and none seem to cut to the core of my challenge.

The scenario is that I have an li element that contains a ul element. I want the widths of the li elements inside the contained ul to be at least as wide as the parent li.

Below are two examples. The first example displays the way I want it to. The second illustrates the issue. I want the items that start "Sub-Item 1" and "Sub-Item 2" to take on the width of the item that starts "Long Item". If you run the code snippet it should be pretty clear what I am after.

I am looking for a 100% CSS solution.

Any assistance would be appreciated.

     ```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div style="position:absolute;top:0;">Example 1
        <ul>
            <li>
                Short Item
                <ul>
                    <li>This is longer than First Item and displays as desired.</li>
                    <li>Filler - width is same as sibling</li>
                </ul>
            </li>
        </ul>
    </div>
    <div style="position:absolute; top:200px;">Example 2
        <ul>

            <li>
                Long Item - This is deliberately longer. I want the width of li below to display as wide but it doesn't
                <ul>
                    <li>Sub-Item 1: Shorter than Long Item and does NOT display as desired</li>
                    <li>Sub Item 2: Filler - width is same as sibling</li>
                </ul>
            </li>
        </ul>
    </div></code>```

答:
This can be accomplished by using flex and wrapping the "Short Item" text in a span tag.

 ul {
            display: flex;
            padding:0;
        }
        ul li {
            position: relative;
            display: flex;
            flex-basis: auto;
            flex-direction: column;
            list-style: none;
            text-decoration: none;
            background-color: red;
            white-space:nowrap;

        }
        span{
          flex-basis: auto;
          flex-grow: 1;
        }
            ul li ul {
                display: flex;
                flex-direction: column;
                text-align: left;
                background-color: lightgoldenrodyellow;
                padding:0;
            }
        ul li ul li {
            text-align: left;
            width: 100%;
            margin-left: 0;
            border-style: none;
            background-color: lightgoldenrodyellow;
            padding:0;
        }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>Example 1
        <ul>
            <li>
                <span>Short Item</span>
                <ul>
                    <li>This is longer than First Item and displays as desired.</li>
                    <li>Filler - width is same as sibling</li>
                </ul>
            </li>
        </ul>
    </div>
   </code>```

Body:
I've looked at several related posts here and none seem to cut to the core of my challenge.

The scenario is that I have an li element that contains a ul element. I want the widths of the li elements inside the contained ul to be at least as wide as the parent li.

Below are two examples. The first example displays the way I want it to. The second illustrates the issue. I want the items that start "Sub-Item 1" and "Sub-Item 2" to take on the width of the item that starts "Long Item". If you run the code snippet it should be pretty clear what I am after.

I am looking for a 100% CSS solution.

Any assistance would be appreciated.

Example 1

                Short Item

This is longer than First Item and displays as desired.

Filler - width is same as sibling

Example 2

                Long Item - This is deliberately longer. I want the width of li below to display as wide but it doesn't

Sub-Item 1: Shorter than Long Item and does NOT display as desired

Sub Item 2: Filler - width is same as sibling

Body:
This can be accomplished by using flex and wrapping the "Short Item" text in a span tag.

 ul {
            display: flex;
            padding:0;
        }
        ul li {
            position: relative;
            display: flex;
            flex-basis: auto;
            flex-direction: column;
            list-style: none;
            text-decoration: none;
            background-color: red;
            white-space:nowrap;

        }
        span{
          flex-basis: auto;
          flex-grow: 1;
        }
            ul li ul {
                display: flex;
                flex-direction: column;
                text-align: left;
                background-color: lightgoldenrodyellow;
                padding:0;
            }
        ul li ul li {
            text-align: left;
            width: 100%;
            margin-left: 0;
            border-style: none;
            background-color: lightgoldenrodyellow;
            padding:0;
        }

<div>Example 1
        <ul>
            <li>
                <span>Short Item</span>
                <ul>
                    <li>This is longer than First Item and displays as desired.</li>
                    <li>Filler - width is same as sibling</li>
                </ul>
            </li>
        </ul>
    </div>


问:
Traefik yml acme email value from environment variables
I use a compose file with two services (Python app & Traefik), in the docker file I load all the environment variables.

For Traefik I use a YML file to define the services, In that YML file I have a node for certificateResolvers, that node looks like this:

```<code>certificatesResolvers:
  letsencrypt:
    acme:
      email: "email@domain.com"
      storage: /etc/traefik/acme/acme.json
      httpChallenge:
        entryPoint: web
</code>```

I want to set the email from a environment variable so the YML file should looks like this:

```<code>certificatesResolvers:
  letsencrypt:
    acme:
      email: '{{env "USER_EMAIL"}}'
      storage: /etc/traefik/acme/acme.json
      httpChallenge:
        entryPoint: web
</code>```

Having the YML in this way I got this in the Logs:

```<code>level=info msg="Starting provider *acme.Provider {\"email\":\"{{env \\\"USER_EMAIL\\\"}}\",\"caServer\":\"https://acme-v02.api.letsencrypt.org/directory\",\"storage\":\"/etc/traefik/acme/acme.json\",\"keyType\":\"RSA4096\",\"httpChallenge\":{\"entryPoint\":\"web\"},\"ResolverName\":\"letsencrypt\",\"store\":{},\"ChallengeStore\":{}}"

level=error msg="Unable to obtain ACME certificate for domains \"domain.com\": cannot get ACME client acme: error: 400 :: POST :: https://acme-v02.api.letsencrypt.org/acme/new-acct :: urn:ietf:params:acme:error:invalidEmail :: Error creating new account :: \"{{env \\\"USER_EMAIL\\\"}}\" is not a valid e-mail address, url: " providerName=letsencrypt.acme routerName=web-secure-router@file rule="Host(`domain.com`)"
</code>```

I tried with:

```<code>email: '{{env "USER_EMAIL"}}'
email: '`{{env "USER_EMAIL"}}`'
email: "{{env 'USER_EMAIL'}}"
email: "{{env USER_EMAIL}}"
</code>```

But none of those worked.

In the same YML file I have a node that looks like this:

```<code>http:
  routers:
    web-secure-router:
      rule: 'Host(`{{env "PROJECT_HOSTNAME"}}`)'

      entryPoints:
        - web-secure
      service: fastapi
      tls:
        certResolver: letsencrypt
</code>```

In that section, I get the right value of the PROJECT_HOSTNAME variable, in this case domain.com as you can see in the Logs above

答:
To clarify on why you cannot use your own user defined environment variable for certificatesResolvers is because this is part of the static configuration, whereas the http is part of the dynamic configuration (where you can use your own like PROJECT_HOSTNAME)

You can still use TRAEFIK Environment variables to set the email for your certificate resolver with the variable TRAEFIK_CERTIFICATESRESOLVERS_<NAME>_ACME_EMAIL.

I haven't tested this myself, but I think the following should do the trick:

services:
  traefik:
    environment:
       TRAEFIK_CERTIFICATESRESOLVERS_LETSENCRYPT_ACME_EMAIL: ${USER_EMAIL}
```

Body:
I use a compose file with two services (Python app & Traefik), in the docker file I load all the environment variables.

For Traefik I use a YML file to define the services, In that YML file I have a node for certificateResolvers, that node looks like this:

certificatesResolvers:
  letsencrypt:
    acme:
      email: "email@domain.com"
      storage: /etc/traefik/acme/acme.json
      httpChallenge:
        entryPoint: web

I want to set the email from a environment variable so the YML file should looks like this:

certificatesResolvers:
  letsencrypt:
    acme:
      email: '{{env "USER_EMAIL"}}'
      storage: /etc/traefik/acme/acme.json
      httpChallenge:
        entryPoint: web

Having the YML in this way I got this in the Logs:

level=info msg="Starting provider *acme.Provider {\"email\":\"{{env \\\"USER_EMAIL\\\"}}\",\"caServer\":\"https://acme-v02.api.letsencrypt.org/directory\",\"storage\":\"/etc/traefik/acme/acme.json\",\"keyType\":\"RSA4096\",\"httpChallenge\":{\"entryPoint\":\"web\"},\"ResolverName\":\"letsencrypt\",\"store\":{},\"ChallengeStore\":{}}"

level=error msg="Unable to obtain ACME certificate for domains \"domain.com\": cannot get ACME client acme: error: 400 :: POST :: https://acme-v02.api.letsencrypt.org/acme/new-acct :: urn:ietf:params:acme:error:invalidEmail :: Error creating new account :: \"{{env \\\"USER_EMAIL\\\"}}\" is not a valid e-mail address, url: " providerName=letsencrypt.acme routerName=web-secure-router@file rule="Host(`domain.com`)"

I tried with:

email: '{{env "USER_EMAIL"}}'
email: '`{{env "USER_EMAIL"}}`'
email: "{{env 'USER_EMAIL'}}"
email: "{{env USER_EMAIL}}"

But none of those worked.

In the same YML file I have a node that looks like this:

http:
  routers:
    web-secure-router:
      rule: 'Host(`{{env "PROJECT_HOSTNAME"}}`)'

      entryPoints:
        - web-secure
      service: fastapi
      tls:
        certResolver: letsencrypt

In that section, I get the right value of the PROJECT_HOSTNAME variable, in this case domain.com as you can see in the Logs above


问:
jQuery slideToggle current div and slideUp the rest divs that are visible
I am trying to build a FAQ page where there is a div, on click it should slideToggle another div inside of it for visibility.

Once if it is clicked I want any other divs except this one, that are visible to slideUP.

My code currently works absolutely different from what I would like. I think the issue is with the .slideUp() part to find the other elements ("faq-f-a:visible") that are visible.

$(document).ready(function(){

  // FAQ Q1
  $(".faq-q1").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a1").slideToggle(500);
  });

  // FAQ Q2
  $(".faq-q2").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a2").slideToggle(500);
  });

// FAQ Q3
  $(".faq-q3").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a3").slideToggle(500);
  });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #FFF;
  padding: 50px;
  font-family: Helvetica;
}

#faq-f-wrap {
  padding: 40px;
  font-size: 25px;
  text-align: center;
  margin: 0 auto;
  width: 300px;
  cursor: pointer;
}

#faq-f-a {
  display: none;
}</code>```

    (1) This is a Question

      This is an answare!

    (2) This is a Question

      This is an answare!

    (3) This is a Question

      This is an answare!

```

JsFiddle Here

答:
You seem to swap ID and class

I would expect this - I changed most IDs to class.

You actually do not even need the IDs anymore

$(document).ready(function() {
  $(".faq-q").click(function() {
    const $ans = $(this).closest(".faq-f-wrap").find(".faq-a")
    $(".faq-a:visible").not($ans).slideUp();
    $ans.slideToggle(500);
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  background: #FFF;
  padding: 50px;
  font-family: Helvetica;
}

.faq-f-wrap {
  padding: 40px;
  font-size: 25px;
  text-align: center;
  margin: 0 auto;
  width: 300px;
  cursor: pointer;
}

.faq-a {
  display: none;
}</code>```

    1
    This is a Question

      This is an answer!

    2
    This is a Question

      This is an answer!

    3
    This is a Question

      This is an answer!

```

Body:
I am trying to build a FAQ page where there is a div, on click it should slideToggle another div inside of it for visibility.

Once if it is clicked I want any other divs except this one, that are visible to slideUP.

My code currently works absolutely different from what I would like. I think the issue is with the .slideUp() part to find the other elements ("faq-f-a:visible") that are visible.

$(document).ready(function(){

  // FAQ Q1
  $(".faq-q1").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a1").slideToggle(500);
  });

  // FAQ Q2
  $(".faq-q2").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a2").slideToggle(500);
  });

// FAQ Q3
  $(".faq-q3").click(function(){
    $("#faq-f-a:visible").not(this).slideUp();
    $(".faq-a3").slideToggle(500);
  });

});

body {
  background: #FFF;
  padding: 50px;
  font-family: Helvetica;
}

#faq-f-wrap {
  padding: 40px;
  font-size: 25px;
  text-align: center;
  margin: 0 auto;
  width: 300px;
  cursor: pointer;
}

#faq-f-a {
  display: none;
}

    (1) This is a Question

      This is an answare!

    (2) This is a Question

      This is an answare!

    (3) This is a Question

      This is an answare!

JsFiddle Here

Body:
You seem to swap ID and class

I would expect this - I changed most IDs to class.

You actually do not even need the IDs anymore

$(document).ready(function() {
  $(".faq-q").click(function() {
    const $ans = $(this).closest(".faq-f-wrap").find(".faq-a")
    $(".faq-a:visible").not($ans).slideUp();
    $ans.slideToggle(500);
  });
});

body {
  background: #FFF;
  padding: 50px;
  font-family: Helvetica;
}

.faq-f-wrap {
  padding: 40px;
  font-size: 25px;
  text-align: center;
  margin: 0 auto;
  width: 300px;
  cursor: pointer;
}

.faq-a {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- FAQ 01 -->
<div class="faq-f-wrap">
  <div id="faq-f-q1" class="faq-q">
    <span id="faq-f-id1">1</span>
    <span id="faq-f-txt1">This is a Question</span>

    <div id="faq-f-a1" class="faq-a">
      <span id="faq-f-ans1">This is an answer!</span>
    </div>
  </div>
</div>

<!-- FAQ 02 -->
<div class="faq-f-wrap">
  <div id="faq-f-q2" class="faq-q">
    <span id="faq-f-id2">2</span>
    <span id="faq-f-txt2">This is a Question</span>

    <div id="faq-f-a2" class="faq-a">
      <span id="faq-f-ans2">This is an answer!</span>
    </div>
  </div>
</div>

<!-- FAQ 03 -->
<div class="faq-f-wrap">
  <div id="faq-f-q" class="faq-q">
    <span id="faq-f-id3">3</span>
    <span id="faq-f-txt3">This is a Question</span>

    <div id="faq-f-a3" class="faq-a">
      <span id="faq-f-ans3">This is an answer!</span>
    </div>
  </div>
</div>


问:
How to know if window.opener comes from my webpage?
I have a login popup that modifies its parent page with window.opener.location.href = XXX. The code goes something like this.

```<code>  if (window.opener) {
      window.opener.location.href = window.location.href;
      self.close();
  }
</code>```

The problem with this, is that if someone has a link to my webpage, like lets say, a link from an email, this code will be executed and the parent is the email client. This will throw a javascript error cause I'm trying to alter a webpage that is not mine.(In Chrome, it says "Unsafe JavaScript attempt to access frame with URL")

I want to know if there is a way I can find out if the window.opener comes from my webpage.

答:
Not bullet-proof, but can you define some function on your main page and then test for its existence as a check that it is your page? Wrapped in a try/catch to avoid other errors when the page isn't yours?

```<code>// on parent, make this function name something unlikely to appear
// on other pages
function checkParentIdentity() { return "some ID string"; }

// on popup
try {
  if (window.opener
      && window.opener.checkParentIdentity
      && window.opener.checkParentIdentify() === "some ID string") {
     window.opener.location.href = window.location.href;
     self.close();
  }
} catch(e) {
  // error message here
}
</code>```

Having said that, I'm not suggesting it as a good idea, just an idea that might fit with your existing code. If it were me I'd move the location.href updating into the function on the parent, and then just have the child window call the function to tell the parent to update itself - something you could do with minimal changes to the code I posted. But then if it were me, I'd probably not use a popup at all when I can do a dynamic dialog overlay thingy on the main page (jQuery's dialog is just one easy way to do that).

And having said that, why would people have a link directly to your login page? Assuming they might, the point where you want to test whether the right parent window exists is when the login first displays, not after the user enters their details and tries to submit.

Body:
I have a login popup that modifies its parent page with window.opener.location.href = XXX. The code goes something like this.

  if (window.opener) {
      window.opener.location.href = window.location.href;
      self.close();
  }

The problem with this, is that if someone has a link to my webpage, like lets say, a link from an email, this code will be executed and the parent is the email client. This will throw a javascript error cause I'm trying to alter a webpage that is not mine.(In Chrome, it says "Unsafe JavaScript attempt to access frame with URL")

I want to know if there is a way I can find out if the window.opener comes from my webpage.

Body:
Not bullet-proof, but can you define some function on your main page and then test for its existence as a check that it is your page? Wrapped in a try/catch to avoid other errors when the page isn't yours?

// on parent, make this function name something unlikely to appear
// on other pages
function checkParentIdentity() { return "some ID string"; }

// on popup
try {
  if (window.opener
      && window.opener.checkParentIdentity
      && window.opener.checkParentIdentify() === "some ID string") {
     window.opener.location.href = window.location.href;
     self.close();
  }
} catch(e) {
  // error message here
}

Having said that, I'm not suggesting it as a good idea, just an idea that might fit with your existing code. If it were me I'd move the location.href updating into the function on the parent, and then just have the child window call the function to tell the parent to update itself - something you could do with minimal changes to the code I posted. But then if it were me, I'd probably not use a popup at all when I can do a dynamic dialog overlay thingy on the main page (jQuery's dialog is just one easy way to do that).

And having said that, why would people have a link directly to your login page? Assuming they might, the point where you want to test whether the right parent window exists is when the login first displays, not after the user enters their details and tries to submit.


问:
How to search Startswith and Endswith in Elasticsearch using Java?
I am using Spring-Data-Elasticsearch and I have the following queries,

```<code>findByStatusIdAndLinkStartingWith(String statusId, String link);
findByStatusIdAndLinkEndingWith(String statusId, String link);
</code>```

And it works fine. But I need to know how to implement this in CriteriaQuery or with NativeSearchQueryBuilder? And also I have seen that StartingWith is possible with Prefix Query but says it will slow. So what is underlying query used in findByStatusIdAndLinkStartingWith by spring-data-elasticsearch? What is the correct and best way to implement the above in single query like CriteriaQuery or with NativeSearchQueryBuilder?

答:
Spring Data Elasticsearch internally builds a CriteriaQuery for a repository method that has StartingWith in in it's name:

https://github.com/spring-projects/spring-data-elasticsearch/blob/main/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java#L113-L116:

case STARTING_WITH:
  return criteria.startsWith(parameters.next().toString());
case ENDING_WITH:
  return criteria.endsWith(parameters.next().toString());
```
<p>This <code>CriteriaQuery</code> is then processed to an Elasticsearch <code>QueryBuilder</code> (https://github.com/spring-projects/spring-data-elasticsearch/blob/main/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java#L205-L210):</p>
<pre class="lang-java prettyprint-override"><code>case STARTS_WITH:
    query = queryStringQuery(searchText + '*').field(fieldName).analyzeWildcard(true);
    break;
case ENDS_WITH:
    query = queryStringQuery('*' + searchText).field(fieldName).analyzeWildcard(true);
    break;
</code>```

which then will be given to the RestHighLevelClient.

So if you use a CriteriaQuery this will end in the same query being sent to Elasticsearch. If you have a different performant query, then you'll need to use a NativeSearchQuery to create that.

Body:
I am using Spring-Data-Elasticsearch and I have the following queries,

findByStatusIdAndLinkStartingWith(String statusId, String link);
findByStatusIdAndLinkEndingWith(String statusId, String link);

And it works fine. But I need to know how to implement this in CriteriaQuery or with NativeSearchQueryBuilder? And also I have seen that StartingWith is possible with Prefix Query but says it will slow. So what is underlying query used in findByStatusIdAndLinkStartingWith by spring-data-elasticsearch? What is the correct and best way to implement the above in single query like CriteriaQuery or with NativeSearchQueryBuilder?

Body:
Spring Data Elasticsearch internally builds a CriteriaQuery for a repository method that has StartingWith in in it's name:

https://github.com/spring-projects/spring-data-elasticsearch/blob/main/src/main/java/org/springframework/data/elasticsearch/repository/query/parser/ElasticsearchQueryCreator.java#L113-L116:

case STARTING_WITH:
  return criteria.startsWith(parameters.next().toString());
case ENDING_WITH:
  return criteria.endsWith(parameters.next().toString());

This CriteriaQuery is then processed to an Elasticsearch QueryBuilder (https://github.com/spring-projects/spring-data-elasticsearch/blob/main/src/main/java/org/springframework/data/elasticsearch/core/CriteriaQueryProcessor.java#L205-L210):

case STARTS_WITH:
    query = queryStringQuery(searchText + '*').field(fieldName).analyzeWildcard(true);
    break;
case ENDS_WITH:
    query = queryStringQuery('*' + searchText).field(fieldName).analyzeWildcard(true);
    break;

which then will be given to the RestHighLevelClient.

So if you use a CriteriaQuery this will end in the same query being sent to Elasticsearch. If you have a different performant query, then you'll need to use a NativeSearchQuery to create that.


问:
semantics on "std::hash<Key>()(k1)"
As stated on std::hash, instances of this function of std::hash satisfy some properties. One of them, property 4 exactly is as follows:
For two parameters k1 and k2 that are equal, std::hash<Key>()(k1) == std::hash<Key>()(k2)

Where can I find semantics to explain std::hash<Key>()(k1)?

答:
In the expression std::hash()(k1), the std::hash() part is constructing an object that has an operator() defined for the type of k1, then it is immediately calling the operator() on k1. One confusing thing is that std::hash is a template and in the expression written like that, without an explicit type, the template parameter is being deduced as the type of k1.

Basically to read that code you need to be aware that operator() exists and can be overloaded with arbitrary argument types as a member function of a class.

()or {} after std::hash is needed here in order to instantiate a temporary object, as  C++ named requirements: DefaultConstructible.

Title: semantics on "std::hash<Key>()(k1)"


问:
ThreeJS - Getting the "existing" color in a FragmentShader
A bit new to ThreeJS. I have a bunch of instanced meshes and doing setColorAt's for each of them. I have their materials set to a ShaderMaterial with a vertexShader and fragmentShader.

I want to experiment with writing vertex shaders but keep the existing colors that I have for the meshes.
My fragment shader:

```<code>        void main() {

            gl_FragColor = /* How do I get the "existing" or whatever the color used to be?

        }
</code>```

From my understanding, the "existing" color isn't available during this part of the rendering pipeline, so there isn't really a way to do something like gl_FragColor=gl_FragColor or anything of the sort.

From what I was reading from other posts, the only way to retrieve the existing colors that they were set with is to render them once with a regular MeshStandardMaterial, write that render to a texture, and then create a composer pass and pass in the texture to that passes fragmentShader.

Are there any good & simple examples of this technique being used? I have a specific algorithm that is setting the colors of each of the meshes, so I want to be able to keep those while modifying the vertices. Also, if there is a way to simply ignore the fragmentShader and only use a vertexShader I would be OK with that too as long as I could still customize the color for each mesh.

答:
Finally figured it out.

instanceColor is available to the vertexShader. So just make a varying vec3 to store it and pass to the fragmentShader.

Body:
A bit new to ThreeJS. I have a bunch of instanced meshes and doing setColorAt's for each of them. I have their materials set to a ShaderMaterial with a vertexShader and fragmentShader.

I want to experiment with writing vertex shaders but keep the existing colors that I have for the meshes.
My fragment shader:

        void main() {

            gl_FragColor = /* How do I get the "existing" or whatever the color used to be?

        }

From my understanding, the "existing" color isn't available during this part of the rendering pipeline, so there isn't really a way to do something like gl_FragColor=gl_FragColor or anything of the sort.

From what I was reading from other posts, the only way to retrieve the existing colors that they were set with is to render them once with a regular MeshStandardMaterial, write that render to a texture, and then create a composer pass and pass in the texture to that passes fragmentShader.

Are there any good & simple examples of this technique being used? I have a specific algorithm that is setting the colors of each of the meshes, so I want to be able to keep those while modifying the vertices. Also, if there is a way to simply ignore the fragmentShader and only use a vertexShader I would be OK with that too as long as I could still customize the color for each mesh.


问:
How can I fix npm error running npm run build?
When I run npm run build, I had this error and I couldn't fix it reading all articles on github and same quest-s on stack:</p>
```<code>npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\Користувач\Desktop\test/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Користувач\Desktop\test\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Користувач\AppData\Local\npm-cache\_logs\2022-02-06T18_36_44_973Z-debug-0.log
</code>```

答: Hi you are trying to run the build command in non node project please check whether you are in correct directory or not, if not please initialize the project by running npm init

Body:
When I run npm run build, I had this error and I couldn't fix it reading all articles on github and same quest-s on stack:

npm ERR! code ENOENT
npm ERR! syscall open
npm ERR! path C:\Users\Користувач\Desktop\test/package.json
npm ERR! errno -4058
npm ERR! enoent ENOENT: no such file or directory, open 'C:\Users\Користувач\Desktop\test\package.json'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Користувач\AppData\Local\npm-cache\_logs\2022-02-06T18_36_44_973Z-debug-0.log


问:
Identify rebooking within 4 weeks of rebooking
For every booking on the table which is canceled. I need to check if the customer_id of the canceled booking appears with another booking within 12 weeks of the booking date.

If there exists another booking with the exact customer_id within 4 weeks after the booking date, then 1, else 0

Table 1

customer_email hash
booking_date
appointment_status

b642b4217b34b1e8d3bd915fc65c4452
01-01-2022
canceled

a642b4217b34b1e8d3bd915fc65c4453
02-01-2022
completed

a842b4217b34b1e8d3bd915fc65c4454
02-01-2022
completed

z642b4217b34b1e8d3bd915fc65c4457
10-01-2022
canceled

b642b4217b34b1e8d3bd915fc65c4452
15-01-2022
completed

z642b4217b34b1e8d3bd915fc65c4457
15-02-2022
canceled

z642b4217b34b1e8d3bd915fc65c4457
17-02-2022
completed

Result

customer_hash
is_rebooked
booking_date

b642b4217b34b1e8d3bd915fc65c4452
1
01-01-2021

a642b4217b34b1e8d3bd915fc65c4453
N/a
02-01-2022

a842b4217b34b1e8d3bd915fc65c4454
N/a
02-01-2022

z642b4217b34b1e8d3bd915fc65c4457
0
10-01-2022

b642b4217b34b1e8d3bd915fc65c4452
N/a
15-01-2022

z642b4217b34b1e8d3bd915fc65c4457
1
15-02-2022

z642b4217b34b1e8d3bd915fc65c4457
N/a
17-02-2022

Since customers 1 and 4 have made a rebooking I will need to check the booking date of the next appointment is within 4 weeks if yes then 1 else 0.

Customer 2 and 3 have completed their booking therefore N/a

I would like to solve this in Mysql

Thank you

答:
I suspect what you're looking for is a not exists correlation, such as:

```<code>select customer_email_hash,
  case when appointment_status='completed' then 'N/A' else
    case when exists (
      select * from t t2
        where t2.customer_email_hash=t.customer_email_hash
          and t2.booking_date > t.booking_date
          and t2.booking_date < Date_add(t.booking_date, interval 4 week)
    ) then '1' else '0' end
  end Is_Rebooked,
  booking_date
from t;
</code>```

Example Fiddle

Body:
I suspect what you're looking for is a not exists correlation, such as:

select customer_email_hash,
  case when appointment_status='completed' then 'N/A' else
    case when exists (
      select * from t t2
        where t2.customer_email_hash=t.customer_email_hash
          and t2.booking_date > t.booking_date
          and t2.booking_date < Date_add(t.booking_date, interval 4 week)
    ) then '1' else '0' end
  end Is_Rebooked,
  booking_date
from t;

Example Fiddle


问:
Any ways to have single select query instead of multiple select queries in Hibernate?
I am using Spring + Hibernate(HQL).

I have a requirement where I need to fire select query multiple times as parameters are different each time.

For Example

SELECT * FROM  MY_TABLE  WHERE name=? and age=?

inputs will be

```<code>"John", 30
"Nick", 29
"Joe", 32
</code>```

etc.. there could be any number of them.

This is leading to n number of queries where n is the number of inputs

Ex:

```<code>SELECT * FROM  MY_TABLE  WHERE name=John and age=30
SELECT * FROM  MY_TABLE  WHERE name=Nick and age=29
SELECT * FROM  MY_TABLE  WHERE name=Joe and age=32
</code>```

is there a way in hibernate where I can have only one query for this instead of multiple select queries

Ex:

SELECT * FROM  MY_TABLE  WHERE (name=John and age=30) or (name=Nick and age=29) or (name=Joe and age=32)

Or any other optimized way?

答:
If you use a Criteria query, you could use a Disjunction:

```<code>Disjunction d = Restrictions.disjunction();
for(param p : params) {
   Conjunction c = Restrictions.conjunction();
   c.add(Restrictions.eq("name", p.getName()));
   c.add(Restrictions.eq("age", p.getAge()));
   d.add(c);
}
criteria.add(d);
</code>```

Body:
I am using Spring + Hibernate(HQL).

I have a requirement where I need to fire select query multiple times as parameters are different each time.

For Example

SELECT * FROM  MY_TABLE  WHERE name=? and age=?

inputs will be

"John", 30
"Nick", 29
"Joe", 32

etc.. there could be any number of them.

This is leading to n number of queries where n is the number of inputs

Ex:

SELECT * FROM  MY_TABLE  WHERE name=John and age=30
SELECT * FROM  MY_TABLE  WHERE name=Nick and age=29
SELECT * FROM  MY_TABLE  WHERE name=Joe and age=32

is there a way in hibernate where I can have only one query for this instead of multiple select queries

Ex:

SELECT * FROM  MY_TABLE  WHERE (name=John and age=30) or (name=Nick and age=29) or (name=Joe and age=32)

Or any other optimized way?

Body:
If you use a Criteria query, you could use a Disjunction:

Disjunction d = Restrictions.disjunction();
for(param p : params) {
   Conjunction c = Restrictions.conjunction();
   c.add(Restrictions.eq("name", p.getName()));
   c.add(Restrictions.eq("age", p.getAge()));
   d.add(c);
}
criteria.add(d);


问:
How to implement server-side multiplayer for a simple JS game?
Thank you, this is my first post so please correct me on any etiquette. I am a beginner programmer and I want to make a game in JavaScript for one of my classes. Specifically, my Latin class for an "anything" project. My goal is to make somewhat of a Roman-themed version of Among Us. I already have basic movement, and an Apache server running my game. The only thing that I need help with here is making it multiplayer.

The way I want to do this is to have an array on the server where each row is a player, and their username, password, coordinates, and various states (connected, dead, role, etc.) is stored in each column. Only the username, coordinates, and some of the states need to be made available to each client. This is to be copied into an array for each client, who will then take this information and display it.
A client takes control of their character by entering their index and password, at which point a 1D array on the client-side will be created that stores their coordinates, which can be changed by the player using their controls, and sent to the server to be stored in the main array.

I've honestly tried to research this, and I have learned a little bit about databases like MySQL, and server-side languages like PHP and node.js. The problem with these is that, as far as I know, they run once at loading and cannot be manipulated further.
I don't care about anything like separate lobbies at this point, my class is of only 30.
Does anyone know of any good libraries or tutorials for this? Or is there a better direction to go entirely? I hope to make this mobile-compatible.

If needed, I can provide the URL to my website and the code so far.

答:
You want to figure out if you're going to do it in 3D or 2D, pick your language, and implement what you said in said language.

The main thing I think you're missing is the data transport, which can be provided to you with a TCP websocket library like socket.io or socks, which will facilitate an instant, constant data flow between server and client.

The other thing you're missing is a graphics library, which you can do more research on after you figure out whether or not you're doing 2D or 3D.


问:
Export default unused in WebStorm
I am using loadable in React to load my component dynamically. So I'm exporting the index of each component and import them in app.js.
But the issue is I am still getting an error in WebStorm that the export default is unused in individual component index file.

Here is my code. This is in my App.js file.

```<code>const HomeIndex = Loadable({
loader: () => import('./components/home/Index'),
loading: () => <div> </div>,
 });
</code>```

My component index file.

```<code>export default class HomeIndex extends React.Component {

fetchCounts = () =>{
    this.counts.fetchCounts();
};

render(){
    return(
        <div className="pageView">
            <Counts ref={refs => { this.counts = refs; }}/>
            <hr/>
            <Customers fetchCounts={this.fetchCounts}/>
        </div>
    )
  }
}
</code>```

Screenshot of error in WebStorm:

答: You can disable this inspection in webstorm by going to Preferences > Editor > Inspections > Unused symbols and unchecking Unused global symbol

Title: Export default unused in WebStorm

Body:
I am using loadable in React to load my component dynamically. So I'm exporting the index of each component and import them in app.js.
But the issue is I am still getting an error in WebStorm that the export default is unused in individual component index file.

Here is my code. This is in my App.js file.

const HomeIndex = Loadable({
loader: () => import('./components/home/Index'),
loading: () =>

,
 });

My component index file.

export default class HomeIndex extends React.Component {

fetchCounts = () =>{
    this.counts.fetchCounts();
};

render(){
    return(

            <Counts ref={refs => { this.counts = refs; }}/>

            <Customers fetchCounts={this.fetchCounts}/>

    )
  }
}

Screenshot of error in WebStorm:


问:
How to fix signal SIGSEGV, Segmentation fault
I'm getting an error message in Codeblocks C++ 'Program received signal SIGSEGV, Segmentation fault' in comparison between a vector element and a size of vector of vectors inside for loop (line 133 if (parz_przestrzenie[i] != parz_dystanse[i].size())).

Could anyone tell me why?

```<code>#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int bloki_parz[100000], bloki_nieparz[100000];

int silnia(int n)
{
    int liczba = 1;
    for (int i = 1; i <= n; i++)
    {
        liczba *= i;
    }
    return liczba;
}

int main()
{
    int n, czapka, wolne_miejsca = 0, wynik = 1;
    vector<int> parz, nieparz, parz_przestrzenie, nieparz_przestrzenie, parz_przestrzenie2, nieparz_przestrzenie2;
    vector<vector<int>> parz_dystanse;
    vector<vector<int>> nieparz_dystanse;

    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> czapka;
        if (i % 2 == 0)
        {
            parz.push_back(czapka);
        }
        else
        {
            nieparz.push_back(czapka);
        }
    }
    int parz_size = parz.size(), nieparz_size = nieparz.size();
    // sprawdzamy czy dane nie sÂą sprzeczne ; gdy zabraknie nam miejsc do rozmieszczania
    vector<int> parz_duplicate = parz;
    vector<int> nieparz_duplicate = nieparz;
    parz_duplicate.erase(unique(parz_duplicate.begin(), parz_duplicate.end()), parz_duplicate.end());
    nieparz_duplicate.erase(unique(nieparz_duplicate.begin(), nieparz_duplicate.end()), nieparz_duplicate.end());
    int parz_dupl_size = parz_duplicate.size(), nieparz_dupl_size = nieparz_duplicate.size();

    if (parz_size < nieparz_dupl_size)
    {
        cout << 0 << endl;
        return 0;
    }
    if (nieparz_size < parz_dupl_size)
    {
        cout << 0 << endl;
        return 0;
    }

    for (int i = 0; i < parz_size - 1; i++)
    {
        if (parz[i] == parz[i + 1])
        {
            bloki_parz[i + 1] = 1;
        }
    }
    for (int i = 0; i < nieparz_size - 1; i++)
    {
        if (nieparz[i] == nieparz[i + 1])
        {
            bloki_nieparz[i] = 1;
        }
    }

    for (int i = 0; i < parz_size; i++)
    {
        vector<int> bloczek;
        for (int j = i; j < parz_size; j++)
        {
            if (parz[j] != parz[j + 1])
            {
                bloczek.push_back(parz[j]);
            }
            else
            {
                i += 1;
                break;
            }
        }
        if (bloczek.size() != 0)
        {
            parz_dystanse.push_back(bloczek);
        }
    }
    int parz_dyst_size = parz_dystanse.size();
    if (parz[parz_size - 1] != parz[parz_size - 2])
    {
        parz_dystanse[parz_dyst_size - 1].push_back(parz[parz_size - 1]);
    }

    for (int i = 0; i < nieparz_size; i++)
    {
        vector<int> bloczek;
        for (int j = i; j < nieparz_size; j++)
        {
            if (nieparz[j] != nieparz[j + 1])
            {
                bloczek.push_back(nieparz[j]);
            }
            else
            {
                i += 1;
                break;
            }
        }

        if (bloczek.size() != 0)
        {
            nieparz_dystanse.push_back(bloczek);
        }
    }

    int nieparz_dyst_size = nieparz_dystanse.size();

    int current_wynik = 0;
    for (int i = 0; i < nieparz_size; i++)
    {
        if (bloki_parz[i] == 0)
        {
            current_wynik++;
        }
        else
        {
            if (current_wynik != 0)
            {
                parz_przestrzenie.push_back(current_wynik);
            }
            current_wynik = 0;
        }
    }
    parz_przestrzenie.push_back(current_wynik);

    current_wynik = 0;
    for (int i = 0; i < parz_size; i++)
    {
        if (bloki_nieparz[i] == 0)
        {
            current_wynik++;
        }
        else
        {
            if (current_wynik != 0)
            {
                nieparz_przestrzenie.push_back(current_wynik);
            }
            current_wynik = 0;
        }
    }
    nieparz_przestrzenie.push_back(current_wynik);

    int parz_przest_size = parz_przestrzenie.size(), nieparz_przest_size = nieparz_przestrzenie.size();

    for (int i = 0; i < 1; i++)
    {
        if (parz_przestrzenie[i] != parz_dystanse[i].size())
        {
            wynik *= parz_przestrzenie[i];
            wolne_miejsca++;
        }
    }
    for (int i = 0; i < nieparz_przest_size; i++)
    {
        if (nieparz_przestrzenie[i] != nieparz_dystanse[i].size())
        {
            wynik *= nieparz_przestrzenie[i];
            wolne_miejsca++;
        }
    }

    cout << wynik * silnia(wolne_miejsca) << endl;
}
</code>```

答:
parz_dystanse is a vector of a vector. In this case the return value of parz_dystanse.size() is a long unsigned int, whereas an element of parz_przestrzenie is an int.

You need to make explicit that parz_dystanse.size() returns an int in order to make comparitions between integer expressions of different signedness.

This will fix that problem:

```<code>if (parz_przestrzenie[i] != (int)parz_dystanse[i].size())
</code>```

Body:
I'm getting an error message in Codeblocks C++ 'Program received signal SIGSEGV, Segmentation fault' in comparison between a vector element and a size of vector of vectors inside for loop (line 133 if (parz_przestrzenie[i] != parz_dystanse[i].size())).

Could anyone tell me why?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int bloki_parz[100000], bloki_nieparz[100000];

int silnia(int n)
{
    int liczba = 1;
    for (int i = 1; i <= n; i++)
    {
        liczba *= i;
    }
    return liczba;
}

int main()
{
    int n, czapka, wolne_miejsca = 0, wynik = 1;
    vector<int> parz, nieparz, parz_przestrzenie, nieparz_przestrzenie, parz_przestrzenie2, nieparz_przestrzenie2;
    vector<vector<int>> parz_dystanse;
    vector<vector<int>> nieparz_dystanse;

    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> czapka;
        if (i % 2 == 0)
        {
            parz.push_back(czapka);
        }
        else
        {
            nieparz.push_back(czapka);
        }
    }
    int parz_size = parz.size(), nieparz_size = nieparz.size();
    // sprawdzamy czy dane nie sÂą sprzeczne ; gdy zabraknie nam miejsc do rozmieszczania
    vector<int> parz_duplicate = parz;
    vector<int> nieparz_duplicate = nieparz;
    parz_duplicate.erase(unique(parz_duplicate.begin(), parz_duplicate.end()), parz_duplicate.end());
    nieparz_duplicate.erase(unique(nieparz_duplicate.begin(), nieparz_duplicate.end()), nieparz_duplicate.end());
    int parz_dupl_size = parz_duplicate.size(), nieparz_dupl_size = nieparz_duplicate.size();

    if (parz_size < nieparz_dupl_size)
    {
        cout << 0 << endl;
        return 0;
    }
    if (nieparz_size < parz_dupl_size)
    {
        cout << 0 << endl;
        return 0;
    }

    for (int i = 0; i < parz_size - 1; i++)
    {
        if (parz[i] == parz[i + 1])
        {
            bloki_parz[i + 1] = 1;
        }
    }
    for (int i = 0; i < nieparz_size - 1; i++)
    {
        if (nieparz[i] == nieparz[i + 1])
        {
            bloki_nieparz[i] = 1;
        }
    }

    for (int i = 0; i < parz_size; i++)
    {
        vector<int> bloczek;
        for (int j = i; j < parz_size; j++)
        {
            if (parz[j] != parz[j + 1])
            {
                bloczek.push_back(parz[j]);
            }
            else
            {
                i += 1;
                break;
            }
        }
        if (bloczek.size() != 0)
        {
            parz_dystanse.push_back(bloczek);
        }
    }
    int parz_dyst_size = parz_dystanse.size();
    if (parz[parz_size - 1] != parz[parz_size - 2])
    {
        parz_dystanse[parz_dyst_size - 1].push_back(parz[parz_size - 1]);
    }

    for (int i = 0; i < nieparz_size; i++)
    {
        vector<int> bloczek;
        for (int j = i; j < nieparz_size; j++)
        {
            if (nieparz[j] != nieparz[j + 1])
            {
                bloczek.push_back(nieparz[j]);
            }
            else
            {
                i += 1;
                break;
            }
        }

        if (bloczek.size() != 0)
        {
            nieparz_dystanse.push_back(bloczek);
        }
    }

    int nieparz_dyst_size = nieparz_dystanse.size();

    int current_wynik = 0;
    for (int i = 0; i < nieparz_size; i++)
    {
        if (bloki_parz[i] == 0)
        {
            current_wynik++;
        }
        else
        {
            if (current_wynik != 0)
            {
                parz_przestrzenie.push_back(current_wynik);
            }
            current_wynik = 0;
        }
    }
    parz_przestrzenie.push_back(current_wynik);

    current_wynik = 0;
    for (int i = 0; i < parz_size; i++)
    {
        if (bloki_nieparz[i] == 0)
        {
            current_wynik++;
        }
        else
        {
            if (current_wynik != 0)
            {
                nieparz_przestrzenie.push_back(current_wynik);
            }
            current_wynik = 0;
        }
    }
    nieparz_przestrzenie.push_back(current_wynik);

    int parz_przest_size = parz_przestrzenie.size(), nieparz_przest_size = nieparz_przestrzenie.size();

    for (int i = 0; i < 1; i++)
    {
        if (parz_przestrzenie[i] != parz_dystanse[i].size())
        {
            wynik *= parz_przestrzenie[i];
            wolne_miejsca++;
        }
    }
    for (int i = 0; i < nieparz_przest_size; i++)
    {
        if (nieparz_przestrzenie[i] != nieparz_dystanse[i].size())
        {
            wynik *= nieparz_przestrzenie[i];
            wolne_miejsca++;
        }
    }

    cout << wynik * silnia(wolne_miejsca) << endl;
}

Body:
parz_dystanse is a vector of a vector. In this case the return value of parz_dystanse.size() is a long unsigned int, whereas an element of parz_przestrzenie is an int.

You need to make explicit that parz_dystanse.size() returns an int in order to make comparitions between integer expressions of different signedness.

This will fix that problem:

if (parz_przestrzenie[i] != (int)parz_dystanse[i].size())


问:
WinSCP .NET Assembly impersonation issue: The stub received bad data
I have an .NET console app using WinSCP assembly version 5.19.5. The app is under impersonation in order to access files on NAS so that I set ExecutableProcessUserName and ExecutableProcessPassword for the Session object.

```<code>Dim sessionOptions As New SessionOptions
With sessionOptions
    .Protocol = Protocol.Sftp
    .HostName = _SFTPServer
    .UserName = _SFTPLoginID
    .Password = _SFTPLoginPwd
    .PortNumber = _SFTPPort
End With

sessionOptions.SshHostKeyFingerprint =
    session.ScanFingerprint(sessionOptions, "SHA-256")

Using session As New Session
    session.ExecutableProcessUserName = _ServiceAccountUsername
    session.ExecutableProcessPassword =
        ConvertToSecureString(_ServiceAccountPassword)
    session.Open(sessionOptions)
</code>```

It fails at session.Open with error:

The stub received bad data
Any ideas? Thanks

答:
It seems that you need to specify the domain:

Stub received bad data?

```<code>session.ExecutableProcessUserName = "user@domain";
</code>```

Side note: Setting SessionOptions.SshHostKeyFingerprint to the value returned by session.ScanFingerprint is just an ineffective equivalent of SshHostKeyPolicy.GiveUpSecurityAndAcceptAny.

Body:
I have an .NET console app using WinSCP assembly version 5.19.5. The app is under impersonation in order to access files on NAS so that I set ExecutableProcessUserName and ExecutableProcessPassword for the Session object.

Dim sessionOptions As New SessionOptions
With sessionOptions
    .Protocol = Protocol.Sftp
    .HostName = _SFTPServer
    .UserName = _SFTPLoginID
    .Password = _SFTPLoginPwd
    .PortNumber = _SFTPPort
End With

sessionOptions.SshHostKeyFingerprint =
    session.ScanFingerprint(sessionOptions, "SHA-256")

Using session As New Session
    session.ExecutableProcessUserName = _ServiceAccountUsername
    session.ExecutableProcessPassword =
        ConvertToSecureString(_ServiceAccountPassword)
    session.Open(sessionOptions)

It fails at session.Open with error:

The stub received bad data
Any ideas? Thanks

Body:
It seems that you need to specify the domain:

Stub received bad data?

session.ExecutableProcessUserName = "user@domain";

Side note: Setting SessionOptions.SshHostKeyFingerprint to the value returned by session.ScanFingerprint is just an ineffective equivalent of SshHostKeyPolicy.GiveUpSecurityAndAcceptAny.