问:
React range slider with two handles
I'm trying to make a range slider with two handles. Its main purpose is to filter the array of cars that I fetch from the server. Should I use library for the slider? I managed to almost get it done without any library. Here is the minimal working example:

https://codesandbox.io/s/trusting-poincare-4kzcvy?file=/src/Slider.js

I seem to get it wrong in regard to calculations, since the red part of rail doesn't follow up precisely when dragging a handle, and the min value matches the full max value if dragged to the end.

```<code>//destructive props
const RangeSlider = ({ classes, label, onChange, value, ...sliderProps }) => {
     //set initial value to 0 this will change inside useEffect in first render also| or you can directly set useState(value)
    const [sliderVal, setSliderVal] = useState(0);

    // keep mouse state to determine whether i should call parent onChange or not.
    // so basically after dragging the slider and then release the mouse then we will call the parent onChange, otherwise parent function will get call each and every change
    const [mouseState, setMouseState] = useState(null);

    useEffect(() => {
      setSliderVal(value); // set new value when value gets changed, even when first render
    }, [value]);

    const changeCallback = (e) => {
      setSliderVal(e.target.value); // update local state of the value when changing
    }

    useEffect(() => {
      if (mouseState === "up") {
        onChange(sliderVal)// when mouse is up then call the parent onChange
      }
    }, [mouseState])

    return (
      <div className="range-slider">
        <p>{label}</p>
        <h3>value: { sliderVal }</h3>
        <input
          type="range"
          value={sliderVal}
          {...sliderProps}
          className={`slider ${classes}`}
          id="myRange"
          onChange={changeCallback}
          onMouseDown={() => setMouseState("down")} // When mouse down set the mouseState to 'down'
          onMouseUp={() => setMouseState("up")} // When mouse down set the mouseState to 'up' | now we can call the parent onChnage
        />
      </div>
    );
};

export default memo(RangeSlider);
</code>```

I tried it this way but it doesnt add up to the solution when having two handles.

Title: React range slider with two handles

Body:
I'm trying to make a range slider with two handles. Its main purpose is to filter the array of cars that I fetch from the server. Should I use library for the slider? I managed to almost get it done without any library. Here is the minimal working example:

https://codesandbox.io/s/trusting-poincare-4kzcvy?file=/src/Slider.js

I seem to get it wrong in regard to calculations, since the red part of rail doesn't follow up precisely when dragging a handle, and the min value matches the full max value if dragged to the end.

//destructive props
const RangeSlider = ({ classes, label, onChange, value, ...sliderProps }) => {
     //set initial value to 0 this will change inside useEffect in first render also| or you can directly set useState(value)
    const [sliderVal, setSliderVal] = useState(0);

    // keep mouse state to determine whether i should call parent onChange or not.
    // so basically after dragging the slider and then release the mouse then we will call the parent onChange, otherwise parent function will get call each and every change
    const [mouseState, setMouseState] = useState(null);

    useEffect(() => {
      setSliderVal(value); // set new value when value gets changed, even when first render
    }, [value]);

    const changeCallback = (e) => {
      setSliderVal(e.target.value); // update local state of the value when changing
    }

    useEffect(() => {
      if (mouseState === "up") {
        onChange(sliderVal)// when mouse is up then call the parent onChange
      }
    }, [mouseState])

    return (

{label}

value: { sliderVal }

        <input
          type="range"
          value={sliderVal}
          {...sliderProps}
          className={`slider ${classes}`}
          id="myRange"
          onChange={changeCallback}
          onMouseDown={() => setMouseState("down")} // When mouse down set the mouseState to 'down'
          onMouseUp={() => setMouseState("up")} // When mouse down set the mouseState to 'up' | now we can call the parent onChnage
        />

    );
};

export default memo(RangeSlider);

I tried it this way but it doesnt add up to the solution when having two handles.


来源: stackexchange

