问:
custom django form field (django-recaptcha) is not added to AuthenticationForm class
objective: adding a new field from (captcha field) within Django Admin Login Form. enabling below method (google captcha v2 - I'm not robot checkbox): https://github.com/torchbox/django-recaptcha

Django: tested on 4.0.X, 4.1.X, 3.2.X versions.

project name: ea_games

app name: ea_app

ea_games\ea_app\forms.py:

```<code>from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import get_user_model
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox

class CustomLoginForm (AuthenticationForm):
    #class Meta:
    #    model = get_user_model()
    #    fields = ('required_checkbox',)    ## comment/un-comment didn't work.

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    required_checkbox = forms.BooleanField(required=True)  ## added to test but it's not showed in django admin login form.

    username = forms.CharField(widget=forms.TextInput(
        attrs={'class': 'form-control', 'placeholder': 'Username or Email'}),
        label="Username or Email")

    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class': 'form-control', 'placeholder': 'Password'}),
        label="Password")

    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox())
</code>```

ea_games\ea_app\views.py:

```<code>class CustomLoginView (LoginView):
    form_class = CustomLoginForm
    template_name = "ea_app/login.html"

    def form_invalid (self, form):
        print ("form_invalid:::::", form)  ## it's not called to print :/
        return self.render_to_response (self.get_context_data(form=form))

    def form_valid (self, form):
        print ("form_valid::::::", form)  ## it's not called to print :/
        checkbox = form.cleaned_data['required_checkbox']
        return super().form_valid(form)
</code>```

ea_games\ea_app\templates\ea_app\login.html:

```<code>{% extends "admin/login.html" %}
</code>```

Also for project's urls.py file, i checked many solutions and they didn't work:

ea_games\urls.py:

```<code>from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.contrib.auth.views import LoginView
from ea_app.forms import CustomLoginForm
from ea_app.views import CustomLoginView
admin.autodiscover()

urlpatterns = [
    #path ('api-auth/', include('rest_framework.urls')),
    #path ('admin/login/', LoginView.as_view(template_name='login.html'), name='login'),
    #path ('admin/login/', LoginView.as_view(authentication_form=CustomLoginForm), name='login'),
    #path ('admin/login/', LoginView.as_view(form_class=CustomLoginForm), name='login'),
    path ('admin/login/', CustomLoginView.as_view(), name="login"),
    path ('admin/',    include('smuggler.urls')),
    path ('admin/',    admin.site.urls),
    path ('',          admin.site.urls),
]
</code>```

Django Captcha App: https://github.com/torchbox/django-recaptcha

Django tutorial worked for him: https://www.youtube.com/watch?v=06gywnBUZ8g. https://pylessons.com/django-recaptcha.

Body:
objective: adding a new field from (captcha field) within Django Admin Login Form. enabling below method (google captcha v2 - I'm not robot checkbox): https://github.com/torchbox/django-recaptcha

Django: tested on 4.0.X, 4.1.X, 3.2.X versions.

project name: ea_games

app name: ea_app

ea_games\ea_app\forms.py:

from django.contrib.auth.forms import AuthenticationForm
from django.contrib.auth import get_user_model
from django import forms
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV2Checkbox

class CustomLoginForm (AuthenticationForm):
    #class Meta:
    #    model = get_user_model()
    #    fields = ('required_checkbox',)    ## comment/un-comment didn't work.

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    required_checkbox = forms.BooleanField(required=True)  ## added to test but it's not showed in django admin login form.

    username = forms.CharField(widget=forms.TextInput(
        attrs={'class': 'form-control', 'placeholder': 'Username or Email'}),
        label="Username or Email")

    password = forms.CharField(widget=forms.PasswordInput(
        attrs={'class': 'form-control', 'placeholder': 'Password'}),
        label="Password")

    captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox())

ea_games\ea_app\views.py:

class CustomLoginView (LoginView):
    form_class = CustomLoginForm
    template_name = "ea_app/login.html"

    def form_invalid (self, form):
        print ("form_invalid:::::", form)  ## it's not called to print :/
        return self.render_to_response (self.get_context_data(form=form))

    def form_valid (self, form):
        print ("form_valid::::::", form)  ## it's not called to print :/
        checkbox = form.cleaned_data['required_checkbox']
        return super().form_valid(form)

ea_games\ea_app\templates\ea_app\login.html:

{% extends "admin/login.html" %}

Also for project's urls.py file, i checked many solutions and they didn't work:

ea_games\urls.py:

from django.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from django.contrib.auth.views import LoginView
from ea_app.forms import CustomLoginForm
from ea_app.views import CustomLoginView
admin.autodiscover()

urlpatterns = [
    #path ('api-auth/', include('rest_framework.urls')),
    #path ('admin/login/', LoginView.as_view(template_name='login.html'), name='login'),
    #path ('admin/login/', LoginView.as_view(authentication_form=CustomLoginForm), name='login'),
    #path ('admin/login/', LoginView.as_view(form_class=CustomLoginForm), name='login'),
    path ('admin/login/', CustomLoginView.as_view(), name="login"),
    path ('admin/',    include('smuggler.urls')),
    path ('admin/',    admin.site.urls),
    path ('',          admin.site.urls),
]

Django Captcha App: https://github.com/torchbox/django-recaptcha

Django tutorial worked for him: https://www.youtube.com/watch?v=06gywnBUZ8g. https://pylessons.com/django-recaptcha.


来源: stackexchange

问:
How to use setTimeout correctly in my sorting visualizer by using React and React Hook?
everyone. I want to create a sorting visualizer and I am working on the bubble sort but I have a problem that I can't solve.

In my plan, the array contains objects, and each object has a number and a color as property. And I have a sorting visualizer which contains two buttons, one is to generate a random array, the other is a sort button. Once the array is generated, you can click on the sort button and it will start to sort.

Bubble sort is one of the functions within the sorting visualizer but it is in a separate file, I want to set arr[j].color and arr[j+1].color to 'turquoise' color prior to comparing. And if arr[j].number > arr[j].number, I want to set it to red color for swapping indication. Then after swapping is done or no need to swap, I want to set both to yellow color temporarily. After maybe 0.5 seconds, I want to set arr[j] back to its default orange color and arr[j + 1] to turquoise color again for the next iteration.

However, in my current code, arr[j] and arr[j+1] will setted to turquoise color but won't become red and yellow no matter how I set it up. But the rest of my coding is working fine and sorting seems it's ok too. It really confused me because the arr[j] color can be set back to orange color.

If I don't solve this one, I cannot solve the insertion sort because I need to change the element color during the sorting and swapping process.

Please help me out. Thank you.

My bubble sort code:

```<code>`const bubbleSort = async(arr, setArray, delay)  => {
      // Note: this loop runs to completion before any setTimeout callbacks are run.
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

          // Make a copy so the setTimeout below has a "snapshot" of the array at
          // this point in time.
          const arrCopy = [...arr];

          arr = arrCopy;
          setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'turquoise';
              arrCopy[j + 1].color = 'turquoise';
              setArray(arrCopy);
          }, delay);

          await new Promise(resolve => setTimeout(() => resolve(), delay));

          // Swap here if index j element is greater than the index j+1 element.
          if (arr[j].number > arr[j + 1].number) {

            arr = arrCopy;
            setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'red';
              arrCopy[j + 1].color = 'red';
              setArray(arrCopy);
            }, delay);

            let temp = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = temp;

            arr = arrCopy;
            setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'yellow';
              arrCopy[j + 1].color = 'yellow';
              setArray(arrCopy);
            }, delay);
          }

          // Set the index j element back to orange color.
          arr = arrCopy;
          setTimeout(() => {
            arrCopy[j].color = '#FF8200';
            setArray(arrCopy);
          }, delay);

          // If this loop hit the up bound, means this round of the nested loop
          // is done sorting, make the last index element to purple color.
          if((j + 1) === arr.length - i - 1) {
            arr = arrCopy;
            setTimeout(() => {
              arrCopy[j+1].color = 'purple';
              setArray(arrCopy);
            }, delay);
          }
        }
      }

      // After done sorting, make the first element of the array
      // to purple color as well.
      const arrCopy = [...arr];
      arr = arrCopy;
      setTimeout(() => {
        arrCopy[0].color = 'purple';
        setArray(arrCopy);
      }, delay);
}

export default bubbleSort;
</code>```
```<code>

My sorting visualizer code:

import React, { useRef, useState, useEffect } from 'react';
import bubbleSortTry from '../Algorithm/bubbleSortTry';