问:
Why is this error coming(ValueError: Must pass 2-d input. shape=()). my python version - 3.7 and confusion matrix is also 2D
[enter image description here](https://i.stack.imgur.com/vWyY9.png)

Trying to print confusion matrix

ContentLicense: CC BY-SA 4.0


问:
Interactive circle annotation on image to replicate Matlab's drawcircle function
In the past I haveused Matlab's drawcircle function to interactively draw a circle on an image as a method of measuring the radius of a circular feature which is very hard to extract using circle-detection algorithms.

I am trying to make the switch over to python (making use of matplotlib and cv2 etc.), but am struggling to find any way replicating this functionality.

Is this sort of interactive annotation at all possible in Python/Matplotlib/openCV/other? Or would it be better to leave this idea behind and go down the route of iteratively entering coordinates/radius into the console?


问:
Problem with saving images via rasterio in a GUI Python
I've created a python gui that allows you to open a raster, view it, crop it using the mouse (by selecting the area of interest) and save it.
My problem is that, after selecting the area with the mouse, when saving I get an error like this:

File "rasterio_base.pyx", line 309, in rasterio._base.DatasetBase.init
rasterio.errors.RasterioIOError: C:/Users/Desktop/output_image.tif: No such file or directory

Would anyone know how to fix it?

I attach my code

```<code>import tkinter as tk
import tkinter.filedialog as fd
import rasterio
import matplotlib.pyplot as plt
from rasterio.plot import show
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

# Create the main window
window = tk.Tk()
window.title("Raster Clipper")

# Function to open and display the raster image
def open_image():
    global src, cid, fig, ax, canvas
    file_path = fd.askopenfilename()
    with rasterio.open(file_path) as src:
        # Show the image using matplotlib
        fig, ax = plt.subplots(figsize=(5,5))
        show(src, ax=ax)
        # Add the figure to a canvas widget
        canvas = FigureCanvasTkAgg(fig, window)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # Add a navigation toolbar
        toolbar = NavigationToolbar2Tk(canvas, window)
        toolbar.update()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # Connect mouse events for cropping
        cid = fig.canvas.mpl_connect('button_press_event', on_click)

# Function to handle mouse click event for cropping
def on_click(event):
    global x1, y1, cid2
    x1, y1 = int(event.xdata), int(event.ydata)
    cid2 = fig.canvas.mpl_connect('button_release_event', on_release)

# Function to handle mouse release event for cropping
def on_release(event):
    global x2, y2
    x2, y2 = int(event.xdata), int(event.ydata)
    fig.canvas.mpl_disconnect(cid2)
    # Draw the crop rectangle
    rect = plt.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
    ax.add_patch(rect)
    plt.draw()

# Function to save the cropped raster image
def save_cropped_image():
    global src, x1, y1, x2, y2
    # Read the image file and get the bounding box of the crop rectangle
    file_path = fd.asksaveasfilename(defaultextension=".tif")
    with rasterio.open(file_path) as src:
        left, bottom, right, top = src.bounds
        xmin = max(x1, left)
        ymin = max(y1, bottom)
        xmax = min(x2, right)
        ymax = min(y2, top)
        bbox = (xmin, ymin, xmax, ymax)
        # Crop the image using the bounding box
        cropped_image, cropped_transform = rasterio.mask.mask(src, [bbox], crop=True)
        # Save the cropped image to a file
        out_file = "C:\\Users\\Desktop\\cropped_image.tiff"
        with rasterio.open(out_file, "w", driver="GTiff", width=cropped_image.shape[2], height=cropped_image.shape[1], count=cropped_image.shape[0], dtype=cropped_image.dtype, transform=cropped_transform) as dst:
            dst.write(cropped_image)

# Create buttons for opening and saving the raster image
open_button = tk.Button(window, text="Open Raster", command=open_image)
open_button.pack(side=tk.LEFT)
save_button = tk.Button(window, text="Save Cropped Raster", command=save_cropped_image)
save_button.pack(side=tk.RIGHT)

# Run the main loop
window.mainloop()
</code>```

Body:
I've created a python gui that allows you to open a raster, view it, crop it using the mouse (by selecting the area of interest) and save it.
My problem is that, after selecting the area with the mouse, when saving I get an error like this:

File "rasterio_base.pyx", line 309, in rasterio._base.DatasetBase.init
rasterio.errors.RasterioIOError: C:/Users/Desktop/output_image.tif: No such file or directory

Would anyone know how to fix it?

I attach my code

import tkinter as tk
import tkinter.filedialog as fd
import rasterio
import matplotlib.pyplot as plt
from rasterio.plot import show
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

# Create the main window
window = tk.Tk()
window.title("Raster Clipper")

# Function to open and display the raster image
def open_image():
    global src, cid, fig, ax, canvas
    file_path = fd.askopenfilename()
    with rasterio.open(file_path) as src:
        # Show the image using matplotlib
        fig, ax = plt.subplots(figsize=(5,5))
        show(src, ax=ax)
        # Add the figure to a canvas widget
        canvas = FigureCanvasTkAgg(fig, window)
        canvas.draw()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # Add a navigation toolbar
        toolbar = NavigationToolbar2Tk(canvas, window)
        toolbar.update()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        # Connect mouse events for cropping
        cid = fig.canvas.mpl_connect('button_press_event', on_click)

# Function to handle mouse click event for cropping
def on_click(event):
    global x1, y1, cid2
    x1, y1 = int(event.xdata), int(event.ydata)
    cid2 = fig.canvas.mpl_connect('button_release_event', on_release)

# Function to handle mouse release event for cropping
def on_release(event):
    global x2, y2
    x2, y2 = int(event.xdata), int(event.ydata)
    fig.canvas.mpl_disconnect(cid2)
    # Draw the crop rectangle
    rect = plt.Rectangle((x1, y1), x2-x1, y2-y1, linewidth=1, edgecolor='r', facecolor='none')
    ax.add_patch(rect)
    plt.draw()

# Function to save the cropped raster image
def save_cropped_image():
    global src, x1, y1, x2, y2
    # Read the image file and get the bounding box of the crop rectangle
    file_path = fd.asksaveasfilename(defaultextension=".tif")
    with rasterio.open(file_path) as src:
        left, bottom, right, top = src.bounds
        xmin = max(x1, left)
        ymin = max(y1, bottom)
        xmax = min(x2, right)
        ymax = min(y2, top)
        bbox = (xmin, ymin, xmax, ymax)
        # Crop the image using the bounding box
        cropped_image, cropped_transform = rasterio.mask.mask(src, [bbox], crop=True)
        # Save the cropped image to a file
        out_file = "C:\\Users\\Desktop\\cropped_image.tiff"
        with rasterio.open(out_file, "w", driver="GTiff", width=cropped_image.shape[2], height=cropped_image.shape[1], count=cropped_image.shape[0], dtype=cropped_image.dtype, transform=cropped_transform) as dst:
            dst.write(cropped_image)

# Create buttons for opening and saving the raster image
open_button = tk.Button(window, text="Open Raster", command=open_image)
open_button.pack(side=tk.LEFT)
save_button = tk.Button(window, text="Save Cropped Raster", command=save_cropped_image)
save_button.pack(side=tk.RIGHT)

# Run the main loop
window.mainloop()


问:
django - How do you enter information from a list displayed on the webpage. For example filling a marksheet of learners

Name
Mark

Jane
78

Ann
60

i tried displaying a django form in table from (form.as_table) but didnot produce the results i expected.


问:
new column using paste0() within loop R
I made a loop through my demographics data set to summarise the number of respondents to each question, the number of each type of response and the percentage of each response based based on total responses. The result is each question outputs a df and they are joined at the end of the loop to produce the desired report. I would like to also include a column n_pct by pasting the n (%) for each row. this almost worked except that the data is grouped, I've tried various combinations of apply, but no results. Rather, I get an error about the FUN (using apply) or an attempted list-string as the value:

```<code>Error in `$<-.data.frame`(`*tmp*`, "n_pct", value = c("c(175, 79) (c(44.5, 40.7)%)",  :
  replacement has 6 rows, data has 2
</code>```
```<code>dem_col<-colnames(demographics_df)
dem_col1<-c(3,21,28,29,30,38:43,52,56:58)

sum_dem_df<-demographics_df%>%
  select(site_name,record_id)%>%
  summarise(sum=n(),.groups='keep')%>%
  mutate(question=NA_character_)

#Loop through all columns and get totals by group
for(i in 3:length(dem_col)){
  dem_df_i<-as.data.frame(demographics_df[,c(1,i)])
  name<-paste0(names(demographics_df[i]))
  }if(i%in%dem_col1){
    dem_df_i$j<-dem_df_i[,2]
    dem_df_i<-dem_df_i%>%
      group_by(site_name)%>%
      drop_na()%>%
      count(j) %>%
      rename(!!name:=j)%>%
      pivot_wider(names_from =!!name,values_from=n )%>%
      mutate(question=!!name)%>%
      replace(is.na(.), 0) %>%
      mutate(sum = rowSums(across(where(is.numeric))))
    dem_df_i<-as.data.frame(dem_df_i)
    dem_df_i$pct<-dem_df_i[,c(2:(length(colnames(dem_df_i))-2))]/dem_df_i$sum
    dem_df_i$n_pct<-paste0(dem_df_i[,c(2:(length(colnames(dem_df_i))-2))],' (',100*round(dem_df_i$pct,3),'%)')
    sum_dem_df<-full_join(sum_dem_df,dem_df_i,by=c('site_name','question','sum'))
  }
</code>```

Code for sample data:

```<code>demographics_df<-data.frame(site_name=c('city1','city2','city1','city2','city1','city2'),
record_id=c(1,2,3,4,5,6),
gender.factor=c('male','female','male,'male','trans female',NA_character_),
employment.factor=c('unemployed','unemployed','temporary employed',NA_character_,'unemployed','part-time employed')

desired_df<-data.frame(site_name=c('city1','city2','city1','city2'),
                       sum=c(3,2,3,2),
                       male=c(2,1,NA,NA),
                       female=c(0,1,NA,NA),
                       trans_female=c(1,0,NA,NA),
                       `pct$male`=c(.66,.5,NA,NA),
                       `pct$female`=c(0,.5,NA,NA),
                       `pct$trans_female`=c(.33,0,NA,NA),
                       umemployed=c(NA,NA,2,1),
                       temp_employed=c(NA,NA,1,0),
                       part_time=c(NA,NA,0,1),
                       `pct$unemployed`=c(NA,NA,.66,.5),
                       `pct$temp_employed`=c(NA,NA,.33,0),
                       `pct$part_time`=c(NA,NA,0,.5),
                       n_pct_female=c('0 (0%)','1 (50%)'))
</code>```

note: this is my first time posting a question this complex. Any feedback is valuable. Thank you for your time.

Desired output:
site_name sum male female trans_female pct.male pct.female pct.trans_female umemployed temp_employed part_time
1     city1   3    2      0            1     0.66        0.0             0.33         NA            NA        NA
2     city2   2    1      1            0     0.50        0.5             0.00         NA            NA        NA
3     city1   3   NA     NA           NA       NA         NA               NA          2             1         0
4     city2   2   NA     NA           NA       NA         NA               NA          1             0         1
pct.unemployed pct.temp_employed pct.part_time n_pct_female
1             NA                NA            NA       0 (0%)
2             NA                NA            NA      1 (50%)
3           0.66              0.33           0.0       0 (0%)
4           0.50              0.00           0.5      1 (50%)

Title: new column using paste0() within loop R

Body:
I made a loop through my demographics data set to summarise the number of respondents to each question, the number of each type of response and the percentage of each response based based on total responses. The result is each question outputs a df and they are joined at the end of the loop to produce the desired report. I would like to also include a column n_pct by pasting the n (%) for each row. this almost worked except that the data is grouped, I've tried various combinations of apply, but no results. Rather, I get an error about the FUN (using apply) or an attempted list-string as the value:

Error in `$<-.data.frame`(`*tmp*`, "n_pct", value = c("c(175, 79) (c(44.5, 40.7)%)",  :
  replacement has 6 rows, data has 2

dem_col<-colnames(demographics_df)
dem_col1<-c(3,21,28,29,30,38:43,52,56:58)

sum_dem_df<-demographics_df%>%
  select(site_name,record_id)%>%
  summarise(sum=n(),.groups='keep')%>%
  mutate(question=NA_character_)

#Loop through all columns and get totals by group
for(i in 3:length(dem_col)){
  dem_df_i<-as.data.frame(demographics_df[,c(1,i)])
  name<-paste0(names(demographics_df[i]))
  }if(i%in%dem_col1){
    dem_df_i$j<-dem_df_i[,2]
    dem_df_i<-dem_df_i%>%
      group_by(site_name)%>%
      drop_na()%>%
      count(j) %>%
      rename(!!name:=j)%>%
      pivot_wider(names_from =!!name,values_from=n )%>%
      mutate(question=!!name)%>%
      replace(is.na(.), 0) %>%
      mutate(sum = rowSums(across(where(is.numeric))))
    dem_df_i<-as.data.frame(dem_df_i)
    dem_df_i$pct<-dem_df_i[,c(2:(length(colnames(dem_df_i))-2))]/dem_df_i$sum
    dem_df_i$n_pct<-paste0(dem_df_i[,c(2:(length(colnames(dem_df_i))-2))],' (',100*round(dem_df_i$pct,3),'%)')
    sum_dem_df<-full_join(sum_dem_df,dem_df_i,by=c('site_name','question','sum'))
  }

Code for sample data:

demographics_df<-data.frame(site_name=c('city1','city2','city1','city2','city1','city2'),
record_id=c(1,2,3,4,5,6),
gender.factor=c('male','female','male,'male','trans female',NA_character_),
employment.factor=c('unemployed','unemployed','temporary employed',NA_character_,'unemployed','part-time employed')

desired_df<-data.frame(site_name=c('city1','city2','city1','city2'),
                       sum=c(3,2,3,2),
                       male=c(2,1,NA,NA),
                       female=c(0,1,NA,NA),
                       trans_female=c(1,0,NA,NA),
                       `pct$male`=c(.66,.5,NA,NA),
                       `pct$female`=c(0,.5,NA,NA),
                       `pct$trans_female`=c(.33,0,NA,NA),
                       umemployed=c(NA,NA,2,1),
                       temp_employed=c(NA,NA,1,0),
                       part_time=c(NA,NA,0,1),
                       `pct$unemployed`=c(NA,NA,.66,.5),
                       `pct$temp_employed`=c(NA,NA,.33,0),
                       `pct$part_time`=c(NA,NA,0,.5),
                       n_pct_female=c('0 (0%)','1 (50%)'))

note: this is my first time posting a question this complex. Any feedback is valuable. Thank you for your time.

Desired output:
site_name sum male female trans_female pct.male pct.female pct.trans_female umemployed temp_employed part_time
1     city1   3    2      0            1     0.66        0.0             0.33         NA            NA        NA
2     city2   2    1      1            0     0.50        0.5             0.00         NA            NA        NA
3     city1   3   NA     NA           NA       NA         NA               NA          2             1         0
4     city2   2   NA     NA           NA       NA         NA               NA          1             0         1
pct.unemployed pct.temp_employed pct.part_time n_pct_female
1             NA                NA            NA       0 (0%)
2             NA                NA            NA      1 (50%)
3           0.66              0.33           0.0       0 (0%)
4           0.50              0.00           0.5      1 (50%)


问:
Reindex from MultiIndex removes row values
I have a case where I have a dataset that I am trying to fill in missing dates for each value in the categorical column I am additionally grouping by data. I was following this solution, and at the point where I reindex the cartesian product, I see that all row values for ap and qps columns (Non-indexed) are now NaN. I'm curious where I might have gone wrong with trying to use this solution? Is there something I missed with re-indexing?

Issues in question:

```<code>new_dma_values_df = dma_values_groupby.reindex(new_index)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | NaN | NaN
...
</code>```

Full Code:

```<code>dma_values_groupby.columns
Index(['created_at', 'dma_description', 'ap', 'qps'], dtype='object')

idx = pd.period_range(min(dma_values_groupby['created_at']), max(dma_values_groupby['created_at']))

PeriodIndex(['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04',
             '2022-01-05', '2022-01-06', '2022-01-07', '2022-01-08',
             '2022-01-09', '2022-01-10',
             ...
             '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16',
             '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20',
             '2022-12-21', '2022-12-22'],
            dtype='period[D]', length=356)

dma_values_groupby.set_index(['created_at', 'dma_description'], inplace=True)

dma_values_groupby.head(5)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | 3 | 1
...

(created_at_index, dma_description_index) = dma_values_groupby.index.levels

new_index = pd.MultiIndex.from_product([idx, dma_description_index])

new_index

MultiIndex([('2022-01-01',             'ABILENE - SWEETWATER'),
            ('2022-01-01',      'ALBANY - SCHENECTADY - TROY'),
            ('2022-01-01',                       'ALBANY, GA'),
            ...
           names=[None, 'dma_description'], length=72268)

new_dma_values_df = dma_values_groupby.reindex(new_index)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | NaN | NaN
...

new_dma_values_df = new_dma_values_df.fillna(0).astype(int) # Value I plan to use after the fix
</code>```

Body:
I have a case where I have a dataset that I am trying to fill in missing dates for each value in the categorical column I am additionally grouping by data. I was following this solution, and at the point where I reindex the cartesian product, I see that all row values for ap and qps columns (Non-indexed) are now NaN. I'm curious where I might have gone wrong with trying to use this solution? Is there something I missed with re-indexing?

Issues in question:

new_dma_values_df = dma_values_groupby.reindex(new_index)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | NaN | NaN
...

Full Code:

dma_values_groupby.columns
Index(['created_at', 'dma_description', 'ap', 'qps'], dtype='object')

idx = pd.period_range(min(dma_values_groupby['created_at']), max(dma_values_groupby['created_at']))

PeriodIndex(['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04',
             '2022-01-05', '2022-01-06', '2022-01-07', '2022-01-08',
             '2022-01-09', '2022-01-10',
             ...
             '2022-12-13', '2022-12-14', '2022-12-15', '2022-12-16',
             '2022-12-17', '2022-12-18', '2022-12-19', '2022-12-20',
             '2022-12-21', '2022-12-22'],
            dtype='period[D]', length=356)

dma_values_groupby.set_index(['created_at', 'dma_description'], inplace=True)

dma_values_groupby.head(5)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | 3 | 1
...

(created_at_index, dma_description_index) = dma_values_groupby.index.levels

new_index = pd.MultiIndex.from_product([idx, dma_description_index])

new_index

MultiIndex([('2022-01-01',             'ABILENE - SWEETWATER'),
            ('2022-01-01',      'ALBANY - SCHENECTADY - TROY'),
            ('2022-01-01',                       'ALBANY, GA'),
            ...
           names=[None, 'dma_description'], length=72268)

new_dma_values_df = dma_values_groupby.reindex(new_index)

created_at (Level 1) | dma_description (Level 2) | ap | qps
2021-01-01 | ALBANY - SCHENECTADY - TROY | NaN | NaN
...

new_dma_values_df = new_dma_values_df.fillna(0).astype(int) # Value I plan to use after the fix


问:
image disappears below 640px resolution in wordpress using avada theme
I have a sticky image in website page, the site is made using wordpress and avada theme, the image disappears when width resolution goes below 640px.

I tried using custom classes and media queries like this:

```<code>@media only screen
and (max-device-width : 640px) {
    .metaverso-img a img {
        width: 60px;
    }
}

@media only screen
and (min-device-width : 640px)
and (max-device-width : 768px) {
    .metaverso-img a img{
        width: 80px;
    }
}

@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
    .metaverso-img a img{
        width: 100px;
    }
}
</code>```

The last two rules work fine but the first one doesn't, even if I edit the queries resolution and i set different intervals, for example: 460-768 it still disappears below 640.

What can I do?

Body:
I have a sticky image in website page, the site is made using wordpress and avada theme, the image disappears when width resolution goes below 640px.

I tried using custom classes and media queries like this:

@media only screen
and (max-device-width : 640px) {
    .metaverso-img a img {
        width: 60px;
    }
}

@media only screen
and (min-device-width : 640px)
and (max-device-width : 768px) {
    .metaverso-img a img{
        width: 80px;
    }
}

@media only screen
and (min-device-width : 768px)
and (max-device-width : 1024px) {
    .metaverso-img a img{
        width: 100px;
    }
}

The last two rules work fine but the first one doesn't, even if I edit the queries resolution and i set different intervals, for example: 460-768 it still disappears below 640.

What can I do?


问:
How can data be obtained while query variables are rapidly changing?
I am working on a react app where I am running a query that requires two query variables. Initially, I fixed my query variables, but they are  changing in response to checkbox clicks. The issue is that if checkboxes are clicked quickly, query variables will likewise change quickly, preventing me from receiving the data.
Can somebody offer a solution to this issue?</p>


问:
WinAppDriver how to select item in ComboBox
I have problem with selecting item from ComboBox,
I able to unfold ComboBox but can't select one of the items

Simply

```<code>var comboBEle = winDriver.FindElementByName("Combo1");
comboBEle.Click();                                       // unfold comboBox
winDriver.FindElementByName("Item1").Click();            // don't work

</code>```

I tried also:

```<code>var comboB = sapSession.FindElementByClassName("Combo1");
var selEle= new SelectElement(comboB);
selEle.SelectByIndex(1);
</code>```

Why winDriver don't see this element?

Body:
I have problem with selecting item from ComboBox,
I able to unfold ComboBox but can't select one of the items

Simply

var comboBEle = winDriver.FindElementByName("Combo1");
comboBEle.Click();                                       // unfold comboBox
winDriver.FindElementByName("Item1").Click();            // don't work

I tried also:

var comboB = sapSession.FindElementByClassName("Combo1");
var selEle= new SelectElement(comboB);
selEle.SelectByIndex(1);

Why winDriver don't see this element?


问:
why we use @DrawableRes in android
fun loadIcon(context: Context, url:String, @DrawableRes placeHolder:Int): Bitmap

what is the difference here while we use @DrawableRes

Title: why we use @DrawableRes in android


问:
Is there a way to get Hostnames using scapy in Python
```<code>import scapy.all as scapy
import optparse

def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-r", "--range", dest="range", help="Use --range To Scan your Wifi Clients")
    options = parser.parse_args()[0]
    if not options.range:
        parser.error("Please Specify an Option")
    else:
        return options

def scan(ip):
    Ip_Addr = scapy.ARP(pdst=ip)
    Mac_Addr = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    add_IpMac = Mac_Addr/Ip_Addr
    (answered, unanswered) = scapy.srp(add_IpMac, timeout=1, verbose=False)

    result_list =[]
    for list in answered:
        result_dic ={
            "ip": list[1].psrc,
            "mac": list[1].hwsrc
        }
        result_list.append(result_dic)

    return(result_list)

def print_results(result_list):
    print("\n")
    print("     IP\t\t\t\tMac")
    print("\n-----------------------------------------")
    for result in result_list:
        print(result["ip"]+"\t\t"+ result["mac"])

options = get_arguments()
result_dic = scan(options.range)
print_results(result_dic)

</code>```

I made a simple IP Scanner which I use to scan the Local Network. I want to get the Hostname like netdiscover. Is there a way to get every Hostname in the local network with scapy.all? Here is my Python Script where I want insert the Hostname:

Body:
import scapy.all as scapy
import optparse

def get_arguments():
    parser = optparse.OptionParser()
    parser.add_option("-r", "--range", dest="range", help="Use --range To Scan your Wifi Clients")
    options = parser.parse_args()[0]
    if not options.range:
        parser.error("Please Specify an Option")
    else:
        return options

def scan(ip):
    Ip_Addr = scapy.ARP(pdst=ip)
    Mac_Addr = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    add_IpMac = Mac_Addr/Ip_Addr
    (answered, unanswered) = scapy.srp(add_IpMac, timeout=1, verbose=False)

    result_list =[]
    for list in answered:
        result_dic ={
            "ip": list[1].psrc,
            "mac": list[1].hwsrc
        }
        result_list.append(result_dic)

    return(result_list)

def print_results(result_list):
    print("\n")
    print("     IP\t\t\t\tMac")
    print("\n-----------------------------------------")
    for result in result_list:
        print(result["ip"]+"\t\t"+ result["mac"])

options = get_arguments()
result_dic = scan(options.range)
print_results(result_dic)

I made a simple IP Scanner which I use to scan the Local Network. I want to get the Hostname like netdiscover. Is there a way to get every Hostname in the local network with scapy.all? Here is my Python Script where I want insert the Hostname:


问:
Use FFMPEG to convert MP4/AAC to MP3 without audio time getting shortened
I've been struggling with extracting the audio from a couple of mp4 files I have. I have tried using all of the different answers posted previously on Stack Overflow, but each of them results in an mp3 file that's shorter than the original mp4.

If anyone has any insights as to what I'm doing wrong, that'd be greatly appreciated, or at the very least why it's not this simple to convert from mp4 to mp3.

I have tried copying the codec and using variable bitrate. The input video is 1:24:56, but the output audio is 1:24:46.

Command: ffmpeg -i sample.mp4 -c:v copy -q:a 0 sample.mp3

Output:

$ffmpeg -i sample.mp4 -c:v copy -q:a 0 sample.mp3

ffmpeg version 2023-01-09-git-13d04e30d7-full_build-www.gyan.dev Copyright (c) 2000-2023 the FFmpeg developers
  built with gcc 12.1.0 (Rev2, Built by MSYS2 project)
  configuration: --enable-gpl --enable-version3 --enable-static --disable-w32threads --disable-autodetect --enable-fontconfig --enable-iconv --enable-gnutls --enable-libxml2 --enable-gmp --enable-bzlib --enable-lzma --enable-libsnappy --enable-zlib --enable-librist --enable-libsrt --enable-libssh --enable-libzmq --enable-avisynth --enable-libbluray --enable-libcaca --enable-sdl2 --enable-libaribb24 --enable-libdav1d --enable-libdavs2 --enable-libuavs3d --enable-libzvbi --enable-librav1e --enable-libsvtav1 --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxavs2 --enable-libxvid --enable-libaom --enable-libjxl --enable-libopenjpeg --enable-libvpx --enable-mediafoundation --enable-libass --enable-frei0r --enable-libfreetype --enable-libfribidi --enable-liblensfun --enable-libvidstab --enable-libvmaf --enable-libzimg --enable-amf --enable-cuda-llvm --enable-cuvid --enable-ffnvcodec --enable-nvdec --enable-nvenc --enable-d3d11va --enable-dxva2 --enable-libvpl --enable-libshaderc --enable-vulkan --enable-libplacebo --enable-opencl --enable-libcdio --enable-libgme --enable-libmodplug --enable-libopenmpt --enable-libopencore-amrwb --enable-libmp3lame --enable-libshine --enable-libtheora --enable-libtwolame --enable-libvo-amrwbenc --enable-libilbc --enable-libgsm --enable-libopencore-amrnb --enable-libopus --enable-libspeex --enable-libvorbis --enable-ladspa --enable-libbs2b --enable-libflite --enable-libmysofa --enable-librubberband --enable-libsoxr --enable-chromaprint
  libavutil      57. 43.100 / 57. 43.100
  libavcodec     59. 56.100 / 59. 56.100
  libavformat    59. 34.102 / 59. 34.102
  libavdevice    59.  8.101 / 59.  8.101
  libavfilter     8. 53.100 /  8. 53.100
  libswscale      6.  8.112 /  6.  8.112
  libswresample   4.  9.100 /  4.  9.100
  libpostproc    56.  7.100 / 56.  7.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'sample.mp4':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    encoder         : Lavf57.83.100
  Duration: 01:24:56.57, start: 0.000000, bitrate: 612 kb/s
  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, smpte170m, progressive), 1920x1080 [SAR 1:1 DAR 16:9], 480 kb/s, 29.94 fps, 30 tbr, 90k tbn (default)
    Metadata:
      handler_name    : VideoHandler
      vendor_id       : [0][0][0][0]
  Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 125 kb/s (default)
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
Stream mapping:
  Stream #0:1 -> #0:0 (aac (native) -> mp3 (libmp3lame))
Press [q] to stop, [?] for help
Output #0, mp3, to 'sample.mp3':
  Metadata:
    major_brand     : isom
    minor_version   : 512
    compatible_brands: isomiso2avc1mp41
    TSSE            : Lavf59.34.102
  Stream #0:0(und): Audio: mp3, 44100 Hz, stereo, fltp (default)
    Metadata:
      handler_name    : SoundHandler
      vendor_id       : [0][0][0][0]
      encoder         : Lavc59.56.100 libmp3lame
size=   88336kB time=01:24:56.54 bitrate= 142.0kbits/s speed= 172x
video:0kB audio:88336kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000394%
```


问:
How to dynamically load Sql data into Dropdown using Select2
I am trying to take the data dynamically from the Sql DB to a Dropdown that is in a modal window (Bootstrap) in order to update the data using Select2, I implemented the suggested code dropdownParent: $('#para2') from the official page but when I open the modal window the Dropdown appear empty I am not having the expected results, please help me to correct this problem.

HTML

```<code>  <div class="row">
            <div class="col-md-6 col-sm-6 col-lg-5 form-group">
              <label class="col-form-label col-md-4 col-sm-2 label-align" for="descx">Para <i class="fa fa-users"></i></label>
              <select name="acompanantes" id="para2" class="nuevo" multiple="multiple" data-placeholder="Para" style="width: 95%">
                <option value=""></option>
                {{empleado}}
              </select>

            </div>
        </div>
</code>```

PHP

```<code>function buscaMemoPorID(){

  $soloID = $_POST["idMemo"];

  $query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
  from TB_Memo
  inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
  inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
  left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
  Where TB_Memo.ID_Memo = $soloID";

  $p = array();
  $data = $this->select($query, $p );

  $datos[1]=count($data);
  $datos[0]=array();
  for($i=0; $i<count($data); $i++){
    $datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
  }

  echo json_encode($datos);

}
</code>```

JS

```<code>function cargaMemoEspecifico(idmemo){
  var cant = $("#mostrar").val();
  var form_data = new FormData();
  form_data.append("action","buscaMemoPorID");
  form_data.append("idMemo",idmemo);
  $.ajax({
      url: 'api_con.php',
      dataType: 'json',
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      success: function(data){
          var area = data[0];
          if(data[1]>0  ){

              var detalle='';
              var cantidad=80;
              var total=0;
              var num=1;
              for(i=0; i<area.length; i++){

                let datos = tinymce.get("mensaje2").setContent(area[i].contenido);

                $("#modalconsulta2").modal("show");
                $("#buscab2").val(area[i].De);
                $("#para2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");
                $("#modal-asunto").val(area[i].asunto);
                $("#modal-fecha").val(area[i].fechCre);
                $("#mensaje2").val(area[i].contenido);
                $("#idMemo").val(area[i].num);

   }

          } else {
              detalle +='<tr><td colspan="8">NO HAY DATOS EN ESTE MOMENTO.........</td></tr>';
          }
      }
   }).error(function(r){
      console.log("Error-->",r.responseText);
   });
}
</code>```

Body:
I am trying to take the data dynamically from the Sql DB to a Dropdown that is in a modal window (Bootstrap) in order to update the data using Select2, I implemented the suggested code dropdownParent: $('#para2') from the official page but when I open the modal window the Dropdown appear empty I am not having the expected results, please help me to correct this problem.

HTML

              Para
              <select name="acompanantes" id="para2" class="nuevo" multiple="multiple" data-placeholder="Para" style="width: 95%">
                <option value=""></option>
                {{empleado}}
              </select>

PHP

function buscaMemoPorID(){

  $soloID = $_POST["idMemo"];

  $query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
  from TB_Memo
  inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
  inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
  inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
  left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
  Where TB_Memo.ID_Memo = $soloID";

  $p = array();
  $data = $this->select($query, $p );

  $datos[1]=count($data);
  $datos[0]=array();
  for($i=0; $i<count($data); $i++){
    $datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
  }

  echo json_encode($datos);

}

JS

function cargaMemoEspecifico(idmemo){
  var cant = $("#mostrar").val();
  var form_data = new FormData();
  form_data.append("action","buscaMemoPorID");
  form_data.append("idMemo",idmemo);
  $.ajax({
      url: 'api_con.php',
      dataType: 'json',
      cache: false,
      contentType: false,
      processData: false,
      data: form_data,
      type: 'post',
      success: function(data){
          var area = data[0];
          if(data[1]>0  ){

              var detalle='';
              var cantidad=80;
              var total=0;
              var num=1;
              for(i=0; i<area.length; i++){

                let datos = tinymce.get("mensaje2").setContent(area[i].contenido);

                $("#modalconsulta2").modal("show");
                $("#buscab2").val(area[i].De);
                $("#para2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");
                $("#modal-asunto").val(area[i].asunto);
                $("#modal-fecha").val(area[i].fechCre);
                $("#mensaje2").val(area[i].contenido);
                $("#idMemo").val(area[i].num);

   }

          } else {
              detalle +='
NO HAY DATOS EN ESTE MOMENTO.........
';
          }
      }
   }).error(function(r){
      console.log("Error-->",r.responseText);
   });
}


问:
How can I make snake like X axis in d3
I need to make axis with curves at its edges in d3, and it can be scrolled down and show more data.
Is it possible with d3?

Tried to use d3-radial-axis library, but without success.
They only have example for radial scale and for spiral scale.

Title: How can I make snake like X axis in d3


问:
Azure RunCommand exit with -1
I am deploying a RunCommand to an azure vm (ubuntu) using ARM (bicep).

I can see my script never completes, and this is the output from the log that the waaagent keeps:

sudo cat /var/log/azure/run-command-handler/handler.log

Writing a placeholder status file indicating progress before forking: /devopsDeploymentAgent.0.status
+ nohup /var/lib/waagent/Microsoft.CPlat.Core.RunCommandHandlerLinux-1.3.2/bin/run-command-handler enable
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event=start
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event=pre-check
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="comparing seqnum" path=devopsDeploymentAgent.mrseq
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="seqnum saved" path=devopsDeploymentAgent.mrseq
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="reading configuration from /var/lib/waagent/Microsoft.CPlat.Core.
RunCommandHandlerLinux-1.3.2/config/devopsDeploymentAgent.0.settings"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="read configuration"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validating json schema"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="json schema valid"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="parsing configuration json"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="parsed configuration json"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validating configuration logically"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validated configuration"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="creating output directory" path=/var/lib/waagent/run-command-hand
ler/download/devopsDeploymentAgent/0
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="created output directory"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 scriptUri=
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="executing command" output=/var/lib/waagent/run-command-handler/do
wnload/devopsDeploymentAgent/0
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="prepare command" scriptFile=/var/lib/waagent/run-command-handler/
download/devopsDeploymentAgent/0/script.sh
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 message="Execute with TimeoutInSeconds=600"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 message="Timeout:signal: killed"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="failed to execute command" error="command terminated with exit st
atus=-1" output=/var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="enable script failed"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="failed to handle" error="failed to execute command: command termi
nated with exit status=-1"
```
<p>As you can see it looks like it exits with a -1 "Timeout:signal: killed". However the timeout for this runcommand (as also seen from the logs) is 5 minutes and it starts at <code>2023-01-09T16:12:47Z</code> and terminates with this exit code at <code>2023-01-09T16:12:48</code> which is 1 second.</p>
<p>I have included the <code>script.sh</code> and the <code>stdout</code> and <code>stderr</code> below.</p>
<p>The script itself does this:-</p>
<ul>
<li>parses some arguments</li>
<li>docker login to an azure container registry</li>
<li>docker pull for an image</li>
<li>checks to see if a named docker container is already running and if so stops it, removes it</li>
<li>runs a new docker container based on the pulled image.</li>
</ul>
<p>From the output that the script writes to <code>stdout</code> I can see that the script gets as far as successfully pulling the image, but then doesn't execute the next line after the <code>docker pull</code> - which is a simple <code>echo</code> statement. So it feels to me like something is actively killing the script - i.e <code>waagent</code>.
From <code>stderr</code> I can see that <code>docker login</code> writes a warning to say a credential helper should be configured, however this isn't causing the script to terminate as it proceeds to do the <code>docker pull</code> of the image, and there are no further errors or warnings written.</p>
<p>Here is the <code>script.sh</code></p>
```#!/bin/bash
while getopts u:z:o:i:t:a:l:p: flag

do
    case "${flag}" in
          u) AZP_URL=${OPTARG};;
          z) AZP_TOKEN=${OPTARG};;
          o) AZP_POOL=${OPTARG};;
          i) AZP_AGENT_DOCKER_IMAGE=${OPTARG};;
          t) AZP_AGENT_DOCKER_IMAGE_TAG=${OPTARG};;
          a) AZP_AGENT_DOCKER_ACR_NAME=${OPTARG};;
          l) AZP_AGENT_DOCKER_ACR_USERNAME=${OPTARG};;
          p) AZP_AGENT_DOCKER_ACR_PASSWORD=${OPTARG};;
     esac
done
## start devops agent
## pull image
## The PAT must have Agent Pools (read, manage) scope (for a deployment group agent, the PAT must have Deployment group (read, manage) scope), and while a single PAT can be used for registering multiple agents, the PAT is used only at the time of registering the agent, and not for subsequent communication.
if [ -n "$AZP_URL" ]; then
echo "docker image is $AZP_AGENT_DOCKER_IMAGE"
echo "installing az agent"
AZP_AGENT_NAME=$(hostname)
echo $AZP_AGENT_DOCKER_ACR_PASSWORD| sudo docker login $AZP_AGENT_DOCKER_ACR_NAME.azurecr.io --username $AZP_AGENT_DOCKER_ACR_USERNAME --password-stdin
# az acr login --name $AZP_AGENT_DOCKER_ACR_NAME
imagePath="$AZP_AGENT_DOCKER_ACR_NAME.azurecr.io/$AZP_AGENT_DOCKER_IMAGE:$AZP_AGENT_DOCKER_IMAGE_TAG"
dockerPullOutput=$(sudo docker pull $imagePath)
echo "finished pulling image $imagePath output was: $dockerPullOutput"
containerName="devops-agent"
# name container and stop and remove any previous one to make this idempotent
if [ ! "$(sudo docker ps -a -q -f name=$containerName)" ]; then
    sudo docker stop $containerName
    sudo docker rm $containerName
fi

echo "running devops agent $AZP_URL $AZP_POOL $AZP_TOKEN $AZP_AGENT_NAME $imagePath"
sudo docker run -d --name $containerName --restart=always -e AZP_URL="$AZP_URL" -e AZP_POOL="$AZP_POOL" -e AZP_TOKEN="$AZP_TOKEN" -e AZP_AGENT_NAME="$AZP_AGENT_NAME" -v /var/run/docker.sock:/var/run/docker.sock $imagePath --once
else
echo "skipping install of devops agent as no devops url provided."
fi

```
<p>and here is the complete <code>stdout</code> as you can see it only executes up to the docker pull based on this output:</p>
```sudo cat /var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0/stdout
docker image is devops/deployment-agent
installing az agent
Login Succeeded
0.1.0-alpha.14: Pulling from devops/deployment-agent
eaead16dc43b: Pulling fs layer
9e72ce0a20ef: Pulling fs layer
e3e8dc6cc33c: Pulling fs layer
b1da6338b120: Pulling fs layer
d746e1c7437c: Pulling fs layer
f9a8bd2a02f1: Pulling fs layer
264e044344ec: Pulling fs layer
2f8fea2b75d2: Pulling fs layer
ffbdacaca4cc: Pulling fs layer
3dd9baa15bcf: Pulling fs layer
891f9750edbc: Pulling fs layer
669c2f9dbfd8: Pulling fs layer
264e044344ec: Waiting
2f8fea2b75d2: Waiting
ffbdacaca4cc: Waiting
3dd9baa15bcf: Waiting
891f9750edbc: Waiting
669c2f9dbfd8: Waiting
b1da6338b120: Waiting
d746e1c7437c: Waiting
f9a8bd2a02f1: Waiting
e3e8dc6cc33c: Download complete
eaead16dc43b: Download complete
9e72ce0a20ef: Verifying Checksum
9e72ce0a20ef: Download complete
f9a8bd2a02f1: Verifying Checksum
f9a8bd2a02f1: Download complete
264e044344ec: Verifying Checksum
264e044344ec: Download complete
b1da6338b120: Verifying Checksum
b1da6338b120: Download complete
ffbdacaca4cc: Verifying Checksum
ffbdacaca4cc: Download complete
3dd9baa15bcf: Verifying Checksum
3dd9baa15bcf: Download complete
891f9750edbc: Verifying Checksum
891f9750edbc: Download complete
669c2f9dbfd8: Verifying Checksum
669c2f9dbfd8: Download complete
d746e1c7437c: Verifying Checksum
d746e1c7437c: Download complete
2f8fea2b75d2: Verifying Checksum
2f8fea2b75d2: Download complete
eaead16dc43b: Pull complete
9e72ce0a20ef: Pull complete
e3e8dc6cc33c: Pull complete
b1da6338b120: Pull complete
d746e1c7437c: Pull complete
f9a8bd2a02f1: Pull complete
264e044344ec: Pull complete
2f8fea2b75d2: Pull complete
ffbdacaca4cc: Pull complete
3dd9baa15bcf: Pull complete
891f9750edbc: Pull complete
669c2f9dbfd8: Pull complete
Digest: sha256:b2c4f630720565fab01993473d3838f5f20632b581d649ea16d7383dac11538d
Status: Downloaded newer image for labdocker.azurecr.io/devops/deployment-agent:0.1.0-alpha.14
labdocker.azurecr.io/devops/deployment-agent:0.1.0-alpha.14
```
<p>and <code>stderr</code>:</p>
```sudo cat /var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0/stderr
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

```

This is not the first time I have seen a run command script seemingly exits for no reason - it happened with another where I was calling sudo gluster volume create commands. Also worth mentioning I am executing multiple separate run commands, one after the other as part of the same deployment. I am being very sure to only deploy one Run Command at a time as I wasn't sure the waagent could deal with concurrency.

For this example, here are the deployment activities shown in the portal - each activity (marked in red) corresponds to a bicep template file that depoys one or more run commands accross a cluster of vm's - one per vm. Each activity runs it's commands accross the seperate vm's, and finishes, before the next one starts. I can't see anything from the times of these activities or how its written that would mean multiple run commands are being executed on a single vm at the same time, so this looks ok to me.

Note: If I run the same exact deployment a second time, this time the script finishes. The difference is that the scripts, when run a second time, have already done lots of work the first time round, and in the case of this script it has already pulled the image, so this time round the pull completes very fast and it then hasn't terminated and successfully runs the docker container.

My question is, what is causing the script to terminate?

Title: Azure RunCommand exit with -1

Body:
I am deploying a RunCommand to an azure vm (ubuntu) using ARM (bicep).

I can see my script never completes, and this is the output from the log that the waaagent keeps:

sudo cat /var/log/azure/run-command-handler/handler.log

Writing a placeholder status file indicating progress before forking: /devopsDeploymentAgent.0.status
+ nohup /var/lib/waagent/Microsoft.CPlat.Core.RunCommandHandlerLinux-1.3.2/bin/run-command-handler enable
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event=start
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event=pre-check
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="comparing seqnum" path=devopsDeploymentAgent.mrseq
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="seqnum saved" path=devopsDeploymentAgent.mrseq
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="reading configuration from /var/lib/waagent/Microsoft.CPlat.Core.
RunCommandHandlerLinux-1.3.2/config/devopsDeploymentAgent.0.settings"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="read configuration"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validating json schema"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="json schema valid"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="parsing configuration json"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="parsed configuration json"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validating configuration logically"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="validated configuration"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="creating output directory" path=/var/lib/waagent/run-command-hand
ler/download/devopsDeploymentAgent/0
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="created output directory"
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 scriptUri=
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="executing command" output=/var/lib/waagent/run-command-handler/do
wnload/devopsDeploymentAgent/0
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="prepare command" scriptFile=/var/lib/waagent/run-command-handler/
download/devopsDeploymentAgent/0/script.sh
time=2023-01-09T16:12:47Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 message="Execute with TimeoutInSeconds=600"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 message="Timeout:signal: killed"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="failed to execute command" error="command terminated with exit st
atus=-1" output=/var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="enable script failed"
time=2023-01-09T16:12:48Z version=v1.3.2/git@6efb77e-clean operation=enable extensionName=devopsDeploymentAgent seq=0 event="failed to handle" error="failed to execute command: command termi
nated with exit status=-1"

As you can see it looks like it exits with a -1 "Timeout:signal: killed". However the timeout for this runcommand (as also seen from the logs) is 5 minutes and it starts at 2023-01-09T16:12:47Z and terminates with this exit code at 2023-01-09T16:12:48 which is 1 second.

I have included the script.sh and the stdout and stderr below.

The script itself does this:-

parses some arguments

docker login to an azure container registry

docker pull for an image

checks to see if a named docker container is already running and if so stops it, removes it

runs a new docker container based on the pulled image.

From the output that the script writes to stdout I can see that the script gets as far as successfully pulling the image, but then doesn't execute the next line after the docker pull - which is a simple echo statement. So it feels to me like something is actively killing the script - i.e waagent.
From stderr I can see that docker login writes a warning to say a credential helper should be configured, however this isn't causing the script to terminate as it proceeds to do the docker pull of the image, and there are no further errors or warnings written.

Here is the script.sh

#!/bin/bash
while getopts u:z:o:i:t:a:l:p: flag

do
    case "${flag}" in
          u) AZP_URL=${OPTARG};;
          z) AZP_TOKEN=${OPTARG};;
          o) AZP_POOL=${OPTARG};;
          i) AZP_AGENT_DOCKER_IMAGE=${OPTARG};;
          t) AZP_AGENT_DOCKER_IMAGE_TAG=${OPTARG};;
          a) AZP_AGENT_DOCKER_ACR_NAME=${OPTARG};;
          l) AZP_AGENT_DOCKER_ACR_USERNAME=${OPTARG};;
          p) AZP_AGENT_DOCKER_ACR_PASSWORD=${OPTARG};;
     esac
done
## start devops agent
## pull image
## The PAT must have Agent Pools (read, manage) scope (for a deployment group agent, the PAT must have Deployment group (read, manage) scope), and while a single PAT can be used for registering multiple agents, the PAT is used only at the time of registering the agent, and not for subsequent communication.
if [ -n "$AZP_URL" ]; then
echo "docker image is $AZP_AGENT_DOCKER_IMAGE"
echo "installing az agent"
AZP_AGENT_NAME=$(hostname)
echo $AZP_AGENT_DOCKER_ACR_PASSWORD| sudo docker login $AZP_AGENT_DOCKER_ACR_NAME.azurecr.io --username $AZP_AGENT_DOCKER_ACR_USERNAME --password-stdin
# az acr login --name $AZP_AGENT_DOCKER_ACR_NAME
imagePath="$AZP_AGENT_DOCKER_ACR_NAME.azurecr.io/$AZP_AGENT_DOCKER_IMAGE:$AZP_AGENT_DOCKER_IMAGE_TAG"
dockerPullOutput=$(sudo docker pull $imagePath)
echo "finished pulling image $imagePath output was: $dockerPullOutput"
containerName="devops-agent"
# name container and stop and remove any previous one to make this idempotent
if [ ! "$(sudo docker ps -a -q -f name=$containerName)" ]; then
    sudo docker stop $containerName
    sudo docker rm $containerName