const SortingVisualizer = (props) => {

    const [array, setArray] = useState([]);
    const [dataSortBtnStatus, setDataSortBtnStatus] = useState(true);

    function generateRandomArrayClick() {
        // Generate an array with 50 random elements between 1 and 75
        const tempArr = [];
        for (let i = 0; i < props.dataSize; i++) {
            let numTemp = randomIntFromInterval(1, 100);
            tempArr.push({number: numTemp, color: `#FF8200`});
        }
        setArray(tempArr);
        setDataSortBtnStatus(false);
    }

    function handleSort() {
        if(props.name === "Bubble Sort") {
            // bubbleSort(array, setArray, props.delay);
            // bubbleSortPrime(array, setArray, props.delay);
            bubbleSortTry(array, setArray, props.delay);
        } else if(props.name === "Selection Sort") {
            // selectionSort(array, setArray, 3000);
            selectionSort(array, setArray, props.delay);
        } else if(props.name === "Insertion Sort") {
            // insertionSort([36,8,1,18,54,100,29,70], setArray, props.delay);
            insertionSort(array, setArray, 1000);
        }
        setDataSortBtnStatus(true);
    }

    // const resetArray = (size) => {
    //     console.log("YEAH");
    //     const arr = [];
    //     for(let i = 0; i < size; i++) {
    //       arr.push(randomIntFromInterval(1, 100));
    //     }
    //     setArray(arr);
    // }

    const randomIntFromInterval = (min, max) => {
       // min and max included
       return Math.floor(Math.random() * (max - min + 1) + min);
    }

    return(
        <div>
            {/*This div has generate and run algorithm buttons inside*/}
            <div>
                <div className='pt1' style={{display: 'flex', justifyContent: 'flex-end'}}>
                    <button
                        className='black b f3 pa2 mb3 mr3 br3 dim pointer shadow-3'
                        style={{backgroundColor: '#00d1b2'}}
                        onClick={generateRandomArrayClick}>Generate Random Data</button>
                <button
                    className='black b f3 pa2 mb3 ml3 mr4 br3 dim pointer shadow-3'
                    style={{backgroundColor: '#D16E00'}}
                    value={props.name}
                    onClick={handleSort}
                    disabled={dataSortBtnStatus}>Run {props.name}</button>
                </div>
            </div>

            <div
            className='ba b--black bw2 ma3'
            style={{display: 'flex', justifyContent: 'flex-center', height: '52vh', width: '97%', transform: 'scaleY(-1)'}}
        >
            {/*<p>The current height of the div is {divHeight}px. </p>
              <p>The current width of the div is {divWidth}px. </p>
              <p>The current data size is {props.generatedArray.forEach(console.log)}. </p>*/}

              {array.length === 0 ?
                    null
                    :
                    array.map((element,index) => (
                        <div
                            className='dib ba b-black'
                            key={index}
                            style={{
                                height: `${element.number}%`,
                                width: '100%',
                                backgroundColor: element.color
                            }}
                      />
              ))}
           </div>
        </div>
    );
}

export default SortingVisualizer;
</code>```

In the beginning, I thought it was a callback problem because I know that a lot of callback functions come back at the same time maybe not having enough time to see the changing or updating.

So I did something below:

```<code>
const SortingVisualizer = (props) => {
    let newDelay = 0;
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

            .......

            arr = arrCopy;
            setTimeout(() => {
              .....
          }, newDelay);
          newDelay += 500;
         ....
</code>```

But that's not work. I used console.log to check. It turned out that newDelay is the total of after looping done.

Then I created an array try to solve that:

```<code>
const SortingVisualizer = (props) => {
    let delayArr = new Array();
    let newDelay = 0;
    const spacing = 500;
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

            .......
            delayArr.push(newDelay);

            arr = arrCopy;
            setTimeout(() => {
              .....
          }, delayArr.shift());
          newDelay += spacing;
          delayArr.push(newDelay);
         ....
</code>```

That still not work, but I used console.log and saw that the output of delayArr was not the same, it was incremented. Then I think maybe callback it not the case.

I also try to have const arrCopy = [...arr]; out of for loop and modified everything from arr to arrCopy, just like:

```<code>const bubbleSort = async(arr, setArray, delay)  => {
     const arrCopy = [...arr];
     for (let i = 0; i < arrCopy.length; i++) {
          for (let j = 0; j < arrCopy.length - i - 1; j++) {
          .....
</code>```

But the sorting visualizer did not update.

ContentLicense: CC BY-SA 4.0

Body:
everyone. I want to create a sorting visualizer and I am working on the bubble sort but I have a problem that I can't solve.

In my plan, the array contains objects, and each object has a number and a color as property. And I have a sorting visualizer which contains two buttons, one is to generate a random array, the other is a sort button. Once the array is generated, you can click on the sort button and it will start to sort.

Bubble sort is one of the functions within the sorting visualizer but it is in a separate file, I want to set arr[j].color and arr[j+1].color to 'turquoise' color prior to comparing. And if arr[j].number > arr[j].number, I want to set it to red color for swapping indication. Then after swapping is done or no need to swap, I want to set both to yellow color temporarily. After maybe 0.5 seconds, I want to set arr[j] back to its default orange color and arr[j + 1] to turquoise color again for the next iteration.

However, in my current code, arr[j] and arr[j+1] will setted to turquoise color but won't become red and yellow no matter how I set it up. But the rest of my coding is working fine and sorting seems it's ok too. It really confused me because the arr[j] color can be set back to orange color.

If I don't solve this one, I cannot solve the insertion sort because I need to change the element color during the sorting and swapping process.

Please help me out. Thank you.

My bubble sort code:

`const bubbleSort = async(arr, setArray, delay)  => {
      // Note: this loop runs to completion before any setTimeout callbacks are run.
      for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

          // Make a copy so the setTimeout below has a "snapshot" of the array at
          // this point in time.
          const arrCopy = [...arr];

          arr = arrCopy;
          setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'turquoise';
              arrCopy[j + 1].color = 'turquoise';
              setArray(arrCopy);
          }, delay);

          await new Promise(resolve => setTimeout(() => resolve(), delay));

          // Swap here if index j element is greater than the index j+1 element.
          if (arr[j].number > arr[j + 1].number) {

            arr = arrCopy;
            setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'red';
              arrCopy[j + 1].color = 'red';
              setArray(arrCopy);
            }, delay);

            let temp = arr[j + 1];
            arr[j + 1] = arr[j];
            arr[j] = temp;

            arr = arrCopy;
            setTimeout(() => {
              // Make two comparing elements to turquoise color.
              arrCopy[j].color = 'yellow';
              arrCopy[j + 1].color = 'yellow';
              setArray(arrCopy);
            }, delay);
          }

          // Set the index j element back to orange color.
          arr = arrCopy;
          setTimeout(() => {
            arrCopy[j].color = '#FF8200';
            setArray(arrCopy);
          }, delay);

          // If this loop hit the up bound, means this round of the nested loop
          // is done sorting, make the last index element to purple color.
          if((j + 1) === arr.length - i - 1) {
            arr = arrCopy;
            setTimeout(() => {
              arrCopy[j+1].color = 'purple';
              setArray(arrCopy);
            }, delay);
          }
        }
      }

      // After done sorting, make the first element of the array
      // to purple color as well.
      const arrCopy = [...arr];
      arr = arrCopy;
      setTimeout(() => {
        arrCopy[0].color = 'purple';
        setArray(arrCopy);
      }, delay);
}

export default bubbleSort;

My sorting visualizer code:

import React, { useRef, useState, useEffect } from 'react';
import bubbleSortTry from '../Algorithm/bubbleSortTry';

const SortingVisualizer = (props) => {

    const [array, setArray] = useState([]);
    const [dataSortBtnStatus, setDataSortBtnStatus] = useState(true);

    function generateRandomArrayClick() {
        // Generate an array with 50 random elements between 1 and 75
        const tempArr = [];
        for (let i = 0; i < props.dataSize; i++) {
            let numTemp = randomIntFromInterval(1, 100);
            tempArr.push({number: numTemp, color: `#FF8200`});
        }
        setArray(tempArr);
        setDataSortBtnStatus(false);
    }

    function handleSort() {
        if(props.name === "Bubble Sort") {
            // bubbleSort(array, setArray, props.delay);
            // bubbleSortPrime(array, setArray, props.delay);
            bubbleSortTry(array, setArray, props.delay);
        } else if(props.name === "Selection Sort") {
            // selectionSort(array, setArray, 3000);
            selectionSort(array, setArray, props.delay);
        } else if(props.name === "Insertion Sort") {
            // insertionSort([36,8,1,18,54,100,29,70], setArray, props.delay);
            insertionSort(array, setArray, 1000);
        }
        setDataSortBtnStatus(true);
    }

    // const resetArray = (size) => {
    //     console.log("YEAH");
    //     const arr = [];
    //     for(let i = 0; i < size; i++) {
    //       arr.push(randomIntFromInterval(1, 100));
    //     }
    //     setArray(arr);
    // }

    const randomIntFromInterval = (min, max) => {
       // min and max included
       return Math.floor(Math.random() * (max - min + 1) + min);
    }

    return(

            {/*This div has generate and run algorithm buttons inside*/}

                    <button
                        className='black b f3 pa2 mb3 mr3 br3 dim pointer shadow-3'
                        style={{backgroundColor: '#00d1b2'}}
                        onClick={generateRandomArrayClick}>Generate Random Data</button>
                <button
                    className='black b f3 pa2 mb3 ml3 mr4 br3 dim pointer shadow-3'
                    style={{backgroundColor: '#D16E00'}}
                    value={props.name}
                    onClick={handleSort}
                    disabled={dataSortBtnStatus}>Run {props.name}</button>

            {/*
The current height of the div is {divHeight}px.

The current width of the div is {divWidth}px.

The current data size is {props.generatedArray.forEach(console.log)}.
*/}

              {array.length === 0 ?
                    null
                    :
                    array.map((element,index) => (
                        <div
                            className='dib ba b-black'
                            key={index}
                            style={{
                                height: `${element.number}%`,
                                width: '100%',
                                backgroundColor: element.color
                            }}
                      />
              ))}

    );
}

export default SortingVisualizer;

In the beginning, I thought it was a callback problem because I know that a lot of callback functions come back at the same time maybe not having enough time to see the changing or updating.

So I did something below:

const SortingVisualizer = (props) => {
    let newDelay = 0;
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

            .......

            arr = arrCopy;
            setTimeout(() => {
              .....
          }, newDelay);
          newDelay += 500;
         ....

But that's not work. I used console.log to check. It turned out that newDelay is the total of after looping done.

Then I created an array try to solve that:

const SortingVisualizer = (props) => {
    let delayArr = new Array();
    let newDelay = 0;
    const spacing = 500;
    for (let i = 0; i < arr.length; i++) {
        for (let j = 0; j < arr.length - i - 1; j++) {

            .......
            delayArr.push(newDelay);

            arr = arrCopy;
            setTimeout(() => {
              .....
          }, delayArr.shift());
          newDelay += spacing;
          delayArr.push(newDelay);
         ....

That still not work, but I used console.log and saw that the output of delayArr was not the same, it was incremented. Then I think maybe callback it not the case.

I also try to have const arrCopy = [...arr]; out of for loop and modified everything from arr to arrCopy, just like:

const bubbleSort = async(arr, setArray, delay)  => {
     const arrCopy = [...arr];
     for (let i = 0; i < arrCopy.length; i++) {
          for (let j = 0; j < arrCopy.length - i - 1; j++) {
          .....

But the sorting visualizer did not update.


问:
How to make CanBus communication via Simulink for stm32 Nucleo H7 board via modules
I cannot communicate with Canbus using the Can read and Can write models on Simulink, I do not know how to use the modules.
How should I do the Canbus communication that will use these modules for the Nucleo h7 card?

I couldn't figure out how to use the modules exactly the resource is too few.


问:
How can I save all session information of Webview tabs using Flutter?
I am planning a mobile application that will enable users to log in easily, although some applications' login information is saved very easily, unfortunately not all of them are.

flutter_inappwebview Using this package I can save users' localStorage and cookies, but for a specific application I need to save data in IndexedDB as well. I set this data again every time the browser starts. Is there a feature where I can save the complete browser information or is there a way to save IndexedDB?


问:
Encountering Out of range error while training on TPU
I have been following notebooks on Kaggle to train models on TPU. This and This where the former notebook shows to make TF Records and the latter one to train models on TPU with these TF Records.
I am strictly following these two notebooks but still encountering with strange error. I am using Skin Cancer HAM10000 dataset from Kaggle.
The error looks like this

```<code>OutOfRangeError: 9 root error(s) found.
  (0) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_2}}]]
  (1) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[tpu_compile_succeeded_assert/_1935868936045555324/_5/_143]]
  (2) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[TPUReplicate/_compile/_17327685160909203060/_4/_108]]
  (3) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[Pad_7/_86]]
  (4) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[Pad_15/_150]]
  (5) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[strided_slice_30/_120]]
  (6) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[TPUReplicate/_compile/_17327685160909203060/_4/_44]]
  (7) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[IteratorGetNext_5/_24]]
  (8) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
0 successful operations.
0 derived errors ignored.
</code>```

I have been searching over the internet for these issues and changing some Hyperparameters but could not able to resolve it. My notebook is here
Please have a look into it and I would be grateful to get a reply back.
Thank you.

Body:
I have been following notebooks on Kaggle to train models on TPU. This and This where the former notebook shows to make TF Records and the latter one to train models on TPU with these TF Records.
I am strictly following these two notebooks but still encountering with strange error. I am using Skin Cancer HAM10000 dataset from Kaggle.
The error looks like this

OutOfRangeError: 9 root error(s) found.
  (0) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_2}}]]
  (1) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[tpu_compile_succeeded_assert/_1935868936045555324/_5/_143]]
  (2) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[TPUReplicate/_compile/_17327685160909203060/_4/_108]]
  (3) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[Pad_7/_86]]
  (4) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[Pad_15/_150]]
  (5) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[strided_slice_30/_120]]
  (6) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[TPUReplicate/_compile/_17327685160909203060/_4/_44]]
  (7) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
     [[IteratorGetNext_5/_24]]
  (8) Out of range: {{function_node __inference_train_function_24967}} End of sequence
     [[{{node IteratorGetNext_1}}]]
0 successful operations.
0 derived errors ignored.

I have been searching over the internet for these issues and changing some Hyperparameters but could not able to resolve it. My notebook is here
Please have a look into it and I would be grateful to get a reply back.
Thank you.


问:
Create a struct from a random input string
I am wondering, is it possible to create any struct from a random input string in C++? For example, if I input a string:

1, "apple", 2

then I would like to have a struct:

struct{int, string, int}

If I input:

"a", "b", 1

Then I would like to have a struct:

struct{string, string, int}

So, the struct would be defined dynamically, based on the input string. Is there any method for doing this in C++?


问:
PHP 8.1 DateTime Diff returns wrong result using different Timezones
I need to calc the years between two dates. When one of the dates are in UTC I get a negative value for year. In this case I get -30. It should be +29. Anyone had the same problem?
This happens only as of PHP 8.1.10

```<code>$startDate = new \DateTimeImmutable('1993-06-05 00:00:00', new \DateTimeZone('UTC'));
$endDate = new \DateTimeImmutable('2023-01-02 00:00:00', new \DateTimeZone('Europe/Berlin'));

var_dump($startDate->diff($endDate));
</code>```
```<code>object(DateInterval)#3 (16) {
  ["y"]=>
  int(-30)
}
</code>```

Online Demo

Body:
I need to calc the years between two dates. When one of the dates are in UTC I get a negative value for year. In this case I get -30. It should be +29. Anyone had the same problem?
This happens only as of PHP 8.1.10

$startDate = new \DateTimeImmutable('1993-06-05 00:00:00', new \DateTimeZone('UTC'));
$endDate = new \DateTimeImmutable('2023-01-02 00:00:00', new \DateTimeZone('Europe/Berlin'));

var_dump($startDate->diff($endDate));

object(DateInterval)#3 (16) {
  ["y"]=>
  int(-30)
}

Online Demo


问:
404 error on new pages with wordpress blog ( on mysql) with django (postgres) using nginx on the same server
Condition :
I have set up my server as follows :
my wordpress blog ( on mysql) with
django (postgres)
using nginx on the same server.

Error

I am getting 404 error for new pages I create on the blog. ( it works when permalink settings is like this : https://www.example.com/blog/?p=1

It does not work when permalink setting contains post name

New pages I create also behave in similar fashion - do not work with name slug

My analysis is that it has something to do with ssl conf or nginx conf. Basically routing issue. I am a newbie.

Here is the Nginx Conf:

```<code>upstream app_server {
    server unix:/home/user/opt/env/run/gunicorn.sock fail_timeout=0;
}

#wordpress php handler
upstream wordpress-prod-php-handler {
    server unix:/var/run/php/php7.0-fpm.sock;

</code>```
```<code># serve wordpress from subdirectory
        location /blog {
        alias /home/user/opt/blog;
        index index.php;
        try_files $uri $uri/ /blog/index.php?$args;
        location ~ \.php$ {
          include snippets/fastcgi-php.conf;
          fastcgi_param SCRIPT_FILENAME $request_filename;
          fastcgi_pass wordpress-prod-php-handler;
        }
    }

</code>```

Please help..

As specified, I was trying to get my blog and app on the same domain.

www.example.com -> opens django app
www.example.com/blog -> opens wordpress blog

Now it works fine, but if anything comes after /blog -- such as example.com/blog/test will result in a 404 error.

Nginx error log shows this :
2022/12/31 14:04:01 [error] 24005#24005: *3968 open() "/usr/share/nginx/htmlindex.php" failed (2: No such file or directory), client: 122.161.15.206, server: www.example.com, request: "GET /blog/7-reasons-for-xyz/ HTTP/2.0", host: "www.example.com", referrer: "https://www.example.com/blog/"

Body:
Condition :
I have set up my server as follows :
my wordpress blog ( on mysql) with
django (postgres)
using nginx on the same server.

Error

I am getting 404 error for new pages I create on the blog. ( it works when permalink settings is like this : https://www.example.com/blog/?p=1

It does not work when permalink setting contains post name

New pages I create also behave in similar fashion - do not work with name slug

My analysis is that it has something to do with ssl conf or nginx conf. Basically routing issue. I am a newbie.

Here is the Nginx Conf:

upstream app_server {
    server unix:/home/user/opt/env/run/gunicorn.sock fail_timeout=0;
}

#wordpress php handler
upstream wordpress-prod-php-handler {
    server unix:/var/run/php/php7.0-fpm.sock;

# serve wordpress from subdirectory
        location /blog {
        alias /home/user/opt/blog;
        index index.php;
        try_files $uri $uri/ /blog/index.php?$args;
        location ~ \.php$ {
          include snippets/fastcgi-php.conf;
          fastcgi_param SCRIPT_FILENAME $request_filename;
          fastcgi_pass wordpress-prod-php-handler;
        }
    }

Please help..

As specified, I was trying to get my blog and app on the same domain.

www.example.com -> opens django app
www.example.com/blog -> opens wordpress blog

Now it works fine, but if anything comes after /blog -- such as example.com/blog/test will result in a 404 error.

Nginx error log shows this :
2022/12/31 14:04:01 [error] 24005#24005: *3968 open() "/usr/share/nginx/htmlindex.php" failed (2: No such file or directory), client: 122.161.15.206, server: www.example.com, request: "GET /blog/7-reasons-for-xyz/ HTTP/2.0", host: "www.example.com", referrer: "https://www.example.com/blog/"


问:
Unable to access routes after deployed Laravel Project on WHM server
I can only access welcome route of laravel  after deploye my project on WHM server. If I am try to get "/login" or "/user" somekind of this site shows me Not found 404 Error. Please help me.

I want run access other routes except "/" index route but getting 404 error.


问:
A strange error occurs when running mvn test on a UNIX server
The development environment is Unix, Java 11, Spring Boot 2.6.9, Maven 3.8.6

I use Unix server, I try 'mvn test' command in springboot project,
the following error occurred when conducting the test related to the data source.

```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.example:FB_FE_020_SD_08025 >-------------------
[INFO] Building FB_FE_020_SD_08025 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ FB_FE_020_SD_08025 ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
java.lang.ArrayIndexOutOfBoundsException: Index 112 out of bounds for length 100
        at org.fusesource.jansi.io.AnsiOutputStream.write(AnsiOutputStream.java:196)
        at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:137)
        at java.base/java.io.PrintStream.write(PrintStream.java:559)
        at java.base/sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:233)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:303)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:281)
        at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
        at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
        at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
        at java.base/java.io.PrintStream.write(PrintStream.java:605)
        at java.base/java.io.PrintStream.print(PrintStream.java:745)
        at java.base/java.io.PrintStream.println(PrintStream.java:882)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:414)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
</code>```

It was so weird that I didn't write anything in the test method and when I proceeded with the test, a strange error occurred

```<code>@Test
void test(){

}
</code>```
```<code>[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.woorifis:FB_FE_020_SD_08025 >-------------------
[INFO] Building FB_FE_020_SD_08025 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ FB_FE_020_SD_08025 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /app/sechul/peb-klid-project/peb-klid-project/FB_FE_020_SD_08025/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ FB_FE_020_SD_08025 ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
java.lang.NumberFormatException: For input string: "1;[[[[[["
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:654)
        at java.base/java.lang.Integer.valueOf(Integer.java:985)
        at org.fusesource.jansi.io.AnsiOutputStream.write(AnsiOutputStream.java:199)
        at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:137)
        at java.base/java.io.PrintStream.write(PrintStream.java:559)
        at java.base/sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:233)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:303)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:281)
        at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
        at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
        at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
        at java.base/java.io.PrintStream.write(PrintStream.java:605)
        at java.base/java.io.PrintStream.print(PrintStream.java:745)
        at java.base/java.io.PrintStream.println(PrintStream.java:882)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:414)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)
</code>```

I don't think it's an application problem, so what should I check?

Body:
The development environment is Unix, Java 11, Spring Boot 2.6.9, Maven 3.8.6

I use Unix server, I try 'mvn test' command in springboot project,
the following error occurred when conducting the test related to the data source.

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.example:FB_FE_020_SD_08025 >-------------------
[INFO] Building FB_FE_020_SD_08025 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ FB_FE_020_SD_08025 ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
java.lang.ArrayIndexOutOfBoundsException: Index 112 out of bounds for length 100
        at org.fusesource.jansi.io.AnsiOutputStream.write(AnsiOutputStream.java:196)
        at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:137)
        at java.base/java.io.PrintStream.write(PrintStream.java:559)
        at java.base/sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:233)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:303)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:281)
        at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
        at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
        at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
        at java.base/java.io.PrintStream.write(PrintStream.java:605)
        at java.base/java.io.PrintStream.print(PrintStream.java:745)
        at java.base/java.io.PrintStream.println(PrintStream.java:882)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:414)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)