fi

echo "running devops agent $AZP_URL $AZP_POOL $AZP_TOKEN $AZP_AGENT_NAME $imagePath"
sudo docker run -d --name $containerName --restart=always -e AZP_URL="$AZP_URL" -e AZP_POOL="$AZP_POOL" -e AZP_TOKEN="$AZP_TOKEN" -e AZP_AGENT_NAME="$AZP_AGENT_NAME" -v /var/run/docker.sock:/var/run/docker.sock $imagePath --once
else
echo "skipping install of devops agent as no devops url provided."
fi

and here is the complete stdout as you can see it only executes up to the docker pull based on this output:

sudo cat /var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0/stdout
docker image is devops/deployment-agent
installing az agent
Login Succeeded
0.1.0-alpha.14: Pulling from devops/deployment-agent
eaead16dc43b: Pulling fs layer
9e72ce0a20ef: Pulling fs layer
e3e8dc6cc33c: Pulling fs layer
b1da6338b120: Pulling fs layer
d746e1c7437c: Pulling fs layer
f9a8bd2a02f1: Pulling fs layer
264e044344ec: Pulling fs layer
2f8fea2b75d2: Pulling fs layer
ffbdacaca4cc: Pulling fs layer
3dd9baa15bcf: Pulling fs layer
891f9750edbc: Pulling fs layer
669c2f9dbfd8: Pulling fs layer
264e044344ec: Waiting
2f8fea2b75d2: Waiting
ffbdacaca4cc: Waiting
3dd9baa15bcf: Waiting
891f9750edbc: Waiting
669c2f9dbfd8: Waiting
b1da6338b120: Waiting
d746e1c7437c: Waiting
f9a8bd2a02f1: Waiting
e3e8dc6cc33c: Download complete
eaead16dc43b: Download complete
9e72ce0a20ef: Verifying Checksum
9e72ce0a20ef: Download complete
f9a8bd2a02f1: Verifying Checksum
f9a8bd2a02f1: Download complete
264e044344ec: Verifying Checksum
264e044344ec: Download complete
b1da6338b120: Verifying Checksum
b1da6338b120: Download complete
ffbdacaca4cc: Verifying Checksum
ffbdacaca4cc: Download complete
3dd9baa15bcf: Verifying Checksum
3dd9baa15bcf: Download complete
891f9750edbc: Verifying Checksum
891f9750edbc: Download complete
669c2f9dbfd8: Verifying Checksum
669c2f9dbfd8: Download complete
d746e1c7437c: Verifying Checksum
d746e1c7437c: Download complete
2f8fea2b75d2: Verifying Checksum
2f8fea2b75d2: Download complete
eaead16dc43b: Pull complete
9e72ce0a20ef: Pull complete
e3e8dc6cc33c: Pull complete
b1da6338b120: Pull complete
d746e1c7437c: Pull complete
f9a8bd2a02f1: Pull complete
264e044344ec: Pull complete
2f8fea2b75d2: Pull complete
ffbdacaca4cc: Pull complete
3dd9baa15bcf: Pull complete
891f9750edbc: Pull complete
669c2f9dbfd8: Pull complete
Digest: sha256:b2c4f630720565fab01993473d3838f5f20632b581d649ea16d7383dac11538d
Status: Downloaded newer image for labdocker.azurecr.io/devops/deployment-agent:0.1.0-alpha.14
labdocker.azurecr.io/devops/deployment-agent:0.1.0-alpha.14