It was so weird that I didn't write anything in the test method and when I proceeded with the test, a strange error occurred

@Test
void test(){

}

[INFO] Scanning for projects...
[INFO]
[INFO] ------------------< com.woorifis:FB_FE_020_SD_08025 >-------------------
[INFO] Building FB_FE_020_SD_08025 1.0
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:resources (default-resources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ FB_FE_020_SD_08025 ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.2.0:testResources (default-testResources) @ FB_FE_020_SD_08025 ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Using 'UTF-8' encoding to copy filtered properties files.
[INFO] Copying 3 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ FB_FE_020_SD_08025 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /app/sechul/peb-klid-project/peb-klid-project/FB_FE_020_SD_08025/target/test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ FB_FE_020_SD_08025 ---
[INFO]
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
java.lang.NumberFormatException: For input string: "1;[[[[[["
        at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
        at java.base/java.lang.Integer.parseInt(Integer.java:654)
        at java.base/java.lang.Integer.valueOf(Integer.java:985)
        at org.fusesource.jansi.io.AnsiOutputStream.write(AnsiOutputStream.java:199)
        at java.base/java.io.FilterOutputStream.write(FilterOutputStream.java:137)
        at java.base/java.io.PrintStream.write(PrintStream.java:559)
        at java.base/sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:233)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:303)
        at java.base/sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:281)
        at java.base/sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
        at java.base/java.io.OutputStreamWriter.write(OutputStreamWriter.java:208)
        at java.base/java.io.BufferedWriter.flushBuffer(BufferedWriter.java:120)
        at java.base/java.io.PrintStream.write(PrintStream.java:605)
        at java.base/java.io.PrintStream.print(PrintStream.java:745)
        at java.base/java.io.PrintStream.println(PrintStream.java:882)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:414)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)

I don't think it's an application problem, so what should I check?


问:
Why ExoPlayer's TimelineQueueNavigator.getMediaDescription method giving wrong index that results in crash due to IndexOutOfBoundsException
I was watching a tutorial and but I don't know why the windowIndex parameter  in my case is giving wrong index , sometimes it even gives index of 7 while there are only 3 items in there.
See if you guys can find something .

Here is the error log -

```<code>2022-12-31 14:12:40.844 15041-15041 AndroidRuntime          com.example.spotifyclone             D  Shutting down VM
2022-12-31 14:12:40.861 15041-15041 AndroidRuntime          com.example.spotifyclone             E  FATAL EXCEPTION: main
                                                                                Process: com.example.spotifyclone, PID: 15041
                                                                                java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
                                                                                at java.util.ArrayList.get(ArrayList.java:437)
                                                                                at com.example.spotifyclone.exoplayer.MusicService$MusicQueueNavigator.getMediaDescription(MusicService.kt:120)
                                                                                at com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator.publishFloatingQueueWindow(TimelineQueueNavigator.java:207)
                                                                                at com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator.onTimelineChanged(TimelineQueueNavigator.java:127)
                                                                                at com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector$ComponentListener.onEvents(MediaSessionConnector.java:1146)
                                                                                at com.google.android.exoplayer2.ExoPlayerImpl.lambda$new$0$com-google-android-exoplayer2-ExoPlayerImpl(ExoPlayerImpl.java:265)
                                                                                at com.google.android.exoplayer2.ExoPlayerImpl$$ExternalSyntheticLambda11.invoke(Unknown Source:4)
                                                                                at com.google.android.exoplayer2.util.ListenerSet$ListenerHolder.iterationFinished(ListenerSet.java:293)
                                                                                at com.google.android.exoplayer2.util.ListenerSet.handleMessage(ListenerSet.java:244)
                                                                                at com.google.android.exoplayer2.util.ListenerSet.$r8$lambda$eEvjP-IE0x3J2lRvKfFbbjRFRvc(Unknown Source:0)
                                                                                at com.google.android.exoplayer2.util.ListenerSet$$ExternalSyntheticLambda0.handleMessage(Unknown Source:2)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loopOnce(Looper.java:233)
                                                                                at android.os.Looper.loop(Looper.java:344)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:8212)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)
</code>```

TimelineQueueNavigator Implementation -

```<code>private inner class MusicQueueNavigator: TimelineQueueNavigator(mediaSession) {
    override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat {
        return firebaseMusicSource.songs[windowIndex].description
    }
}
</code>```

And the MusicService file -

```<code>private const val SERVICE_TAG = "MusicServiceTag"

@AndroidEntryPoint
class MusicService: MediaBrowserServiceCompat() {

    @Inject
    lateinit var dataSourceFactory: DefaultDataSource.Factory

    @Inject
    lateinit var exoPlayer:ExoPlayer

    @Inject
    lateinit var firebaseMusicSource:FirebaseMusicSource

    private val serviceJob = Job()

    // merge properties of our job and main so our custom scope is formed
    private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)

    // to cumminicate with service of current music we have music session
    private lateinit var mediaSession:MediaSessionCompat
    private lateinit var mediaSessionConnector:MediaSessionConnector
    private lateinit var musicNotificationManager: MusicNotificationManager

    private lateinit var musicPlayerEventListener:MusicPlayerEventListener

    var isforegroundService = false
    private var curPlayingSong: MediaMetadataCompat? = null

    private var isPlayerPrepared = false

    companion object{
        var curSongDuration = 0L
        private set
    }

    override fun onCreate() {
        super.onCreate()

        serviceScope.launch {
            firebaseMusicSource.fetchMediaData()
        }

        //to do something on notification click we have this intent
        val activityIntent = packageManager?.getLaunchIntentForPackage(packageName)?.let {
            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_MUTABLE)
            else PendingIntent.getActivity(this, 0, it, 0 )
        }

        mediaSession = MediaSessionCompat(this, SERVICE_TAG).apply {
            setSessionActivity(activityIntent)
            isActive = true
        }

        /* service extends MediaBrowserServiceCompat and it contains the sessionToken property
        that can be used to get info about specific different music session using different tokens */
        sessionToken = mediaSession.sessionToken

        musicNotificationManager = MusicNotificationManager(
            context= this,
            sessionToken = mediaSession.sessionToken,
            notificationListener= MusicPlayerNotificationListener(this),
            newSongCallbacks= {
                curSongDuration = exoPlayer.duration
            }
        )

        val musicPlaybackPreparer:MusicPlaybackPreparer = MusicPlaybackPreparer(firebaseMusicSource){
            curPlayingSong = it
            preparePlayer(
                firebaseMusicSource.songs,
                it,
                true
            )
            Log.d("MUSICSERVICE", "Player Playback prepared and also player prepared ")
        }

        mediaSessionConnector = MediaSessionConnector(mediaSession)
        mediaSessionConnector.setPlaybackPreparer(musicPlaybackPreparer)
        mediaSessionConnector.setPlayer(exoPlayer)
        mediaSessionConnector.setQueueNavigator(MusicQueueNavigator())

        musicPlayerEventListener = MusicPlayerEventListener(this)
        exoPlayer.addListener(musicPlayerEventListener)
        musicNotificationManager.showNotification(exoPlayer)
    }

    private inner class MusicQueueNavigator: TimelineQueueNavigator(mediaSession) {
        override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat {
            return firebaseMusicSource.songs[windowIndex].description
        }
    }

    private fun preparePlayer(
        songs:List<MediaMetadataCompat>,
        itemToPlay:MediaMetadataCompat?,
        playNow: Boolean
    ){
        val curSongIndex = if(curPlayingSong == null) 0 else songs.indexOf(itemToPlay)

        exoPlayer.prepare()
        exoPlayer.addMediaSource(firebaseMusicSource.asMediaSource(dataSourceFactory))
        exoPlayer.seekTo(curSongIndex,0L)
        exoPlayer.playWhenReady =  playNow
        Log.d("MUSICSERVICE", "Player prepared ")
    }

    override fun onGetRoot(
        clientPackageName: String,
        clientUid: Int,
        rootHints: Bundle?
    ): BrowserRoot? {

        return BrowserRoot(MEDIA_ROOT_ID, null)

    }

    override fun onLoadChildren(
        parentId: String,
        result: Result<MutableList<MediaBrowserCompat.MediaItem>>
    ) {
        when(parentId){

            MEDIA_ROOT_ID -> {
                val resultSent:Boolean = firebaseMusicSource.whenReady { isInitialized ->
                    if(isInitialized){
                        result.sendResult(firebaseMusicSource.asMediaItem())
                        if(!isPlayerPrepared && firebaseMusicSource.songs.isEmpty()){
                            preparePlayer( firebaseMusicSource.songs, firebaseMusicSource.songs[0], false )
                            isPlayerPrepared = true
                            Log.d("MUSICSERVICE", "Player prepared during loadChildren ")
                        }
                    }else{
                        mediaSession.sendSessionEvent(NETWORK_ERROR, null)
                        result.sendResult(null)

                    }
                }

                if(!resultSent){
                    // wait for some time to get results ready and call the whole
                    // loading thing after some time
                    result.detach()
                }

            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()

        exoPlayer.release()
        exoPlayer.removeListener(musicPlayerEventListener)
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        exoPlayer.stop()
    }

}
</code>```