and stderr:

sudo cat /var/lib/waagent/run-command-handler/download/devopsDeploymentAgent/0/stderr
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

This is not the first time I have seen a run command script seemingly exits for no reason - it happened with another where I was calling sudo gluster volume create commands. Also worth mentioning I am executing multiple separate run commands, one after the other as part of the same deployment. I am being very sure to only deploy one Run Command at a time as I wasn't sure the waagent could deal with concurrency.

For this example, here are the deployment activities shown in the portal - each activity (marked in red) corresponds to a bicep template file that depoys one or more run commands accross a cluster of vm's - one per vm. Each activity runs it's commands accross the seperate vm's, and finishes, before the next one starts. I can't see anything from the times of these activities or how its written that would mean multiple run commands are being executed on a single vm at the same time, so this looks ok to me.

Note: If I run the same exact deployment a second time, this time the script finishes. The difference is that the scripts, when run a second time, have already done lots of work the first time round, and in the case of this script it has already pulled the image, so this time round the pull completes very fast and it then hasn't terminated and successfully runs the docker container.

My question is, what is causing the script to terminate?


问:
Torch: Losses keep being NaNs
I am currently fitting a Neural Network, with the following code:

```<code>model = torch.nn.Sequential(
    torch.nn.Linear(14261, 1000),
    torch.nn.ReLU(),
    torch.nn.Linear(1000, 1)
)

X_train_t = torch.from_numpy(X_train.to_numpy(np.float32))
Y_train_t = torch.from_numpy(Y_train.to_numpy(np.float32))

xst = (X_train_t - X_train_t.mean())/X_train_t.std()

train_set = torch.utils.data.TensorDataset(xst, Y_train_t)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=4, shuffle=True)

optimiser = torch.optim.SGD(model.parameters(), lr=1e-50)
loss = torch.nn.functional.mse_loss
for epoch in range(10):
    current_loss = 0
    for (Xt, yt) in train_loader:
        yb_pred = model(Xt)
        c_loss = loss(yb_pred.squeeze(), yt)
        current_loss += c_loss.item()*yb_pred.shape[0]
        optimiser.zero_grad()
        c_loss.backward()
        optimiser.step()
    print(epoch, current_loss)
</code>```