Here is complete logcat stack trace : Stacktrace

Body:
I was watching a tutorial and but I don't know why the windowIndex parameter  in my case is giving wrong index , sometimes it even gives index of 7 while there are only 3 items in there.
See if you guys can find something .

Here is the error log -

2022-12-31 14:12:40.844 15041-15041 AndroidRuntime          com.example.spotifyclone             D  Shutting down VM
2022-12-31 14:12:40.861 15041-15041 AndroidRuntime          com.example.spotifyclone             E  FATAL EXCEPTION: main
                                                                                Process: com.example.spotifyclone, PID: 15041
                                                                                java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
                                                                                at java.util.ArrayList.get(ArrayList.java:437)
                                                                                at com.example.spotifyclone.exoplayer.MusicService$MusicQueueNavigator.getMediaDescription(MusicService.kt:120)
                                                                                at com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator.publishFloatingQueueWindow(TimelineQueueNavigator.java:207)
                                                                                at com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator.onTimelineChanged(TimelineQueueNavigator.java:127)
                                                                                at com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector$ComponentListener.onEvents(MediaSessionConnector.java:1146)
                                                                                at com.google.android.exoplayer2.ExoPlayerImpl.lambda$new$0$com-google-android-exoplayer2-ExoPlayerImpl(ExoPlayerImpl.java:265)
                                                                                at com.google.android.exoplayer2.ExoPlayerImpl$$ExternalSyntheticLambda11.invoke(Unknown Source:4)
                                                                                at com.google.android.exoplayer2.util.ListenerSet$ListenerHolder.iterationFinished(ListenerSet.java:293)
                                                                                at com.google.android.exoplayer2.util.ListenerSet.handleMessage(ListenerSet.java:244)
                                                                                at com.google.android.exoplayer2.util.ListenerSet.$r8$lambda$eEvjP-IE0x3J2lRvKfFbbjRFRvc(Unknown Source:0)
                                                                                at com.google.android.exoplayer2.util.ListenerSet$$ExternalSyntheticLambda0.handleMessage(Unknown Source:2)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loopOnce(Looper.java:233)
                                                                                at android.os.Looper.loop(Looper.java:344)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:8212)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:584)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)

TimelineQueueNavigator Implementation -

private inner class MusicQueueNavigator: TimelineQueueNavigator(mediaSession) {
    override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat {
        return firebaseMusicSource.songs[windowIndex].description
    }
}

And the MusicService file -

private const val SERVICE_TAG = "MusicServiceTag"

@AndroidEntryPoint
class MusicService: MediaBrowserServiceCompat() {

    @Inject
    lateinit var dataSourceFactory: DefaultDataSource.Factory

    @Inject
    lateinit var exoPlayer:ExoPlayer

    @Inject
    lateinit var firebaseMusicSource:FirebaseMusicSource

    private val serviceJob = Job()

    // merge properties of our job and main so our custom scope is formed
    private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)

    // to cumminicate with service of current music we have music session
    private lateinit var mediaSession:MediaSessionCompat
    private lateinit var mediaSessionConnector:MediaSessionConnector
    private lateinit var musicNotificationManager: MusicNotificationManager

    private lateinit var musicPlayerEventListener:MusicPlayerEventListener

    var isforegroundService = false
    private var curPlayingSong: MediaMetadataCompat? = null

    private var isPlayerPrepared = false

    companion object{
        var curSongDuration = 0L
        private set
    }

    override fun onCreate() {
        super.onCreate()

        serviceScope.launch {
            firebaseMusicSource.fetchMediaData()
        }

        //to do something on notification click we have this intent
        val activityIntent = packageManager?.getLaunchIntentForPackage(packageName)?.let {
            if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ) PendingIntent.getActivity(this, 0, it, PendingIntent.FLAG_MUTABLE)
            else PendingIntent.getActivity(this, 0, it, 0 )
        }

        mediaSession = MediaSessionCompat(this, SERVICE_TAG).apply {
            setSessionActivity(activityIntent)
            isActive = true
        }

        /* service extends MediaBrowserServiceCompat and it contains the sessionToken property
        that can be used to get info about specific different music session using different tokens */
        sessionToken = mediaSession.sessionToken

        musicNotificationManager = MusicNotificationManager(
            context= this,
            sessionToken = mediaSession.sessionToken,
            notificationListener= MusicPlayerNotificationListener(this),
            newSongCallbacks= {
                curSongDuration = exoPlayer.duration
            }
        )

        val musicPlaybackPreparer:MusicPlaybackPreparer = MusicPlaybackPreparer(firebaseMusicSource){
            curPlayingSong = it
            preparePlayer(
                firebaseMusicSource.songs,
                it,
                true
            )
            Log.d("MUSICSERVICE", "Player Playback prepared and also player prepared ")
        }

        mediaSessionConnector = MediaSessionConnector(mediaSession)
        mediaSessionConnector.setPlaybackPreparer(musicPlaybackPreparer)
        mediaSessionConnector.setPlayer(exoPlayer)
        mediaSessionConnector.setQueueNavigator(MusicQueueNavigator())

        musicPlayerEventListener = MusicPlayerEventListener(this)
        exoPlayer.addListener(musicPlayerEventListener)
        musicNotificationManager.showNotification(exoPlayer)
    }

    private inner class MusicQueueNavigator: TimelineQueueNavigator(mediaSession) {
        override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat {
            return firebaseMusicSource.songs[windowIndex].description
        }
    }

    private fun preparePlayer(
        songs:List<MediaMetadataCompat>,
        itemToPlay:MediaMetadataCompat?,
        playNow: Boolean
    ){
        val curSongIndex = if(curPlayingSong == null) 0 else songs.indexOf(itemToPlay)

        exoPlayer.prepare()
        exoPlayer.addMediaSource(firebaseMusicSource.asMediaSource(dataSourceFactory))
        exoPlayer.seekTo(curSongIndex,0L)
        exoPlayer.playWhenReady =  playNow
        Log.d("MUSICSERVICE", "Player prepared ")
    }

    override fun onGetRoot(
        clientPackageName: String,
        clientUid: Int,
        rootHints: Bundle?
    ): BrowserRoot? {

        return BrowserRoot(MEDIA_ROOT_ID, null)

    }

    override fun onLoadChildren(
        parentId: String,
        result: Result<MutableList<MediaBrowserCompat.MediaItem>>
    ) {
        when(parentId){

            MEDIA_ROOT_ID -> {
                val resultSent:Boolean = firebaseMusicSource.whenReady { isInitialized ->
                    if(isInitialized){
                        result.sendResult(firebaseMusicSource.asMediaItem())
                        if(!isPlayerPrepared && firebaseMusicSource.songs.isEmpty()){
                            preparePlayer( firebaseMusicSource.songs, firebaseMusicSource.songs[0], false )
                            isPlayerPrepared = true
                            Log.d("MUSICSERVICE", "Player prepared during loadChildren ")
                        }
                    }else{
                        mediaSession.sendSessionEvent(NETWORK_ERROR, null)
                        result.sendResult(null)

                    }
                }

                if(!resultSent){
                    // wait for some time to get results ready and call the whole
                    // loading thing after some time
                    result.detach()
                }

            }

        }
    }

    override fun onDestroy() {
        super.onDestroy()
        serviceScope.cancel()

        exoPlayer.release()
        exoPlayer.removeListener(musicPlayerEventListener)
    }

    override fun onTaskRemoved(rootIntent: Intent?) {
        super.onTaskRemoved(rootIntent)
        exoPlayer.stop()
    }

}

Here is complete logcat stack trace : Stacktrace


问:
Curried function type inference
I have the following wrapper function:

```<code>declare function wrap<A extends any[]>(fn: (...args: A) => (x: number) => number)
</code>```

Instead of number there will be a generic T type, it's just a minimal example.

Now, when I use it and give types to outer arguments, TS incorrectly resolves A type. But if I leave at least one argument untyped, it resolves the type right.

```<code>wrap((a: number) => x => x) // Argument of type '(a: number) => (x: number) => number' is not assignable to parameter of type '() => (x: number) => number'.
wrap(a => x => x) // OK
wrap((a: number, b) => x => x) // OK
</code>```

However, if I use a little trick it will work again:

```<code>declare function id<T>(x: T): T

wrap((a: number) => id(x => x)) // OK
</code>```

Playground link

Why does this happen? Is it a TS limitation?

Title: Curried function type inference

Body:
I have the following wrapper function:

declare function wrap(fn: (...args: A) => (x: number) => number)

Instead of number there will be a generic T type, it's just a minimal example.

Now, when I use it and give types to outer arguments, TS incorrectly resolves A type. But if I leave at least one argument untyped, it resolves the type right.

wrap((a: number) => x => x) // Argument of type '(a: number) => (x: number) => number' is not assignable to parameter of type '() => (x: number) => number'.
wrap(a => x => x) // OK
wrap((a: number, b) => x => x) // OK

However, if I use a little trick it will work again:

declare function id<T>(x: T): T

wrap((a: number) => id(x => x)) // OK

Playground link

Why does this happen? Is it a TS limitation?


问:
Mongodb - java - retrieve distinct values of multiple fields
I have a collection with repeated values for columns in the documents.  I want to query for distinct values of multiple fields(System, subsystem) combination. Below is a sample data:

```<code>"System" : "training", "subsystem": "user", "ccid": "post", ret: 0
"System": "training", "subsystem": "user", "ccid": "test", ret: 1
"System": "training", "subsystem ":"cour", "ccid":"sample", ret:0
</code>```

I tried to use the aggregate from the other links, but it's not resolving in java for me. Could you please share me a sample java code using aggregate or map-reduce or any of the suitable methods

Body:
I have a collection with repeated values for columns in the documents.  I want to query for distinct values of multiple fields(System, subsystem) combination. Below is a sample data:

"System" : "training", "subsystem": "user", "ccid": "post", ret: 0
"System": "training", "subsystem": "user", "ccid": "test", ret: 1
"System": "training", "subsystem ":"cour", "ccid":"sample", ret:0

I tried to use the aggregate from the other links, but it's not resolving in java for me. Could you please share me a sample java code using aggregate or map-reduce or any of the suitable methods


问:
Duplicated files inside Android and iOS folders
I have all my files and folders duplicated inside my Android and iOS folders.

How can I get rid of them? I've tried 'flutter clean' and 'flutter pub get' but they don't get deleted.

Should I delete these extra files manually? is it safe this way.

Thank you in advance!

Edit:
Below is the output from 'flutter doctor -v':

```<code>    [✓] Flutter (Channel stable, 3.3.10, on macOS 12.6 21G115 darwin-arm, locale en-IQ)
                • Flutter version 3.3.10 on channel stable at /Users/salar/Development/flutter
                • Upstream repository https://github.com/flutter/flutter.git
                • Framework revision 135454af32 (2 weeks ago), 2022-12-15 07:36:55 -0800
                • Engine revision 3316dd8728
                • Dart version 2.18.6
                • DevTools version 2.15.0
            [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
                • Android SDK at /Users/salar/Library/Android/sdk
                • Platform android-33, build-tools 33.0.0
                • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
                • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
                • All Android licenses accepted.
        [✓] Xcode - develop for iOS and macOS (Xcode 14.1)
            • Xcode at /Applications/Xcode.app/Contents/Developer
            • Build 14B47b
            • CocoaPods version 1.11.3

    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

    [✓] Android Studio (version 2021.3)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
           https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
           https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

    [✓] VS Code (version 1.74.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.56.0

    [✓] Connected device (3 available)
        • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 13 (API 33) (emulator)
        • macOS (desktop)             • macos         • darwin-arm64   • macOS 12.6 21G115 darwin-arm
        • Chrome (web)                • chrome        • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
</code>```

Body:
I have all my files and folders duplicated inside my Android and iOS folders.

How can I get rid of them? I've tried 'flutter clean' and 'flutter pub get' but they don't get deleted.

Should I delete these extra files manually? is it safe this way.

Thank you in advance!

Edit:
Below is the output from 'flutter doctor -v':

    [✓] Flutter (Channel stable, 3.3.10, on macOS 12.6 21G115 darwin-arm, locale en-IQ)
                • Flutter version 3.3.10 on channel stable at /Users/salar/Development/flutter
                • Upstream repository https://github.com/flutter/flutter.git
                • Framework revision 135454af32 (2 weeks ago), 2022-12-15 07:36:55 -0800
                • Engine revision 3316dd8728
                • Dart version 2.18.6
                • DevTools version 2.15.0
            [✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0)
                • Android SDK at /Users/salar/Library/Android/sdk
                • Platform android-33, build-tools 33.0.0
                • Java binary at: /Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java
                • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)
                • All Android licenses accepted.
        [✓] Xcode - develop for iOS and macOS (Xcode 14.1)
            • Xcode at /Applications/Xcode.app/Contents/Developer
            • Build 14B47b
            • CocoaPods version 1.11.3

    [✓] Chrome - develop for the web
        • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

    [✓] Android Studio (version 2021.3)
        • Android Studio at /Applications/Android Studio.app/Contents
        • Flutter plugin can be installed from:
           https://plugins.jetbrains.com/plugin/9212-flutter
        • Dart plugin can be installed from:
           https://plugins.jetbrains.com/plugin/6351-dart
        • Java version OpenJDK Runtime Environment (build 11.0.13+0-b1751.21-8125866)

    [✓] VS Code (version 1.74.2)
        • VS Code at /Applications/Visual Studio Code.app/Contents
        • Flutter extension version 3.56.0

    [✓] Connected device (3 available)
        • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64  • Android 13 (API 33) (emulator)
        • macOS (desktop)             • macos         • darwin-arm64   • macOS 12.6 21G115 darwin-arm
        • Chrome (web)                • chrome        • web-javascript • Google Chrome 108.0.5359.124

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!


问:
Problem with variadic template classes implementation
I'm trying to create some kind of extremely simple event system in C++. I have these files:

Events.h

```<code>#pragma once

#include <vector>
#include <functional>

using namespace std;

template <typename... Args>
class Event
{
public:
   typedef function<void(Args...)> HandlerFunc;

   void Add(HandlerFunc handler);
   void operator()(Args... params);

private:
   vector<HandlerFunc>* handlers = new vector<HandlerFunc>;
};
</code>```

Events.cpp

```<code>#include "Events.h"

template <typename... Args>
void Event<Args...>::Add(HandlerFunc handler)
{
    handlers->push_back(handler);
}

template <typename... Args>
void Event<Args...>::operator()(Args... params)
{
    for (const auto& handler : handlers)
    {
        handler(params...);
    }
}
</code>```

main.cpp

```<code>#include <iostream>
#include "Events.h"

using namespace std;

void handler(int x)
{
    cout << "HANDLER: " << x;
}

int main()
{
    Event<int> evt;
    evt.Add(handler);
    evt(69);

    return 0;
}
</code>```

But I get the following errors:

LNK2001 unresolved extern symbol "public: void __cdecl Event::operator()(int)" (??R?$Event@H@@QEAAXH@Z)

LNK2001 unresolved extern symbol "public: void __cdecl Event::Add(class std::function<void __cdecl(int)>)" (?Add@?$Event@H@@QEAAXV?$function@$$A6AXH@Z@std@@@Z)

LNK1120 2 unresolved externs

Why is that?

Body:
I'm trying to create some kind of extremely simple event system in C++. I have these files:

Events.h

#pragma once

#include <vector>
#include <functional>

using namespace std;

template <typename... Args>
class Event
{
public:
   typedef function<void(Args...)> HandlerFunc;

   void Add(HandlerFunc handler);
   void operator()(Args... params);

private:
   vector<HandlerFunc>* handlers = new vector<HandlerFunc>;
};

Events.cpp

#include "Events.h"

template <typename... Args>
void Event<Args...>::Add(HandlerFunc handler)
{
    handlers->push_back(handler);
}

template <typename... Args>
void Event<Args...>::operator()(Args... params)
{
    for (const auto& handler : handlers)
    {
        handler(params...);
    }
}

main.cpp

#include <iostream>
#include "Events.h"

using namespace std;

void handler(int x)
{
    cout << "HANDLER: " << x;
}

int main()
{
    Event<int> evt;
    evt.Add(handler);
    evt(69);

    return 0;
}

But I get the following errors:

LNK2001 unresolved extern symbol "public: void __cdecl Event::operator()(int)" (??R?$Event@H@@QEAAXH@Z)

LNK2001 unresolved extern symbol "public: void __cdecl Event::Add(class std::function<void __cdecl(int)>)" (?Add@?$Event@H@@QEAAXV?$function@$$A6AXH@Z@std@@@Z)

LNK1120 2 unresolved externs

Why is that?


问:
i am trying to plot a line chart but it shows area chart everytime i plot?
```<code>#Test for staionarity
def test_stationarity(timeseries):
    #Determing rolling statistics
    rolmean = timeseries.rolling(12).mean()
    rolstd = timeseries.rolling(12).std()
    #Plot rolling statistics:
    plt.plot(timeseries, color='blue',label='Original')
    plt.plot(rolmean, color='red', label='Rolling Mean')
    plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean and Standard Deviation')
    plt.show(block=False)  #problem lies in this part

    print("Results of dickey fuller test")
    adft = adfuller(timeseries,autolag='AIC')
    # output for dft will give us without defining what the values are.
    #hence we manually write what values does it explains using a for loop
    output = pd.Series(adft[0:4],index=['Test Statistics','p-value','No. of lags used','Number of observations used'])
    for key,values in adft[4].items():
        output['critical value (%s)'%key] =  values
    print(output)

test_stationarity(df_close)
</code>```