Yet, the current loss being printed is always a nan. I don't understand how can I get regular values as I have already lowered the learning rate numerous times ?

Title: Torch: Losses keep being NaNs

Body:
I am currently fitting a Neural Network, with the following code:

model = torch.nn.Sequential(
    torch.nn.Linear(14261, 1000),
    torch.nn.ReLU(),
    torch.nn.Linear(1000, 1)
)

X_train_t = torch.from_numpy(X_train.to_numpy(np.float32))
Y_train_t = torch.from_numpy(Y_train.to_numpy(np.float32))

xst = (X_train_t - X_train_t.mean())/X_train_t.std()

train_set = torch.utils.data.TensorDataset(xst, Y_train_t)
train_loader = torch.utils.data.DataLoader(train_set, batch_size=4, shuffle=True)

optimiser = torch.optim.SGD(model.parameters(), lr=1e-50)
loss = torch.nn.functional.mse_loss
for epoch in range(10):
    current_loss = 0
    for (Xt, yt) in train_loader:
        yb_pred = model(Xt)
        c_loss = loss(yb_pred.squeeze(), yt)
        current_loss += c_loss.item()*yb_pred.shape[0]
        optimiser.zero_grad()
        c_loss.backward()
        optimiser.step()
    print(epoch, current_loss)

Yet, the current loss being printed is always a nan. I don't understand how can I get regular values as I have already lowered the learning rate numerous times ?


问:
Database Mail configuration in 2023 onward
I've been using Database Mail successfully for about ten years, but it seems that while mail protocols and security have moved forward, SQL Server Database Mail has not.

At a new company, I've spent a full work day already trying various credentials and parameters.  The most recent release I have tested with is SQL Server 2019.

What I believe I need to know is how to configure SQL Server Database Mail to work with one of the following:

Office 365 or Exchange SMTP

Windows [Server] SMTP relay

In tests with GMAIL/SMTP, AT&T/SMTP and Earthlink/SMTP, all returned errors, and at least some of the error messages are clearly from the destination SMTP service and not the result of firewall or connectivity problems.  For example:

The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 8 (2023-01-06T11:14:56). Exception Message: Cannot send mails to mail server. (Mailbox unavailable. The server response was: 5.5.1 Authentication Required - ELNK003_308 - https://postmaster-earthlink.vadesecure.com/outbound_error_codes/#_308).  )

Unfortunately, error 308 is not actually documented within the linked Earthlink page.

Looking into some available posts, I find that Database Mail is said to use the SmtpClient class, which in turn is pretty much obsolete, with recommendations to use MailKit.  That's fine, but SQL Server Database Mail has apparently NOT been updated to use MailKit.

Returning to what I think are my choices are from above:

If I am to configure SMTP to Office 365 (we already have an account) or Exchange (if we have Exchange also), then what SMTP configuration parameters do I need to use with Database Mail and within Office 365?

=OR=

If I am to use Windows Server SMTP relay, then how do I configure the SMTP relay's OUTPUT mail to satisfy to the "modern" security requirements of Office 365, GMAIL, Earthlink or AT&T?

(I've used the Windows Server SMTP relay in years past, but only to offload the messages from SQL Server, not to satisfy security requirements)


问:
Is it possible to match the url fragment in a chrome extension?
Currently using match patterns in chrome.contextMenus.create#targetUrlPatterns for a chromium extension, however I've run into an issue.
Is it possible to somehow filter URLs by their fragment (the string following the hash)?

My understanding is that match patterns do not apply to the fragment, however for content scripts you can use include_globs and exclude_globs to filter. Is there a similar alternative for the target url patterns in context menus?

Please note that I am reluctant to manually check in the onclick function using regex, whilst I have already tested this, it is desirable to hide a context menu rather than having it do nothing.

Example urls I would like to match:

www.example.com/foo.php#123bar456 //should show contextmenu
www.example.com/foo.php#123baz456 //should hide contextmenu
```
<p>Please note that the numbers in the example are unknown. My initial attempt is below:</p>
<pre class="lang-js prettyprint-override"><code>//background.js
chrome.contextMenus.create({
    ...
    contexts: ["link"]
    targetUrlPatterns: "*://*.example.com/foo.php*bar*"
</code>```

Obviously the above won't work, but is there any alternative to having to manually check the fragment on click?

Body:
Currently using match patterns in chrome.contextMenus.create#targetUrlPatterns for a chromium extension, however I've run into an issue.
Is it possible to somehow filter URLs by their fragment (the string following the hash)?

My understanding is that match patterns do not apply to the fragment, however for content scripts you can use include_globs and exclude_globs to filter. Is there a similar alternative for the target url patterns in context menus?

Please note that I am reluctant to manually check in the onclick function using regex, whilst I have already tested this, it is desirable to hide a context menu rather than having it do nothing.

Example urls I would like to match:

www.example.com/foo.php#123bar456 //should show contextmenu
www.example.com/foo.php#123baz456 //should hide contextmenu

Please note that the numbers in the example are unknown. My initial attempt is below:

//background.js
chrome.contextMenus.create({
    ...
    contexts: ["link"]
    targetUrlPatterns: "*://*.example.com/foo.php*bar*"

Obviously the above won't work, but is there any alternative to having to manually check the fragment on click?


问:
Python enemy animation
Im working on a platformer for my game and im trying to learn how to add animation to enemies i was looking at a tutorial on how to add animation too enemies i copied it into my own but it just come up with an error saying pygame has no attribute image what does this mean and how can i fix it

```<code># adding enemies
class Enemy1(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.animation_images  = [pygame.image.load('Arlong_1.png'), pygame.image.load('Arlong_2.png'),
        pygame.image.load('Arlong_3.png')]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.move_direction = 1
        self.move_counter = 0

    def update(self):
        self.rect.x += self.move_direction
        self.move_counter += 1
        if abs(self.move_counter) > 50:
            self.move_direction *= -1
            self.move_counter *= -1

</code>```

I tried changing the word image to img or images but it still didnt work I dont know why

Title: Python enemy animation

Body:
Im working on a platformer for my game and im trying to learn how to add animation to enemies i was looking at a tutorial on how to add animation too enemies i copied it into my own but it just come up with an error saying pygame has no attribute image what does this mean and how can i fix it

# adding enemies
class Enemy1(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.animation_images  = [pygame.image.load('Arlong_1.png'), pygame.image.load('Arlong_2.png'),
        pygame.image.load('Arlong_3.png')]
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.move_direction = 1
        self.move_counter = 0

    def update(self):
        self.rect.x += self.move_direction
        self.move_counter += 1
        if abs(self.move_counter) > 50:
            self.move_direction *= -1
            self.move_counter *= -1

I tried changing the word image to img or images but it still didnt work I dont know why


问:
C++ , Inheritance for variable which share the same purpose but different datatype
Base class

class SudokuGenerator {
    protected: // protected is accessible by derived class
        DatabaseConnection DB;
    public:
        virtual void generate() = 0; //pure virtual function that need to be implemented in derived class
        virtual void getSuccessTask() = 0;
        virtual void getFailTask() = 0;
};
```
<p>4 derived class</p>
<pre class="lang-cpp prettyprint-override"><code>class SudokuGenerator_SingleThread : SudokuGenerator {
    private:
        atomic<int> successTask;
        atomic<int> failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};
</code>```

class SudokuGenerator_MultiThread_ATOMIC : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask()override;
};
```
<pre class="lang-cpp prettyprint-override"><code>class SudokuGenerator_MultiThread_MUTEX : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};
</code>```

class SudokuGenerator_MultiThread_INT : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};
```

I have a base class which generate sudoku, and from my derived class, there are private variable for counting success and fail task (insertion to database). As I know there are not anything call Virtual Variable in C++, therefore I have following question.

As the successTask and fail Task is different datatype for the 4 derived function, is there a way to include these variable to the base class, if not, is there anyway to improve my code in this area.

I know there is not any abstract class in C++, is there a way that I could implement SudokuGenerator that it is invalid to declare a SudokuGenerator object (baseclass)

Body:
Base class

class SudokuGenerator {
    protected: // protected is accessible by derived class
        DatabaseConnection DB;
    public:
        virtual void generate() = 0; //pure virtual function that need to be implemented in derived class
        virtual void getSuccessTask() = 0;
        virtual void getFailTask() = 0;
};

4 derived class

class SudokuGenerator_SingleThread : SudokuGenerator {
    private:
        atomic<int> successTask;
        atomic<int> failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};

class SudokuGenerator_MultiThread_ATOMIC : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask()override;
};

class SudokuGenerator_MultiThread_MUTEX : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};

class SudokuGenerator_MultiThread_INT : SudokuGenerator {
    private:
        int successTask;
        int failTask;
    public:
        void generate() override;
        void getSuccessTask() override;
        void getFailTask() override;
};

I have a base class which generate sudoku, and from my derived class, there are private variable for counting success and fail task (insertion to database). As I know there are not anything call Virtual Variable in C++, therefore I have following question.

As the successTask and fail Task is different datatype for the 4 derived function, is there a way to include these variable to the base class, if not, is there anyway to improve my code in this area.

I know there is not any abstract class in C++, is there a way that I could implement SudokuGenerator that it is invalid to declare a SudokuGenerator object (baseclass)


问:
Is it possible to automatically generate documentation from a transforms repo and reference it in a Rosetta Authoring repository in Palantir Foundry?
I was wondering if there exists a way to automatically generate documentation based on doc-strings in either/both a Data Transforms or Python Library repository? What I am thinking is ideally a sphinx implementation which builds documentation on for example commits or PR's, and then referencing the documentation somehow from a Rosetta Authoring repository.


问:
Android Java: Is there a way to to make the runtime for SpeechRecognizer.startListening() indefinite?
I am working in Android Studio (Java) to try to create a certain app, and a part of what I need this app to do is as follows: When the user clicks on the screen, the app starts listening for speech. Then, when they click on the screen again, the app stops listening. In other words, I need it to be so that the speech recognition does not just stop after about a second of silence. Here is something that I tried (this is an excerpt of my code):

```<code>speechRecognizer.setRecognitionListener(recognitionListener);
Button startSpeech = findViewById(R.id.startSpeech);
startSpeech.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    TextView textView = findViewById(R.id.spokenWords);
    textView.setText("Listening");
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 10000);
    speechRecognizer.startListening(intent);

  }
});
</code>```

Doing this does actually allow me to lengthen the time that the speech recognition service runs. Using the parameter of 10000 milliseconds, the recognition runs for a minimum of 10 seconds and then stops. However, I've run into a problem with this:

If I make the milliseconds parameter too high, then all of a sudden the recognition does not last any longer than a second of silence. For example, when I changed the parameter to 3600000 milliseconds (an hour) and then ran the app, I turned on the speech recognition and then stayed silent. In response to my silence, the speech recognition stopped after about a second of silence (nowhere near an hour). This is unlike when the parameter was 10000 milliseconds where I could remain silent and the recognition still would not stop until at least 10 seconds have passed. Why is this? Is there perhaps a maximum for the EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS constant? If so, what is that maximum?

Moreover, is there any way to just make the recognition run indefinitely so that I don't have to worry about a maximum? Thank you.

Body:
I am working in Android Studio (Java) to try to create a certain app, and a part of what I need this app to do is as follows: When the user clicks on the screen, the app starts listening for speech. Then, when they click on the screen again, the app stops listening. In other words, I need it to be so that the speech recognition does not just stop after about a second of silence. Here is something that I tried (this is an excerpt of my code):

speechRecognizer.setRecognitionListener(recognitionListener);
Button startSpeech = findViewById(R.id.startSpeech);
startSpeech.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    TextView textView = findViewById(R.id.spokenWords);
    textView.setText("Listening");
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS, 10000);
    speechRecognizer.startListening(intent);

  }
});

Doing this does actually allow me to lengthen the time that the speech recognition service runs. Using the parameter of 10000 milliseconds, the recognition runs for a minimum of 10 seconds and then stops. However, I've run into a problem with this:

If I make the milliseconds parameter too high, then all of a sudden the recognition does not last any longer than a second of silence. For example, when I changed the parameter to 3600000 milliseconds (an hour) and then ran the app, I turned on the speech recognition and then stayed silent. In response to my silence, the speech recognition stopped after about a second of silence (nowhere near an hour). This is unlike when the parameter was 10000 milliseconds where I could remain silent and the recognition still would not stop until at least 10 seconds have passed. Why is this? Is there perhaps a maximum for the EXTRA_SPEECH_INPUT_MINIMUM_LENGTH_MILLIS constant? If so, what is that maximum?

Moreover, is there any way to just make the recognition run indefinitely so that I don't have to worry about a maximum? Thank you.


问:
PyJulia: %julia magic ignores local assigments
I'm getting weird results when using the %julia magic inside of functions. Here is a minimal example (copied from the documentation):

```<code>import julia
%load_ext julia.magic

x = "global"

def f():
    x = "local"
    ret = %julia py"x"
    return ret