this is my code and idk how come it is showing area chart...

what should i add more, it is showing different on others...

this one is my graph

Body:
#Test for staionarity
def test_stationarity(timeseries):
    #Determing rolling statistics
    rolmean = timeseries.rolling(12).mean()
    rolstd = timeseries.rolling(12).std()
    #Plot rolling statistics:
    plt.plot(timeseries, color='blue',label='Original')
    plt.plot(rolmean, color='red', label='Rolling Mean')
    plt.plot(rolstd, color='black', label = 'Rolling Std')
    plt.legend(loc='best')
    plt.title('Rolling Mean and Standard Deviation')
    plt.show(block=False)  #problem lies in this part

    print("Results of dickey fuller test")
    adft = adfuller(timeseries,autolag='AIC')
    # output for dft will give us without defining what the values are.
    #hence we manually write what values does it explains using a for loop
    output = pd.Series(adft[0:4],index=['Test Statistics','p-value','No. of lags used','Number of observations used'])
    for key,values in adft[4].items():
        output['critical value (%s)'%key] =  values
    print(output)

test_stationarity(df_close)

this is my code and idk how come it is showing area chart...

what should i add more, it is showing different on others...

this one is my graph


问:
Feature file not running from Spring boot
This  my Cucumber Runner file

```<code>import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)

@CucumberOptions(features = "classpath:features",
    plugin = {"com.example"},
    glue = {"com.example.test"}
)

public class CucumberTest {
}

@SpringBootTest

@CucumberContextConfiguration

@ContextConfiguration(classes = test.class, loader = SpringBootContextLoader.class)
public class CucumberSpringContextConfiguration extends TestValidations {

private static final Logger log =
LoggerFactory.getLogger(CucumberSpringContextConfiguration.class);

@Before
public void setUp() {
    log.info(" Spring Context Initialized For Executing Cucumber Tests");
}

}

My feature file is
@Dummy
Scenario Outline: ISSUER : Verify test.
Given User construct the  payload
And User publish event
Examples:
| SourcePayload | TargetPayload | DisputeEvent |
</code>```

When i run this from intellij I get below error

```<code>C:\Java\jdk8_151\bin\java.exeagentlib:jdwp=transport=dt_socket,address=127.0.0.1:51079,suspend=y,server=n -Dspring.profiles.active=xyz -Dcucumber.filter.tags=@Dummy
</code>```

Connected to the target VM, address: '127.0.0.1:51079', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:51079', transport: 'socket'

Process finished with exit code 0

My test is not run

Same framework runs with another feature file

Body:
This  my Cucumber Runner file

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)

@CucumberOptions(features = "classpath:features",
    plugin = {"com.example"},
    glue = {"com.example.test"}
)

public class CucumberTest {
}

@SpringBootTest

@CucumberContextConfiguration

@ContextConfiguration(classes = test.class, loader = SpringBootContextLoader.class)
public class CucumberSpringContextConfiguration extends TestValidations {

private static final Logger log =
LoggerFactory.getLogger(CucumberSpringContextConfiguration.class);

@Before
public void setUp() {
    log.info(" Spring Context Initialized For Executing Cucumber Tests");
}

}

My feature file is
@Dummy
Scenario Outline: ISSUER : Verify test.
Given User construct the  payload
And User publish event
Examples:
| SourcePayload | TargetPayload | DisputeEvent |

When i run this from intellij I get below error

C:\Java\jdk8_151\bin\java.exeagentlib:jdwp=transport=dt_socket,address=127.0.0.1:51079,suspend=y,server=n -Dspring.profiles.active=xyz -Dcucumber.filter.tags=@Dummy

Connected to the target VM, address: '127.0.0.1:51079', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:51079', transport: 'socket'

Process finished with exit code 0

My test is not run

Same framework runs with another feature file


问:
Cutting and placing text based on time stamps in a srt file
I had an srt file, and to be able to translate it using DeepL, I gathered the fragmented sentences in one line. Now I want to do the opposite of this process. In other words, I want to randomly divide the sentence in a single line into multiple lines as I have exemplified below.

I tried with the code block below but I couldn't write the necessary codes to separate the text. What I want to do is to split the long text into chunks and distribute it to the empty parts as below, if possible, depending on how long the timestamps in the srt file have. If this is not possible, I can also divide the text into equal parts.

This is the file that I have:

```<code>1
00:00:00,000 --> 00:00:13,680
Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.

2
00:00:13,680 --> 00:00:14,680
Evet.

3
00:00:14,680 --> 00:00:20,080
Romain'in direkt olduğunu bildireceğim.

4
00:00:20,080 --> 00:00:22,720
Devam edin ve canlı yayını açın.

5
00:00:22,720 --> 00:00:25,640
Evet, seni duyabiliyoruz.

6
00:00:25,640 --> 00:00:26,640
Güzel.

7
00:00:26,640 --> 00:00:28,480
Hızlı bir sunum yapacağım, herkesin gelmesini bekleyeceğim.

8
00:00:28,480 --> 00:00:40,640
Merhaba Raphaël, merhaba Ismaël, merhaba Jean-Marc, herkese merhaba, merhaba Clément, merhaba Thierry.

9
00:00:40,640 --> 00:00:41,640

10
00:00:41,640 --> 00:00:42,640
Herkese merhaba.

11
00:00:42,640 --> 00:00:44,640
Normalde bizi duyup duymadıklarını bilmiyorum.

12
00:00:44,640 --> 00:00:45,640
Evet, artık seni duyabiliyorlar.

13
00:00:45,640 --> 00:00:46,640
Bekleyeceğiz.

14
00:00:46,640 --> 00:00:51,480
Hızlı bir şekilde çalışmasını beklerken bizi bile filme alabilirsiniz, sadece bekleyin.

15
00:00:51,480 --> 00:00:53,360
Seni filme alacağım.

16
00:00:53,360 --> 00:00:57,520
Pekala çocuklar, sadece küçük bir açıklama yapmak için bugün iki konuşmacımız olacak, kafamı keseceğim, CP Dropshipping olacak, sanırım onu tanıyorsunuz, bir YouTube kanalı var, Çok güzel bir Balenciaga tişörtü olan bir Facebook hesabı var ve ayrıca Jérémy, yani oldukça ağır olan iki Dropshipper'ımız var ve Jérémy her şeyi doğru yapmaya başlayan, oldukça fazla para kazanmaya başlayan ve sanırım yakında Malta'ya gelip yaşayacak olan bir Discord yöneticisi.

17
00:00:57,520 --> 00:01:02,560

18
00:01:02,560 --> 00:01:06,320

19
00:01:06,320 --> 00:01:11,520

20
00:01:11,520 --> 00:01:16,960

21
00:01:16,960 --> 00:01:21,520

22
00:01:21,520 --> 00:01:22,520

23
00:01:22,520 --> 00:01:25,520
Daha önce orada uçak videolarını izlemiştik.

24
00:01:25,520 --> 00:01:28,520
Bir hafta sonra geri getirmem gerekecek.

25
00:01:28,520 --> 00:01:30,320
Kahretsin, yanılmışım.
</code>```

And I want this instead:

```<code>1
00:00:00,000 --> 00:00:13,680
Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.

2
00:00:13,680 --> 00:00:14,680
Evet.

3
00:00:14,680 --> 00:00:20,080
Romain'in direkt olduğunu bildireceğim.

4
00:00:20,080 --> 00:00:22,720
Devam edin ve canlı yayını açın.

5
00:00:22,720 --> 00:00:25,640
Evet, seni duyabiliyoruz.

6
00:00:25,640 --> 00:00:26,640
Güzel.

7
00:00:26,640 --> 00:00:28,480
Hızlı bir sunum yapacağım, herkesin gelmesini bekleyeceğim.

8
00:00:28,480 --> 00:00:40,640
Merhaba Raphaël, merhaba Ismaël, merhaba Jean-Marc, herkese merhaba, merhaba Clément,

9
00:00:40,640 --> 00:00:41,640
merhaba Thierry.

10
00:00:41,640 --> 00:00:42,640
Herkese merhaba.

11
00:00:42,640 --> 00:00:44,640
Normalde bizi duyup duymadıklarını bilmiyorum.

12
00:00:44,640 --> 00:00:45,640
Evet, artık seni duyabiliyorlar.

13
00:00:45,640 --> 00:00:46,640
Bekleyeceğiz.

14
00:00:46,640 --> 00:00:51,480
Hızlı bir şekilde çalışmasını beklerken bizi bile filme alabilirsiniz, sadece bekleyin.

15
00:00:51,480 --> 00:00:53,360
Seni filme alacağım.

16
00:00:53,360 --> 00:00:57,520
Pekala çocuklar, sadece küçük bir açıklama yapmak için bugün iki konuşmacımız olacak,

17
00:00:57,520 --> 00:01:02,560
kafamı keseceğim, CP Dropshipping olacak, sanırım onu tanıyorsunuz,

18
00:01:02,560 --> 00:01:06,320
bir YouTube kanalı var, Çok güzel bir Balenciaga tişörtü olan bir Facebook hesabı var

19
00:01:06,320 --> 00:01:11,520
ve ayrıca Jérémy, yani oldukça ağır olan iki Dropshipper'ımız var ve Jérémy her şeyi doğru yapmaya başlayan,

20
00:01:11,520 --> 00:01:16,960
oldukça fazla para kazanmaya başlayan

21
00:01:16,960 --> 00:01:21,520
ve sanırım yakında Malta'ya gelip yaşayacak olan

22
00:01:21,520 --> 00:01:22,520
bir Discord yöneticisi.

23
00:01:22,520 --> 00:01:25,520
Daha önce orada uçak videolarını izlemiştik.

24
00:01:25,520 --> 00:01:28,520
Bir hafta sonra geri getirmem gerekecek.

25
00:01:28,520 --> 00:01:30,320
Kahretsin, yanılmışım.
</code>```
```<code>with open('original.srt') as org_file:
    text = org_file.read()
segment_list = text.split('\n\n')

def allocate_long_text():
    #for this part I don't know how to split text into parts and put them into different lines.

processed_segment_list = []
tmp_segment_list = []
dirty = False
for segment in segment_list:
    element_list = segment.split('\n')
    if len(element_list) == 3: # for example element_list = ['1', '00:00:00,000 --> 00:00:13,680', 'Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.']
        if dirty:
            processed_segment_list.extend(allocate_long_text(tmp_segment_list))
            dirty = False
            tmp_segment_list = []
        if tmp_segment_list:
            processed_segment_list.append(tmp_segment_list.pop(0))
        tmp_segment_list.append(segment)
    elif len(element_list) == 2: # for example element_list = ['9', '00:00:40,640 --> 00:00:41,640']
        tmp_segment_list.append(segment)
        dirty = True
    else:
        print(segment)
        raise ValueError('Something went wrong...')

with open('processed.srt', 'w') as proc_file:
    proc_file.write('\n\n'.join(processed_segment_list))
</code>```