f()
</code>```

Contrary to expectation, I get the result 'global'. So it seems like all local assignment operations are ignored. Am I doing something wrong?

Body:
I'm getting weird results when using the %julia magic inside of functions. Here is a minimal example (copied from the documentation):

import julia
%load_ext julia.magic

x = "global"

def f():
    x = "local"
    ret = %julia py"x"
    return ret

f()

Contrary to expectation, I get the result 'global'. So it seems like all local assignment operations are ignored. Am I doing something wrong?


问:
How to properly get an IPAddress IPv6 or IPv4 now as of 2023?
Is anybody else noticing that "http_x_forwarded_for" or "REMOTE_ADDR" returns a Private- "IPV6" value that is no longer useful?  I have had the same code for years, but all of a sudden I started receiving an error: "Exception message: Data too long for column 'ipaddress' at row 1"

After extending the column and having the customer try it again, I was able to determine what was happening.  I think this might be apart of some fundamental change in how IP works.  I'm not entirely sure.

The function below is for logging their IPAddress in my Database after the person logs into the website.

This is my current code that uses a two-fold approach:

```<code>protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}
</code>```

The problem is, I may get a IPv6 address and I look it up.  'Warning: .... is a private address', and sites will not even bother to tell me so much of what state they think they reside in, let alone what country.  In looking at the log on the server, I do have a IPv4 address for the same entry.

How do I correct this to be more accurate?  I know there is no such thing in IP-land as real, but there can be better.  Should I switch to IPv6?  In the past all of my DB records have been in IPv4.

Body:
Is anybody else noticing that "http_x_forwarded_for" or "REMOTE_ADDR" returns a Private- "IPV6" value that is no longer useful?  I have had the same code for years, but all of a sudden I started receiving an error: "Exception message: Data too long for column 'ipaddress' at row 1"

After extending the column and having the customer try it again, I was able to determine what was happening.  I think this might be apart of some fundamental change in how IP works.  I'm not entirely sure.

The function below is for logging their IPAddress in my Database after the person logs into the website.

This is my current code that uses a two-fold approach:

protected string GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            return addresses[0];
        }
    }

    return context.Request.ServerVariables["REMOTE_ADDR"];
}

The problem is, I may get a IPv6 address and I look it up.  'Warning: .... is a private address', and sites will not even bother to tell me so much of what state they think they reside in, let alone what country.  In looking at the log on the server, I do have a IPv4 address for the same entry.

How do I correct this to be more accurate?  I know there is no such thing in IP-land as real, but there can be better.  Should I switch to IPv6?  In the past all of my DB records have been in IPv4.


问:
Is there R/Python function for find the best sample combination for regression model?
I have 100 sample data, from there I want to find a regression model that fulfills all the classical assumptions using only the 50 sample data. How do I make the loop program determine the best sample combination from the initial 100 data samples for a regression model that follows the classical assumptions? (Using R or Python)

I hope to get the best 50 samples for my model


问:
Updating documents with logastash
I have a solution with filebeat(on server) -> logstash(on server) -> elasticsearch(as service)

I have to ingest data from file.log in JSON format.
each row have an "GUID" element which is use for upsert. there is the structure of a row generate by workflow:

{"connectorid":"1600140", **"endtime":"", "starttime":"2022-12-02 09:30:00.000"**, "completed":"false", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"assignationTache", "writetime":"2022-12-02 09:29:52.165", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Connector", **"state":"INITIALIZING"**, "parentobjectid":"81015-1700283", "rootcaseid":"81014"}
```
<p>an another step of the same workflow:</p>
<pre class="lang-json prettyprint-override"><code>{"connectorid":"1600140", **"endtime":"", "starttime":""**, "completed":"false", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"assignationTache", "writetime":"2022-12-02 11:00:00.000", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Connector", **"state":"PROCESS"**, "parentobjectid":"81015-1700283", "rootcaseid":"81014"}
</code>```

the final step of the workflow:

{"connectorid":"1600140", **"endtime":"2022-12-02 11:30:00.000", "starttime":""**, "completed":"true", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"Vérifier informations", "writetime":"2022-12-02 11:30:00.000", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Activity", **"state":"DONE",** "parentobjectid":"81015-1700283", "rootcaseid":"81014"}
```
<p>Actually I have this configuration in logstash.conf:</p>
```input {
  beats{
    port => 5044
    add_field => {
      "[@metadata][target_index]" => "index-bonita-qal-processlog-%{+YYYY-MM-dd}"
    }
  }
}

# filtre qui permet de parser la donnee entrante
filter {
  json {
  source => "message"
  target => "fields"
  }
  mutate {
  add_field => { "[@metadata][target_document_id]" => "%{[fields][guid]}" }
  }
}
# configuration de sortie
output {
    elasticsearch {
      hosts => ["<elasticsearch_endpoint>"]
      user => "<username>"
      password => "<password>"
      proxy => "<proxy_endpoint>"
      index => "%{[@metadata][target_index]}"
      document_id => "%{[@metadata][target_document_id]}"
      doc_as_upsert => true
      action => "update"
    }
}
```

this is my result :
enter image description here

actually it's working, the same GUID element are update with the new step of workflow, but I would like to conserved the initial "starttime" value because this value is not store in the application. And I have no idea how can I store the initial value of starttime to be insert after each upsert of the same GUID element.

Title: Updating documents with logastash

Body:
I have a solution with filebeat(on server) -> logstash(on server) -> elasticsearch(as service)

I have to ingest data from file.log in JSON format.
each row have an "GUID" element which is use for upsert. there is the structure of a row generate by workflow:

{"connectorid":"1600140", **"endtime":"", "starttime":"2022-12-02 09:30:00.000"**, "completed":"false", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"assignationTache", "writetime":"2022-12-02 09:29:52.165", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Connector", **"state":"INITIALIZING"**, "parentobjectid":"81015-1700283", "rootcaseid":"81014"}

an another step of the same workflow:

{"connectorid":"1600140", **"endtime":"", "starttime":""**, "completed":"false", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"assignationTache", "writetime":"2022-12-02 11:00:00.000", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Connector", **"state":"PROCESS"**, "parentobjectid":"81015-1700283", "rootcaseid":"81014"}

the final step of the workflow:

{"connectorid":"1600140", **"endtime":"2022-12-02 11:30:00.000", "starttime":""**, "completed":"true", "type":"scripting-groovy-script", "activityid":"1700283", "elementname":"Vérifier informations", "writetime":"2022-12-02 11:30:00.000", "loglevel":"INFO", "caseid":"81015", **"guid":"81015-1700283-1600140"**, "notificationtype":"Activity", **"state":"DONE",** "parentobjectid":"81015-1700283", "rootcaseid":"81014"}

Actually I have this configuration in logstash.conf:

input {
  beats{
    port => 5044
    add_field => {
      "[@metadata][target_index]" => "index-bonita-qal-processlog-%{+YYYY-MM-dd}"
    }
  }
}

# filtre qui permet de parser la donnee entrante
filter {
  json {
  source => "message"
  target => "fields"
  }
  mutate {
  add_field => { "[@metadata][target_document_id]" => "%{[fields][guid]}" }
  }
}
# configuration de sortie
output {
    elasticsearch {
      hosts => ["<elasticsearch_endpoint>"]
      user => "<username>"
      password => "<password>"
      proxy => "<proxy_endpoint>"
      index => "%{[@metadata][target_index]}"
      document_id => "%{[@metadata][target_document_id]}"
      doc_as_upsert => true
      action => "update"
    }
}

this is my result :
enter image description here

actually it's working, the same GUID element are update with the new step of workflow, but I would like to conserved the initial "starttime" value because this value is not store in the application. And I have no idea how can I store the initial value of starttime to be insert after each upsert of the same GUID element.


问:
Can I automatically fix my old paths to tests in Intellij IDEA(using IDEA tools)?
I change paths to java classes in gradle project, but paths for this classes tests steel the same.

Can I change paths using IDEA tools, not manually?

paths to classes

paths to tests


问:
how to list all files from specific directory using media store?
I am trying to list all the files from specific folder but I can't understand how to do that using media store, the code I have tried ,it list all the files from the internal storage, but I want to list all the files from specific folder not to list all files from internal storage.
please help out of this problem.

here is my code

```<code> Uri collection;
        final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
        final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?"
                +" OR " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
        final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
        final String jpg = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
        final String[] selectionArgs = new String[]{mimeType,jpg};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
        }else{
            collection = MediaStore.Files.getContentUri("external");
        }
        try (Cursor cursor = getContext().getContentResolver().query(collection, null, selection, selectionArgs, sortOrder)) {
            if ((cursor != null) && (cursor.getCount() > 0)) {
                if (cursor.moveToFirst()) {
                    do {
                        @SuppressLint("Range") String columnData = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
                        @SuppressLint("Range") String columnName = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME));
                        @SuppressLint("Range") Long date = Long.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED)));
                        ModalClass mediaFiles = new ModalClass();
                        mediaFiles.setFileName(columnName);
                        mediaFiles.setPath(columnData);
                        mediaFiles.setDate(date);
                        fileList.add(mediaFiles);
                    } while (cursor.moveToNext());
                }
            }
</code>```

Body:
I am trying to list all the files from specific folder but I can't understand how to do that using media store, the code I have tried ,it list all the files from the internal storage, but I want to list all the files from specific folder not to list all files from internal storage.
please help out of this problem.

here is my code

 Uri collection;
        final String sortOrder = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
        final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?"
                +" OR " + MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
        final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
        final String jpg = MimeTypeMap.getSingleton().getMimeTypeFromExtension("jpg");
        final String[] selectionArgs = new String[]{mimeType,jpg};
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
        }else{
            collection = MediaStore.Files.getContentUri("external");
        }
        try (Cursor cursor = getContext().getContentResolver().query(collection, null, selection, selectionArgs, sortOrder)) {
            if ((cursor != null) && (cursor.getCount() > 0)) {
                if (cursor.moveToFirst()) {
                    do {
                        @SuppressLint("Range") String columnData = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA));
                        @SuppressLint("Range") String columnName = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME));
                        @SuppressLint("Range") Long date = Long.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATE_MODIFIED)));
                        ModalClass mediaFiles = new ModalClass();
                        mediaFiles.setFileName(columnName);
                        mediaFiles.setPath(columnData);
                        mediaFiles.setDate(date);
                        fileList.add(mediaFiles);
                    } while (cursor.moveToNext());
                }
            }