Body:
I had an srt file, and to be able to translate it using DeepL, I gathered the fragmented sentences in one line. Now I want to do the opposite of this process. In other words, I want to randomly divide the sentence in a single line into multiple lines as I have exemplified below.

I tried with the code block below but I couldn't write the necessary codes to separate the text. What I want to do is to split the long text into chunks and distribute it to the empty parts as below, if possible, depending on how long the timestamps in the srt file have. If this is not possible, I can also divide the text into equal parts.

This is the file that I have:

1
00:00:00,000 --> 00:00:13,680
Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.

2
00:00:13,680 --> 00:00:14,680
Evet.

3
00:00:14,680 --> 00:00:20,080
Romain'in direkt olduğunu bildireceğim.

4
00:00:20,080 --> 00:00:22,720
Devam edin ve canlı yayını açın.

5
00:00:22,720 --> 00:00:25,640
Evet, seni duyabiliyoruz.

6
00:00:25,640 --> 00:00:26,640
Güzel.

7
00:00:26,640 --> 00:00:28,480
Hızlı bir sunum yapacağım, herkesin gelmesini bekleyeceğim.

8
00:00:28,480 --> 00:00:40,640
Merhaba Raphaël, merhaba Ismaël, merhaba Jean-Marc, herkese merhaba, merhaba Clément, merhaba Thierry.

9
00:00:40,640 --> 00:00:41,640

10
00:00:41,640 --> 00:00:42,640
Herkese merhaba.

11
00:00:42,640 --> 00:00:44,640
Normalde bizi duyup duymadıklarını bilmiyorum.

12
00:00:44,640 --> 00:00:45,640
Evet, artık seni duyabiliyorlar.

13
00:00:45,640 --> 00:00:46,640
Bekleyeceğiz.

14
00:00:46,640 --> 00:00:51,480
Hızlı bir şekilde çalışmasını beklerken bizi bile filme alabilirsiniz, sadece bekleyin.

15
00:00:51,480 --> 00:00:53,360
Seni filme alacağım.

16
00:00:53,360 --> 00:00:57,520
Pekala çocuklar, sadece küçük bir açıklama yapmak için bugün iki konuşmacımız olacak, kafamı keseceğim, CP Dropshipping olacak, sanırım onu tanıyorsunuz, bir YouTube kanalı var, Çok güzel bir Balenciaga tişörtü olan bir Facebook hesabı var ve ayrıca Jérémy, yani oldukça ağır olan iki Dropshipper'ımız var ve Jérémy her şeyi doğru yapmaya başlayan, oldukça fazla para kazanmaya başlayan ve sanırım yakında Malta'ya gelip yaşayacak olan bir Discord yöneticisi.

17
00:00:57,520 --> 00:01:02,560

18
00:01:02,560 --> 00:01:06,320

19
00:01:06,320 --> 00:01:11,520

20
00:01:11,520 --> 00:01:16,960

21
00:01:16,960 --> 00:01:21,520

22
00:01:21,520 --> 00:01:22,520

23
00:01:22,520 --> 00:01:25,520
Daha önce orada uçak videolarını izlemiştik.

24
00:01:25,520 --> 00:01:28,520
Bir hafta sonra geri getirmem gerekecek.

25
00:01:28,520 --> 00:01:30,320
Kahretsin, yanılmışım.

And I want this instead:

1
00:00:00,000 --> 00:00:13,680
Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.

2
00:00:13,680 --> 00:00:14,680
Evet.

3
00:00:14,680 --> 00:00:20,080
Romain'in direkt olduğunu bildireceğim.

4
00:00:20,080 --> 00:00:22,720
Devam edin ve canlı yayını açın.

5
00:00:22,720 --> 00:00:25,640
Evet, seni duyabiliyoruz.

6
00:00:25,640 --> 00:00:26,640
Güzel.

7
00:00:26,640 --> 00:00:28,480
Hızlı bir sunum yapacağım, herkesin gelmesini bekleyeceğim.

8
00:00:28,480 --> 00:00:40,640
Merhaba Raphaël, merhaba Ismaël, merhaba Jean-Marc, herkese merhaba, merhaba Clément,

9
00:00:40,640 --> 00:00:41,640
merhaba Thierry.

10
00:00:41,640 --> 00:00:42,640
Herkese merhaba.

11
00:00:42,640 --> 00:00:44,640
Normalde bizi duyup duymadıklarını bilmiyorum.

12
00:00:44,640 --> 00:00:45,640
Evet, artık seni duyabiliyorlar.

13
00:00:45,640 --> 00:00:46,640
Bekleyeceğiz.

14
00:00:46,640 --> 00:00:51,480
Hızlı bir şekilde çalışmasını beklerken bizi bile filme alabilirsiniz, sadece bekleyin.

15
00:00:51,480 --> 00:00:53,360
Seni filme alacağım.

16
00:00:53,360 --> 00:00:57,520
Pekala çocuklar, sadece küçük bir açıklama yapmak için bugün iki konuşmacımız olacak,

17
00:00:57,520 --> 00:01:02,560
kafamı keseceğim, CP Dropshipping olacak, sanırım onu tanıyorsunuz,

18
00:01:02,560 --> 00:01:06,320
bir YouTube kanalı var, Çok güzel bir Balenciaga tişörtü olan bir Facebook hesabı var

19
00:01:06,320 --> 00:01:11,520
ve ayrıca Jérémy, yani oldukça ağır olan iki Dropshipper'ımız var ve Jérémy her şeyi doğru yapmaya başlayan,

20
00:01:11,520 --> 00:01:16,960
oldukça fazla para kazanmaya başlayan

21
00:01:16,960 --> 00:01:21,520
ve sanırım yakında Malta'ya gelip yaşayacak olan

22
00:01:21,520 --> 00:01:22,520
bir Discord yöneticisi.

23
00:01:22,520 --> 00:01:25,520
Daha önce orada uçak videolarını izlemiştik.

24
00:01:25,520 --> 00:01:28,520
Bir hafta sonra geri getirmem gerekecek.

25
00:01:28,520 --> 00:01:30,320
Kahretsin, yanılmışım.

with open('original.srt') as org_file:
    text = org_file.read()
segment_list = text.split('\n\n')

def allocate_long_text():
    #for this part I don't know how to split text into parts and put them into different lines.

processed_segment_list = []
tmp_segment_list = []
dirty = False
for segment in segment_list:
    element_list = segment.split('\n')
    if len(element_list) == 3: # for example element_list = ['1', '00:00:00,000 --> 00:00:13,680', 'Otele canlı yayın koyacağım, böylece mesajlara ve diğer şeylere bakabileceğiz.']
        if dirty:
            processed_segment_list.extend(allocate_long_text(tmp_segment_list))
            dirty = False
            tmp_segment_list = []
        if tmp_segment_list:
            processed_segment_list.append(tmp_segment_list.pop(0))
        tmp_segment_list.append(segment)
    elif len(element_list) == 2: # for example element_list = ['9', '00:00:40,640 --> 00:00:41,640']
        tmp_segment_list.append(segment)
        dirty = True
    else:
        print(segment)
        raise ValueError('Something went wrong...')

with open('processed.srt', 'w') as proc_file:
    proc_file.write('\n\n'.join(processed_segment_list))


问:
What are the ways to Call an Input box to fill data in it using selenium , if call by i.d fails to identify the box?
`

```<code>for data in form_data:
    driver.find_element_by_id('name').send_keys(data['name'])
    driver.find_element_by_id('email').send_keys(data['email'])
    driver.find_element_by_id('message').send_keys(data['message'])
    driver.find_element_by_id('submit').click()
</code>```

`
In the above code, It is unable to get the input box from the given Id, Although Id is mentioned while inspecting the input Box.

I read about xpath but unable to use it to get the input box.I want to select the input box and send data to fill the form and submit it

Body:
`

for data in form_data:
    driver.find_element_by_id('name').send_keys(data['name'])
    driver.find_element_by_id('email').send_keys(data['email'])
    driver.find_element_by_id('message').send_keys(data['message'])
    driver.find_element_by_id('submit').click()

`
In the above code, It is unable to get the input box from the given Id, Although Id is mentioned while inspecting the input Box.

I read about xpath but unable to use it to get the input box.I want to select the input box and send data to fill the form and submit it