问:
Calling wtforms validations conditionally
I am writing a login page using wtforms .The fields are username and password.Below are the two validations defined for two fields.Is there a way to stop the execution of validation function on password field if validation method on username raises exception

```<code>    def validate_username(self, field):
    # Check if not None for that username!
    print('Inside check_username')
    if User.query.filter_by(username=field.data).first() is None:
        raise ValidationError(f'Sorry username : {field.data} is not registered!')

    def validate_password(self, field):
       # Below is not the actual code.This method will contain code to check of valid password.
       raise ValidationError(f'Sorry username : {field.data} is not registered!')
</code>```

What is happening right now is both of the above methods are been called which is expected but I don't want to check for password if the username doesn't exist

答:
You cannot stop wtforms for trying to validate each field.

I suggest you simply override validate:

```<code>def validate(self):
    if not super().validate():
        return False

    if User.query.filter_by(username=self.username.data).first() is None:
        self.errors["username"] = f'Sorry username : {self.username.data} is not registered!'
        return False

    if not check_that_password():
        self.errors["password"] = f"Bad password for user {self.username.data}"
        return False

    return True
</code>```

Body:
I am writing a login page using wtforms .The fields are username and password.Below are the two validations defined for two fields.Is there a way to stop the execution of validation function on password field if validation method on username raises exception

    def validate_username(self, field):
    # Check if not None for that username!
    print('Inside check_username')
    if User.query.filter_by(username=field.data).first() is None:
        raise ValidationError(f'Sorry username : {field.data} is not registered!')

    def validate_password(self, field):
       # Below is not the actual code.This method will contain code to check of valid password.
       raise ValidationError(f'Sorry username : {field.data} is not registered!')

What is happening right now is both of the above methods are been called which is expected but I don't want to check for password if the username doesn't exist

Body:
You cannot stop wtforms for trying to validate each field.

I suggest you simply override validate:

def validate(self):
    if not super().validate():
        return False

    if User.query.filter_by(username=self.username.data).first() is None:
        self.errors["username"] = f'Sorry username : {self.username.data} is not registered!'
        return False

    if not check_that_password():
        self.errors["password"] = f"Bad password for user {self.username.data}"
        return False

    return True


来源: stackexchange

问:
How to initialize mutli dimentional list in Python
I am a beginner in Python. I am having difficulty creating multidimensional array or list.

I want to do two things:

a) Create a list, b) Intialize the list

For example, if D is list then:

The total matrix is till D[8] [7] but I need to initialize only below
  values to  0

```<code>D[0][0] = 0

D[0][1] = 0
D[0][2] = 0
D[0][3] = 0
D[0][4] = 0

D[1][0] = 0
D[2][0] = 0
D[3][0] = 0
D[4][0] = 0
D[5][0] = 0
</code>```

I tried following but its not working:

```<code>import numpy
Matrix = numpy.zeros((len(A) + 1, len(B) + 1))
    for i in range(len(B) + 1):
        Matrix[0][i] = i

    for i in range(len(A) + 1):
        Matrix[i][0] = i
</code>```

But it gives output something like below which I don't want:

```<code>[[0. 1. 2. 3. 4. 5. 6. 7. 8.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [2. 0. 0. 0. 0. 0. 0. 0. 0.]
 [3. 0. 0. 0. 0. 0. 0. 0. 0.]
 [4. 0. 0. 0. 0. 0. 0. 0. 0.]
 [5. 0. 0. 0. 0. 0. 0. 0. 0.]
 [6. 0. 0. 0. 0. 0. 0. 0. 0.]
 [7. 0. 0. 0. 0. 0. 0. 0. 0.]]
</code>```

答:
if you are using numpy then You can do your both work together with "shape" feature as it define and initialise with 0 as well

```<code>import numpy
a = numpy.zeros(shape=(8,7))
</code>```

or for the general case

```<code>a = numpy.zeros(shape=(i,j))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am a beginner in Python. I am having difficulty creating multidimensional array or list.

I want to do two things:

a) Create a list, b) Intialize the list

For example, if D is list then:

The total matrix is till D[8] [7] but I need to initialize only below
  values to  0

D[0][0] = 0

D[0][1] = 0
D[0][2] = 0
D[0][3] = 0
D[0][4] = 0

D[1][0] = 0
D[2][0] = 0
D[3][0] = 0
D[4][0] = 0
D[5][0] = 0

I tried following but its not working:

import numpy
Matrix = numpy.zeros((len(A) + 1, len(B) + 1))
    for i in range(len(B) + 1):
        Matrix[0][i] = i

    for i in range(len(A) + 1):
        Matrix[i][0] = i

But it gives output something like below which I don't want:

[[0. 1. 2. 3. 4. 5. 6. 7. 8.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [2. 0. 0. 0. 0. 0. 0. 0. 0.]
 [3. 0. 0. 0. 0. 0. 0. 0. 0.]
 [4. 0. 0. 0. 0. 0. 0. 0. 0.]
 [5. 0. 0. 0. 0. 0. 0. 0. 0.]
 [6. 0. 0. 0. 0. 0. 0. 0. 0.]
 [7. 0. 0. 0. 0. 0. 0. 0. 0.]]

Body:
if you are using numpy then You can do your both work together with "shape" feature as it define and initialise with 0 as well

import numpy
a = numpy.zeros(shape=(8,7))

or for the general case

a = numpy.zeros(shape=(i,j))


问:
How to synchronise multiple threads?
How would you synchronise multiple threads to be at a certain place in their code at a particular time?

I am not looking for WaitAll, await etc. As in the example code, the threads do not return, only one thread is created per worker.

I have made this monster...
It works for simple and slow cases, but there is a race condition: when a fast thread locks _sync before the synchroniser. As a result sometimes that thread will execute more than once per cycle and break any assumptions of what is ready for use by other threads.

```<code>static readonly Stopwatch timer = new Stopwatch();

static readonly object _locker1 = new object();
static readonly object _locker2 = new object();
...
static readonly object _sync = new object();

static void Main()
{
    Task.Run(Synchroniser);
    Task.Run(DoWork1);
    Task.Run(DoWork2);
    ...
}

static void Synchroniser()
{
    while (true)
    {
        lock (_sync)
        {
            timer.Restart();
            while (timer.ElapseMilliseconds < 16) ;
            lock (_locker1) ;
            lock (_locker2) ;
            ...
        }
    }
}

static void DoWork1()
{
    while (true)
    {
        lock (_locker1)
        {
            //all worker threads continue from here at the same time
            ...
        }
        lock (_sync) ;
    }
}
...
</code>```

答:
It's hard to tell what kind of behavior you're after, but I think this is what you're trying to achieve.  Run it and see how it behaves...

The code makes use of the ManualResetEvent class and the WaitAll function:

```<code>class Program
{

    static readonly ManualResetEvent startWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent worker1 = new ManualResetEvent(false);
    static readonly ManualResetEvent worker2 = new ManualResetEvent(false);
    static readonly Random R = new Random();

    static void Main()
    {
        Task.Run(new Action(Synchroniser));
        Task.Run(new Action(DoWork1));
        Task.Run(new Action(DoWork2));

        Console.ReadLine(); // keep program from closing
    }

    static void Synchroniser()
    {
        ManualResetEvent[] workers = new ManualResetEvent[] { worker1, worker2 };
        while (true)
        {
            Console.WriteLine("Pausing...");
            Thread.Sleep(5000); // long pause so we can see what is happening

            Console.WriteLine("Signalling workers.");
            startWorkers.Set(); // allow workers to run
            startWorkers.Reset(); // workers can only run ONCE until we set again

            Console.WriteLine("Waiting for all workers to be done...");
            WaitHandle.WaitAll(workers); // wait for all the workers to be done
            Console.WriteLine("All workers are done.");
            worker1.Reset();
            worker2.Reset();
        }
    }

    static void DoWork1()
    {
        while (true)
        {
            Console.WriteLine("Worker1 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker1 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work
            Console.WriteLine("Worker1 done.");

            worker1.Set(); // let Synchroniser know we are done
        }
    }

    static void DoWork2()
    {
        while (true)
        {
            Console.WriteLine("Worker2 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker2 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work
            Console.WriteLine("Worker2 done.");

            worker2.Set(); // let Synchroniser know we are done
        }
    }

}
</code>```

Sample output:

```<code>Worker1 waiting.
Pausing...
Worker2 waiting.
Signalling workers.
Waiting for all workers to be done...
Worker2 processing...
Worker1 processing...
Worker1 done.
Worker1 waiting.
Worker2 done.
Worker2 waiting.
All workers are done.
Pausing...
Signalling workers.
Waiting for all workers to be done...
Worker2 processing...
Worker1 processing...
Worker1 done.
Worker1 waiting.
Worker2 done.
Worker2 waiting.
All workers are done.
Pausing...
</code>```

If somehow the worker thread finishes before startWorkers.Reset();

I think it's unlikely to happen, but here's a two gate system that should prevent that from happening.  After signalling that the thread is done, it will sit and wait until all threads have completed before being allowed to continue:

```<code>class Program
{

    static readonly ManualResetEvent startWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent releaseWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent worker1 = new ManualResetEvent(false);
    static readonly ManualResetEvent worker2 = new ManualResetEvent(false);
    static readonly Random R = new Random();

    static void Main()
    {
        Task.Run(new Action(Synchroniser));
        Task.Run(new Action(DoWork1));
        Task.Run(new Action(DoWork2));

        Console.ReadLine(); // keep program from closing
    }

    static void Synchroniser()
    {
        ManualResetEvent[] workers = new ManualResetEvent[] { worker1, worker2 };
        while (true)
        {
            Console.WriteLine("Pausing...");
            Thread.Sleep(5000); // long pause so we can see what is happening

            Console.WriteLine("Signalling workers.");
            startWorkers.Set(); // allow workers to run, automatically reset
            startWorkers.Reset();

            Console.WriteLine("Waiting for all workers to be done...");
            WaitHandle.WaitAll(workers); // wait for all the workers to be done
            Console.WriteLine("All workers are done.");

            Console.WriteLine("Resetting workers...");
            // Reset all workers
            foreach(ManualResetEvent mre in workers)
            {
                mre.Reset();
            }

            // release the workers to wait at the top of their loops
            Console.WriteLine("Releasing workers...");
            releaseWorkers.Set();
            releaseWorkers.Reset();
        }
    }

    static void DoWork1()
    {
        while (true)
        {
            Console.WriteLine("Worker1 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker1 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work

            Console.WriteLine("Worker1 done.");
            worker1.Set(); // let Synchroniser know we are done

            Console.WriteLine("Worker1 waiting for release...");
            releaseWorkers.WaitOne(); // wait for all clear
        }
    }

    static void DoWork2()
    {
        while (true)
        {
            Console.WriteLine("Worker2 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker2 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work

            Console.WriteLine("Worker2 done.");
            worker2.Set(); // let Synchroniser know we are done

            Console.WriteLine("Worker2 waiting for release...");
            releaseWorkers.WaitOne(); // wait for all clear
        }
    }

}
</code>```

Title: How to synchronise multiple threads?

Body:
How would you synchronise multiple threads to be at a certain place in their code at a particular time?

I am not looking for WaitAll, await etc. As in the example code, the threads do not return, only one thread is created per worker.

I have made this monster...
It works for simple and slow cases, but there is a race condition: when a fast thread locks _sync before the synchroniser. As a result sometimes that thread will execute more than once per cycle and break any assumptions of what is ready for use by other threads.

static readonly Stopwatch timer = new Stopwatch();

static readonly object _locker1 = new object();
static readonly object _locker2 = new object();
...
static readonly object _sync = new object();

static void Main()
{
    Task.Run(Synchroniser);
    Task.Run(DoWork1);
    Task.Run(DoWork2);
    ...
}

static void Synchroniser()
{
    while (true)
    {
        lock (_sync)
        {
            timer.Restart();
            while (timer.ElapseMilliseconds < 16) ;
            lock (_locker1) ;
            lock (_locker2) ;
            ...
        }
    }
}

static void DoWork1()
{
    while (true)
    {
        lock (_locker1)
        {
            //all worker threads continue from here at the same time
            ...
        }
        lock (_sync) ;
    }
}
...

Body:
It's hard to tell what kind of behavior you're after, but I think this is what you're trying to achieve.  Run it and see how it behaves...

The code makes use of the ManualResetEvent class and the WaitAll function:

class Program
{

    static readonly ManualResetEvent startWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent worker1 = new ManualResetEvent(false);
    static readonly ManualResetEvent worker2 = new ManualResetEvent(false);
    static readonly Random R = new Random();

    static void Main()
    {
        Task.Run(new Action(Synchroniser));
        Task.Run(new Action(DoWork1));
        Task.Run(new Action(DoWork2));

        Console.ReadLine(); // keep program from closing
    }

    static void Synchroniser()
    {
        ManualResetEvent[] workers = new ManualResetEvent[] { worker1, worker2 };
        while (true)
        {
            Console.WriteLine("Pausing...");
            Thread.Sleep(5000); // long pause so we can see what is happening

            Console.WriteLine("Signalling workers.");
            startWorkers.Set(); // allow workers to run
            startWorkers.Reset(); // workers can only run ONCE until we set again

            Console.WriteLine("Waiting for all workers to be done...");
            WaitHandle.WaitAll(workers); // wait for all the workers to be done
            Console.WriteLine("All workers are done.");
            worker1.Reset();
            worker2.Reset();
        }
    }

    static void DoWork1()
    {
        while (true)
        {
            Console.WriteLine("Worker1 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker1 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work
            Console.WriteLine("Worker1 done.");

            worker1.Set(); // let Synchroniser know we are done
        }
    }

    static void DoWork2()
    {
        while (true)
        {
            Console.WriteLine("Worker2 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker2 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work
            Console.WriteLine("Worker2 done.");

            worker2.Set(); // let Synchroniser know we are done
        }
    }

}

Sample output:

Worker1 waiting.
Pausing...
Worker2 waiting.
Signalling workers.
Waiting for all workers to be done...
Worker2 processing...
Worker1 processing...
Worker1 done.
Worker1 waiting.
Worker2 done.
Worker2 waiting.
All workers are done.
Pausing...
Signalling workers.
Waiting for all workers to be done...
Worker2 processing...
Worker1 processing...
Worker1 done.
Worker1 waiting.
Worker2 done.
Worker2 waiting.
All workers are done.
Pausing...

If somehow the worker thread finishes before startWorkers.Reset();

I think it's unlikely to happen, but here's a two gate system that should prevent that from happening.  After signalling that the thread is done, it will sit and wait until all threads have completed before being allowed to continue:

class Program
{

    static readonly ManualResetEvent startWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent releaseWorkers = new ManualResetEvent(false); // workers initially blocked
    static readonly ManualResetEvent worker1 = new ManualResetEvent(false);
    static readonly ManualResetEvent worker2 = new ManualResetEvent(false);
    static readonly Random R = new Random();

    static void Main()
    {
        Task.Run(new Action(Synchroniser));
        Task.Run(new Action(DoWork1));
        Task.Run(new Action(DoWork2));

        Console.ReadLine(); // keep program from closing
    }

    static void Synchroniser()
    {
        ManualResetEvent[] workers = new ManualResetEvent[] { worker1, worker2 };
        while (true)
        {
            Console.WriteLine("Pausing...");
            Thread.Sleep(5000); // long pause so we can see what is happening

            Console.WriteLine("Signalling workers.");
            startWorkers.Set(); // allow workers to run, automatically reset
            startWorkers.Reset();

            Console.WriteLine("Waiting for all workers to be done...");
            WaitHandle.WaitAll(workers); // wait for all the workers to be done
            Console.WriteLine("All workers are done.");

            Console.WriteLine("Resetting workers...");
            // Reset all workers
            foreach(ManualResetEvent mre in workers)
            {
                mre.Reset();
            }

            // release the workers to wait at the top of their loops
            Console.WriteLine("Releasing workers...");
            releaseWorkers.Set();
            releaseWorkers.Reset();
        }
    }

    static void DoWork1()
    {
        while (true)
        {
            Console.WriteLine("Worker1 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker1 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work

            Console.WriteLine("Worker1 done.");
            worker1.Set(); // let Synchroniser know we are done

            Console.WriteLine("Worker1 waiting for release...");
            releaseWorkers.WaitOne(); // wait for all clear
        }
    }

    static void DoWork2()
    {
        while (true)
        {
            Console.WriteLine("Worker2 waiting.");
            startWorkers.WaitOne(); // wait here until signalled

            // ... do something in here ...
            Console.WriteLine("Worker2 processing...");
            Thread.Sleep(R.Next(3000, 10000)); // random amount of work

            Console.WriteLine("Worker2 done.");
            worker2.Set(); // let Synchroniser know we are done

            Console.WriteLine("Worker2 waiting for release...");
            releaseWorkers.WaitOne(); // wait for all clear
        }
    }

}


问:
Make certain part of text bold using DataBinding
I want to make certain part of my text to bold whose value is set using DataBinding with ViewModel.

For e.g

If you are selected, you will pay $160 for your pair.

I am using strings resources

<string name="product_price">If you are selected, you will have to pay $%d for your pair.</string>

```<code><TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginEnd="@dimen/spacing_xlarge"
          android:layout_marginStart="@dimen/spacing_xlarge"
          android:layout_marginBottom="@dimen/spacing_small"
          android:text="@{@string/product_price(productPrice)}"
          android:textColor="@color/button_tertiary"
          android:visibility="@{productPrice > 0}"
          style="@style/Body.Small"
          />
</code>```

Currently passing product price using ViewModel with Binding by setting binding.setProductPrice(Object.getPrice())

I know the following solutions : But want to try using DataBinding

Using Html Text - But don't want to use it in code.

Using Different TextView in Horizontal Style. Setting styles as bold for that Product Price. - Really Bad Practice

Using SpannableString - But don't want to use it in code.

But all of the above solutions are workaround.

Question ::

Want to try DataBinding feature which can be used to style certain part of string. Just like SpannableString

Manipulate String in the Layout file using DataBinding

答:
use BindingAdapter as mentioned below </p>

```<code>    @BindingAdapter("setBold")
    @JvmStatic
    public static void setBold(TextView view, boolean isBold) {
        if (isBold) {
            view.setTypeface(null, Typeface.BOLD);
        } else {
            view.setTypeface(null, Typeface.NORMAL);
        }
    }
</code>```

<p>And use it   in xml as below :  </p>

```<code>  <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{model.value}"
        app:setBold="@{model.isBold}"
   />
</code>```

Body:
I want to make certain part of my text to bold whose value is set using DataBinding with ViewModel.

For e.g

If you are selected, you will pay $160 for your pair.

I am using strings resources

<string name="product_price">If you are selected, you will have to pay $%d for your pair.</string>

<TextView
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_marginEnd="@dimen/spacing_xlarge"
          android:layout_marginStart="@dimen/spacing_xlarge"
          android:layout_marginBottom="@dimen/spacing_small"
          android:text="@{@string/product_price(productPrice)}"
          android:textColor="@color/button_tertiary"
          android:visibility="@{productPrice > 0}"
          style="@style/Body.Small"
          />

Currently passing product price using ViewModel with Binding by setting binding.setProductPrice(Object.getPrice())

I know the following solutions : But want to try using DataBinding

Using Html Text - But don't want to use it in code.

Using Different TextView in Horizontal Style. Setting styles as bold for that Product Price. - Really Bad Practice

Using SpannableString - But don't want to use it in code.

But all of the above solutions are workaround.

Question ::

Want to try DataBinding feature which can be used to style certain part of string. Just like SpannableString

Manipulate String in the Layout file using DataBinding

Body:
use BindingAdapter as mentioned below

    @BindingAdapter("setBold")
    @JvmStatic
    public static void setBold(TextView view, boolean isBold) {
        if (isBold) {
            view.setTypeface(null, Typeface.BOLD);
        } else {
            view.setTypeface(null, Typeface.NORMAL);
        }
    }

And use it   in xml as below :

  <androidx.appcompat.widget.AppCompatTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@{model.value}"
        app:setBold="@{model.isBold}"
   />


问:
Point in rectangle
What is the fastest way to find if a point is in a rectangle given in this form:

I have two points which are the centers of opposite sides of the rectangle, and a number which is the height of those sides. I hope this is clear.

The rectangle is (probably) not aligned with the axis. I am wondering if there may be a faster algorithm given this data then calculating the four corners, rotating, etc.

An idea I though of but am not sure how to implement (having trouble with the math) was to find the distance from the point to the line traced between the two centers, and if it is  less then half the length of the side of the rectangle and also on the line then it is in the rectangle. I don't know how to explain this better.

Maybe the picture will help explain:

A, B, C are given, as well as the length of side A/B. Basically I thought that if CD is less then half of side A and D is on AB, the point is in the rectangle. But how do I do this?

Another thought: Instead of finding D to see if it is on AB, check if angles ABC and BAC are acute, but I still don't know how to do this.

答:
Not entirely sure it's the fastest, but this would likely work:

Rather than placing D half in between the two centers, project C as D along the AB axis. Then check that a) D is between A and B and b) CD is less or equal to half of the rectangle's height.

Re your idea of using the angles... using Pythagorus and or Al Kashi's theorem might actually make sense:

http://en.wikipedia.org/wiki/Law_of_cosines

ABC acute and BAC acute would both be a prerequisite, and given them you place C2 on the rectangle, with the same alpha/beta (see wiki page). From there you also know gamma (pi/2, since on the rectangle) and beta/alpha (pi/2 - beta), which leads to wondering whether the [A,C] or [B,C] distance is lesser or equal to that of [A,C2] or [B,C2] respectively.

ContentLicense: CC BY-SA 3.0

Title: Point in rectangle


问:
Variable is not assigned C# Unity
i have a problem with a variable:

```<code>private ScriptCorredor objetivo = null;
public List<ScriptCorredor> corredores2;
</code>```

I'm adding a series of ScriptCorridor to the list

I edit and add the full Enter method

```<code>public void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.tag == "enemigo")
    {
        corredores2.Add(collision.GetComponent<ScriptCorredor>());
        if (objetivo=null)
        {
            objetivo = corredores2.ElementAt(0);
        }
    }
}
</code>```

then i try asign the first objeto in the objetivo variable with:

```<code>objetivo = corredores2.ElementAt(0);
</code>```

but cannot be assigned, when I read the objetivo variable, it is always empty.

any idea what I'm failing at?

答:
When you create the list at the top change it to:

```<code>public List<ScriptCorredor> corredores2 = new List<ScriptCorredor>();
</code>```

You might be having an issue of trying to set index 0 of the list that hasn't been initialized yet. When you create the list variable its an empty variable. Adding new List

Title: Variable is not assigned C# Unity

Body:
i have a problem with a variable:

private ScriptCorredor objetivo = null;
public List

Body:
When you create the list at the top change it to:

public List<ScriptCorredor> corredores2 = new List<ScriptCorredor>();

You might be having an issue of trying to set index 0 of the list that hasn't been initialized yet. When you create the list variable its an empty variable. Adding new List<ScriptCorredor>(); to it, creates the list and puts it into that variable. Now it should work.


问:
Space at begin of paragraph
Hello im doing a project for my university in latex and came accross this problem and nothing to fix it.
Basically there is this white space bevore the beginning of each paragraph. Below is my latex code from this sheet.

```<code>einem Ausgabeneuron. Gewichte in Neuronalen Netzen sind reelle Zahlen, unter denen man sich die Wichtigkeit der jeweiligen Eingabe vorstellen kann. Ändert man die Gewichte der einzelnen Eingabeneuronen, beeinflusst man somit die spätere Aktivierung des Ausgabeneurons. Die Ausgabe $y$ wird bestimmt durch die Aktivierungsfunktion des Ausgabeneurons und ist dabei wie folgt definiert: \\
%Output gleichung
\begin{equation}
    y =
    \begin{cases}
      0, & \text{wenn}\ $$\sum_{i} w_{i}x_{i} \leq Schwellwert$$ \\
      1, & \text{andernfalls}
    \end{cases}
\end{equation}\\

Dabei ist der Schwellwert Teil des jeweiligen Neurons. Wie bei den Eingaben und Gewichtungen handelt es sich bei dem Schwellwert auch um eine reelle Zahl, welche anpassbar ist, um unterschiedliche Ergebnisse zu erzwingen. Worin besteht nun der Unterschied zu einem Multilayer Perzeptron? \\

Die Aktivierungsfunktion eines Multilayer Perzeptrons springt nicht zwischen 0 und 1, wie in (1) definiert sondern verhält sich stetig. \\
Das Singlelayer Perzeptron ist in der Lage, linear separierbare Probleme, wie z.B. die AND Funktion, zu lösen. Hier lassen sich die Resultatrelationen klar durch eine Gerade trennen. Bei der XOR Funktion reicht eine Gerade nicht mehr aus, ein Singlelayer Perzeptron wäre also nicht in der Lage, die XOR Funktion zu lösen.
</code>```

答: Add \usepackage{parskip} to your preamble. For further customisation options see the parskip documentation.

Title: Space at begin of paragraph

Body:
Hello im doing a project for my university in latex and came accross this problem and nothing to fix it.
Basically there is this white space bevore the beginning of each paragraph. Below is my latex code from this sheet.

einem Ausgabeneuron. Gewichte in Neuronalen Netzen sind reelle Zahlen, unter denen man sich die Wichtigkeit der jeweiligen Eingabe vorstellen kann. Ändert man die Gewichte der einzelnen Eingabeneuronen, beeinflusst man somit die spätere Aktivierung des Ausgabeneurons. Die Ausgabe $y$ wird bestimmt durch die Aktivierungsfunktion des Ausgabeneurons und ist dabei wie folgt definiert: \\
%Output gleichung
\begin{equation}
    y =
    \begin{cases}
      0, & \text{wenn}\ $$\sum_{i} w_{i}x_{i} \leq Schwellwert$$ \\
      1, & \text{andernfalls}
    \end{cases}
\end{equation}\\

Dabei ist der Schwellwert Teil des jeweiligen Neurons. Wie bei den Eingaben und Gewichtungen handelt es sich bei dem Schwellwert auch um eine reelle Zahl, welche anpassbar ist, um unterschiedliche Ergebnisse zu erzwingen. Worin besteht nun der Unterschied zu einem Multilayer Perzeptron? \\

Die Aktivierungsfunktion eines Multilayer Perzeptrons springt nicht zwischen 0 und 1, wie in (1) definiert sondern verhält sich stetig. \\
Das Singlelayer Perzeptron ist in der Lage, linear separierbare Probleme, wie z.B. die AND Funktion, zu lösen. Hier lassen sich die Resultatrelationen klar durch eine Gerade trennen. Bei der XOR Funktion reicht eine Gerade nicht mehr aus, ein Singlelayer Perzeptron wäre also nicht in der Lage, die XOR Funktion zu lösen.


问:
Using JavaScript , how do I keep user input on page after it has reloaded?
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

```

With JavaScript, is there anyway to make input stay once the page reloads?

答:
Well, ideally this value should come from the server through an API.
However, if you're keen on doing it with JavaScript, you may consider localstorage

```<code>var post = document.getElementById("userInput").value;
localStorage.setItem("post", post);

document.getElementById("printhere").innerHTML = post || localStorage.getItem("post");
</code>```

Body:
I used HTML and JavaScript to allow a user to enter text and then push submit. When the user pushes submit, his text is displayed on the page. The problem is that when the page is reloaded, the text goes away. Obviously. Here is the code I have:

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">

        <TEXTAREA Name="content" ROWS="5" COLS="20" id = "userInput"></TEXTAREA>

        <button  onclick="display()">post</button>

With JavaScript, is there anyway to make input stay once the page reloads?

Body:
Well, ideally this value should come from the server through an API.
However, if you're keen on doing it with JavaScript, you may consider localstorage

var post = document.getElementById("userInput").value;
localStorage.setItem("post", post);

document.getElementById("printhere").innerHTML = post || localStorage.getItem("post");


问:
ASP.NET Core Identity : a second operation started on this context before a previous operation completed
I get an error:

A second operation started on this context before a previous operation completed

when I am trying to add a user role using the AddToRoleAsync function. I have seen a lot of posts saying missing await but everything is correct. Below is the code that I am using.

```<code>public async Task<IActionResult> RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto)
{
        userForRegisterCustomerDto.UserName = userForRegisterCustomerDto.Email;

        var userToCreate = _mapper.Map<Users>(userForRegisterCustomerDto);

        var userVehicleToCreate = _mapper.Map<CustomerVehicles>(userForRegisterCustomerDto.CustomerVehicles);

        var result = await _userManager.CreateAsync(userToCreate, userForRegisterCustomerDto.Password);

        var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);

        if (result.Succeeded)
        {
            var currentUser = await _userManager.FindByEmailAsync(userForRegisterCustomerDto.Email);
            await _userManager.AddToRoleAsync(currentUser, "Customer");
            userVehicleToCreate.UserId = currentUser.Id;

            _repo.Add(userVehicleToCreate);

            if (await _repo.SaveAll())
            {
                string confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
                //ConfirmEmail(currentUser.Id, confirmationToken);
                return Ok(userToReturn);
            }
        }

        return BadRequest(result.Errors);
    }
</code>```

My Startup.cs is

```<code>services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);
</code>```

adding ServiceLifetime.Transient doesn't resolve this issue.  Please suggest.

Error is:

```<code> Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'Demo.API.Models.DataContext'.
      System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by
different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
         at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.IsInRoleAsync(TUser user, String normalizedRoleName, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.AddToRoleAsync(TUser user, String role)
   at Demo.API.Controllers.AuthController.RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto) in F:\test\Demo\Demo.API\Controllers\AuthController.cs:line 66
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker,
Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task
lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
</code>```

答:
then add this instead</p>

```<code>services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration
.GetConnectionString("DefaultConnection")).UseQueryTrackingBehaviour(QueryTrackingBehavior.NoTracking));
</code>```

Body:
I get an error:

A second operation started on this context before a previous operation completed

when I am trying to add a user role using the AddToRoleAsync function. I have seen a lot of posts saying missing await but everything is correct. Below is the code that I am using.

public async Task<IActionResult> RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto)
{
        userForRegisterCustomerDto.UserName = userForRegisterCustomerDto.Email;

        var userToCreate = _mapper.Map<Users>(userForRegisterCustomerDto);

        var userVehicleToCreate = _mapper.Map<CustomerVehicles>(userForRegisterCustomerDto.CustomerVehicles);

        var result = await _userManager.CreateAsync(userToCreate, userForRegisterCustomerDto.Password);

        var userToReturn = _mapper.Map<UserForDetailedDto>(userToCreate);

        if (result.Succeeded)
        {
            var currentUser = await _userManager.FindByEmailAsync(userForRegisterCustomerDto.Email);
            await _userManager.AddToRoleAsync(currentUser, "Customer");
            userVehicleToCreate.UserId = currentUser.Id;

            _repo.Add(userVehicleToCreate);

            if (await _repo.SaveAll())
            {
                string confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(currentUser);
                //ConfirmEmail(currentUser.Id, confirmationToken);
                return Ok(userToReturn);
            }
        }

        return BadRequest(result.Errors);
    }

My Startup.cs is

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

adding ServiceLifetime.Transient doesn't resolve this issue.  Please suggest.

Error is:

 Microsoft.EntityFrameworkCore.Query[10100]
      An exception occurred while iterating over the results of a query for context type 'Demo.API.Models.DataContext'.
      System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by
different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
         at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
         at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
      An unhandled exception has occurred while executing the request.
System.InvalidOperationException: A second operation started on this context before a previous operation completed. This is usually caused by different threads using the same instance of DbContext. For more information on how to avoid threading issues with DbContext, see https://go.microsoft.com/fwlink/?linkid=2097913.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.EntityFrameworkCore.UserStore`9.IsInRoleAsync(TUser user, String normalizedRoleName, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Identity.UserManager`1.AddToRoleAsync(TUser user, String role)
   at Demo.API.Controllers.AuthController.RegisterCustomer(UserForRegisterCustomerDto userForRegisterCustomerDto) in F:\test\Demo\Demo.API\Controllers\AuthController.cs:line 66
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker,
Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task
lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

Body:
then add this instead

services.AddDbContext<DataContext>(x => x.UseSqlServer(Configuration
.GetConnectionString("DefaultConnection")).UseQueryTrackingBehaviour(QueryTrackingBehavior.NoTracking));


问:
'IServiceCollection' does not contain a definition for 'AddControllers'
I have a ASP.NET Core 3.0 project running fine with the following startup:

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllers();
}
</code>```

Now I want to move this setup to another project, to serve as a Common dll to be used by dozens of other ASP.NET Core 3.0 projects where all of them will execute the startup with calling just services.Configure();, considering that Configure will be an extension method created by me.

For this, I've created another project with the following .csproj file:

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" />
  </ItemGroup>

</Project>
</code>```

And the following class:

```<code>using System;
using Microsoft.Extensions.DependencyInjection;

namespace MyCommon.Extensions
{
    public static class MyIServiceCollectionExtensions
    {
        public static class IServiceCollectionExtensions
        {
            public static IServiceCollection Configure(this IServiceCollection services)
            {
                services.AddCors();
                services.AddControllers();
                return services;
            }
        }
    }
}
</code>```

This gives me the following build error:

'IServiceCollection' does not contain a definition for 'AddControllers'

As I've already added the Microsoft.AspNetCore.Mvc package, I don't understand why the AddControllers method couldn't be found.

答:
I got the same with Asp .netcore 3.0.
Resolved it by adding Microsoft.AspNetCore.Mvc.NewtonsoftJson package.</p>

Body:
I have a ASP.NET Core 3.0 project running fine with the following startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllers();
}

Now I want to move this setup to another project, to serve as a Common dll to be used by dozens of other ASP.NET Core 3.0 projects where all of them will execute the startup with calling just services.Configure();, considering that Configure will be an extension method created by me.

For this, I've created another project with the following .csproj file:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="2.2.0" />
  </ItemGroup>

</Project>

And the following class:

using System;
using Microsoft.Extensions.DependencyInjection;

namespace MyCommon.Extensions
{
    public static class MyIServiceCollectionExtensions
    {
        public static class IServiceCollectionExtensions
        {
            public static IServiceCollection Configure(this IServiceCollection services)
            {
                services.AddCors();
                services.AddControllers();
                return services;
            }
        }
    }
}

This gives me the following build error:

'IServiceCollection' does not contain a definition for 'AddControllers'

As I've already added the Microsoft.AspNetCore.Mvc package, I don't understand why the AddControllers method couldn't be found.


问:
p5.js shape update issue
Um. I need help with the following p5.js code to make the shapes stop "bluring"
I mean how to make it so those shapes no longer have trails.

I believe the issue is relates to the "update" part. But i am not sure how to fix it.

Thanks

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(40, 100, 124);
  background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
  noFill();
  noStroke();
  rect(0, 0, width, height);

  for (let a = 0; a < cubes.length; a++) {
    cubes[a].update();
  }

}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 50;
  }

  update() {
    this.shape();
  }

  shape() {
    push();
    stroke(255);
    translate(this.x - width / 2, this.y - height / 2, 0);
    rotateX(millis() / 1000);
    rotateY(millis() / 800);
    ambientMaterial('clear');
    box(this.size);
    pop();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script></code>```

答:
You have to clear the background, by background() at begin of draw:

function draw() {
    background(backCol);
    noFill();
    noStroke();
    rect(0, 0, width, height);

    for (let a = 0; a < cubes.length; a++) {
        cubes[a].update();
    }
}
```

<p>Note, <code>background()</code> does not just set the background color, it actually clears the background. Invoking <code>background()</code> in <code>draw()</code>, ensures that the canvas is cleared in every frame.  </p>

<p>See the example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(40, 100, 124);
  background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
    background(backCol);
    noFill();
    noStroke();
    rect(0, 0, width, height);

    for (let a = 0; a < cubes.length; a++) {
        cubes[a].update();
    }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 50;
  }

  update() {
    this.shape();
  }

  shape() {
    push();
    stroke(255);
    translate(this.x - width / 2, this.y - height / 2, 0);
    rotateX(millis() / 1000);
    rotateY(millis() / 800);
    ambientMaterial('clear');
    box(this.size);
    pop();
  }
}</code>```

```

Title: p5.js shape update issue

Body:
You have to clear the background, by background() at begin of draw:

function draw() {
    background(backCol);
    noFill();
    noStroke();
    rect(0, 0, width, height);

    for (let a = 0; a < cubes.length; a++) {
        cubes[a].update();
    }
}

Note, background() does not just set the background color, it actually clears the background. Invoking background() in draw(), ensures that the canvas is cleared in every frame.

See the example:

let cubes = [];

function setup() {
  createCanvas(windowWidth, windowHeight, WEBGL);
  backCol = color(40, 100, 124);
  background(backCol);

  for (let i = 0; i < 10; i++) {
    for (let j = 0; j < 10; j++) {
      let xPos = map(i, 0, 9, 50, width - 50);
      let yPos = map(j, 0, 9, 50, height - 50);

      cubes.push(new Cubes(xPos, yPos));

    }
  }

}

function draw() {
    background(backCol);
    noFill();
    noStroke();
    rect(0, 0, width, height);

    for (let a = 0; a < cubes.length; a++) {
        cubes[a].update();
    }
}

class Cubes {

  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.size = 50;
  }

  update() {
    this.shape();
  }

  shape() {
    push();
    stroke(255);
    translate(this.x - width / 2, this.y - height / 2, 0);
    rotateX(millis() / 1000);
    rotateY(millis() / 800);
    ambientMaterial('clear');
    box(this.size);
    pop();
  }
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>


问:
strcpy and array function char to const char problem
I can't give a value in a string with function. Also my strcpy is always making problem.

I have a problem in char xc[50]=trying(c);

invalid conversion from 'char' to 'const char*' [-fpermissive]

```<code>//This function doing reverse printing.
#include <stdio.h>
#include <string.h>

char trying(char *pchar);

int main()
{

char c[50]="It is a massage";

char xc[50]=trying(c);

printf("%s",xc);

return 0;

}
</code>```

And other problem is  char d=pchar[j-i];

invalid conversion from 'char' to 'const char*' [-fpermissive]

b was not declared in this scope

```<code>char trying(char *pchar)
{
   for(int i=0;i<strlen(pchar);i++)
   {
      int j = strlen(pchar);

      char b[50];

      char d=pchar[j-i];

      strcpy(b,d);

   }

   return b;
}
</code>```

答:
In your main function, char xc[50]=trying(c); will not work:

To assign values to an array you'll have to do it one character at a time using a loop or using strcpy in case both the source and destination can be used as pointers.

In your trying function, strcpy(b,d); will not work:

The signature of strcpy is char * strcpy ( char * destination, const char * source );
so the source as well as the destination needs to be pointers, in your case d is not a pointer, it is just a character + logically (not syntactically) you are copying d to first position of character array b.

Body:
I can't give a value in a string with function. Also my strcpy is always making problem.

I have a problem in char xc[50]=trying(c);

invalid conversion from 'char' to 'const char*' [-fpermissive]

//This function doing reverse printing.
#include <stdio.h>
#include <string.h>

char trying(char *pchar);

int main()
{

char c[50]="It is a massage";

char xc[50]=trying(c);

printf("%s",xc);

return 0;

}

And other problem is  char d=pchar[j-i];

invalid conversion from 'char' to 'const char*' [-fpermissive]

b was not declared in this scope

char trying(char *pchar)
{
   for(int i=0;i<strlen(pchar);i++)
   {
      int j = strlen(pchar);

      char b[50];

      char d=pchar[j-i];

      strcpy(b,d);

   }

   return b;
}


问:
Kafka - different configuration settings
I am going through the documentation, and there seems to be there are lot of moving with respect to message processing like exactly once processing , at least once processing . And, the settings scattered here and there. There doesnt seem a single place that documents the properties need to be configured rougly for exactly once processing and atleast once processing.

I know there are many moving parts involved and it always depends . However, like i was mentioning before , what are the settings to be configured atleast to provide exactly once processing and at most once and atleast once ...

答:
You might be interested in the first part of Kafka FAQ that describes some approaches on how to avoid duplication on data production (i.e. on producer side):

Exactly once semantics has two parts: avoiding duplication during data
  production and avoiding duplicates during data consumption.

There are two approaches to getting exactly once semantics during data
  production:

Use a single-writer per partition and every time you get a network
  error check the last message in that partition to see if your last
  write succeeded

Include a primary key (UUID or something) in the
  message and deduplicate on the consumer.

If you do one of these things, the log that Kafka hosts will be
  duplicate-free. However, reading without duplicates depends on some
  co-operation from the consumer too. If the consumer is periodically
  checkpointing its position then if it fails and restarts it will
  restart from the checkpointed position. Thus if the data output and
  the checkpoint are not written atomically it will be possible to get
  duplicates here as well. This problem is particular to your storage
  system. For example, if you are using a database you could commit
  these together in a transaction. The HDFS loader Camus that LinkedIn
  wrote does something like this for Hadoop loads. The other alternative
  that doesn't require a transaction is to store the offset with the
  data loaded and deduplicate using the topic/partition/offset
  combination.


问:
Requirements for getting a Kindle Development Kit
How focused a project proposal is required to gain access to a Kindle Development Kit?

From Amazon's Request Access page:

Briefly describe the active content
  applications you intend to build on
  Kindle

I don't have a project spec yet, I just want to explore and experiment.  I thought about putting that as my description, but I don't want to be denied because my project wasn't fleshed out enough.

What types of applications have people described that have gained them access to the KDK?  Has anyone been denied access because of a "bad" proposal?  About how long did it take to hear back from Amazon?

答:
It makes sense to think about the motivations of Amazon and how that would restrict what they would allow. For instance:

They would like to make lots on money.

Proposing a way of selling lots of copies of your app, or proposing a very marketable app would make them like you.

Any apps that could bypass their revenue sources wouldn't be allowed. For instance file-sharing, or free ebook type apps.

They don't want it hacked.

Although it possible has been, Amazon won't allow you to create Apps that could become a security vulnerablility.

I general, you should write your proposal as a developer with good faith, outlining your idea and showing you have took Amazon's revenue protection into account, or that your going to make lots of money, or present something usefull for their users.

Also, I wouldn't suggest anything that would obviously put to much strain on the Kindle. I think anything more intensive than solitaire is a no no.


问:
Not update View when `changesetPublisher` emits a collection changeset
If I have a property in Realm models let book = List<Book>() then its changes do not update the View.

I think it`s because realm models are classes.

Any ideas on how to fix this

```<code>final class Book: Object, ObjectKeyIdentifable {

    @objc dynamic var id: String = ""
    @objc dynamic var title: String = ""
    @objc dynamic var subTitle: String = ""

    override class func primaryKey() -> String? {
        return "id"
    }
}

final class Author: Object, ObjectKeyIdentifable {

    @objc dynamic var id: String = ""
    @objc dynamic var name: String = ""
    let book = List<Book>()

    override class func primaryKey() -> String? {
        return "id"
    }
}

class Store: ObservableObject {

    @Published var Authors: Results<Author>?
    private var subscriptions = Set<AnyCancellable>()

    init() {
        let realm = try! Realm()
        realm.objects(Author.self)
            .changesetPublisher
            .sink { changeset in
                self.applyChangeset(changeset)
        }
        .store(in: &subscriptions)
    }

    func applyChangeset(_ changes: RealmCollectionChange<Results<Author>>) {
        switch changes {
        case .initial(let results):
            self.Authors = results
        case .update(let results, deletions: _, insertions: _, modifications: _):
            self.Authors = results
        case .error(let error):
            print(error.localizedDescription)
        }
    }
}

</code>```

答:
Try to dispatch on main queue, as

```<code>realm.objects(Author.self)
    .changesetPublisher
    .receive(on: DispatchQueue.main)      // << here !!
    .sink { [weak self] changeset in
        self?.applyChangeset(changeset)    // avoid cross reference
}
</code>```

and explicitly notify about changes, because you work with reference-type models, so changing internals does not change reference itself... so

```<code>func applyChangeset(_ changes: RealmCollectionChange<Results<Author>>) {
    switch changes {
    case .initial(let results):
        self.Authors = results
    case .update(let results, deletions: _, insertions: _, modifications: _):
        self.Authors = results
        // let assume we consider this case, then
        self.objectWillChange.send()                // << this !!
    case .error(let error):
        print(error.localizedDescription)
    }
}
</code>```

Body:
If I have a property in Realm models let book = List<Book>() then its changes do not update the View.

I think it`s because realm models are classes.

Any ideas on how to fix this

final class Book: Object, ObjectKeyIdentifable {

    @objc dynamic var id: String = ""
    @objc dynamic var title: String = ""
    @objc dynamic var subTitle: String = ""

    override class func primaryKey() -> String? {
        return "id"
    }
}

final class Author: Object, ObjectKeyIdentifable {

    @objc dynamic var id: String = ""
    @objc dynamic var name: String = ""
    let book = List<Book>()

    override class func primaryKey() -> String? {
        return "id"
    }
}

class Store: ObservableObject {

    @Published var Authors: Results<Author>?
    private var subscriptions = Set<AnyCancellable>()

    init() {
        let realm = try! Realm()
        realm.objects(Author.self)
            .changesetPublisher
            .sink { changeset in
                self.applyChangeset(changeset)
        }
        .store(in: &subscriptions)
    }

    func applyChangeset(_ changes: RealmCollectionChange<Results<Author>>) {
        switch changes {
        case .initial(let results):
            self.Authors = results
        case .update(let results, deletions: _, insertions: _, modifications: _):
            self.Authors = results
        case .error(let error):
            print(error.localizedDescription)
        }
    }
}

Body:
Try to dispatch on main queue, as

realm.objects(Author.self)
    .changesetPublisher
    .receive(on: DispatchQueue.main)      // << here !!
    .sink { [weak self] changeset in
        self?.applyChangeset(changeset)    // avoid cross reference
}

and explicitly notify about changes, because you work with reference-type models, so changing internals does not change reference itself... so

func applyChangeset(_ changes: RealmCollectionChange<Results<Author>>) {
    switch changes {
    case .initial(let results):
        self.Authors = results
    case .update(let results, deletions: _, insertions: _, modifications: _):
        self.Authors = results
        // let assume we consider this case, then
        self.objectWillChange.send()                // << this !!
    case .error(let error):
        print(error.localizedDescription)
    }
}


问:
FileReader is not defined with Angular Server Side Rendering
I'm setting Server Side Rendering in a large webapp. It works well for page without FileReader instance. Do you know how can I make FileReader to work with SSR enable?

I found an NPM package for filereader. I installed and import it in server.ts import * as FileReader from 'filereader'; but I got no result from that.

I also added the filereader package in the whitelist of webpack.server.config.ts with no luck again.

I tried to replace FileReader with new Response(blob).text(); but in that case it is the Response which is undefined too.

I also tried window.FileReader() and global.FileReader() and no luck again.

This is the method with FileReader:

```<code>function blobToText(blob: any): Observable<string> {
  return new Observable<string>((observer: any) => {
        if (!blob) {
            observer.next("");
            observer.complete();
        } else {
          let reader = new FileReader(); // FileReader is not defined
            reader.onload = event => {
                observer.next((<any>event.target).result);
                observer.complete();
            };
            reader.readAsText(blob);
        }
    });
}
</code>```

Here is the error message

I got: ERROR { Error: Uncaught (in promise): ReferenceError:
  FileReader is not defined ReferenceError: FileReader is not defined
      at Observable._subscribe....

答:
Maybe this answer comes too late but in case anybody else could run into this issue, this solution worked for me, when using Angular 9. So basically you need to create a block of code that only gets executed when your application is on the browser not in the server side:

```<code>//Import PLATFORM_ID and Inject from @angular/core
import { Component, OnInit, PLATFORM_ID, Inject } from '@angular/core';

@Component({
  selector: 'app-new-post',
  templateUrl: './new-post.component.html',
  styleUrls: ['./new-post.component.scss']
})
export class NewPostComponent implements OnInit {

//Change the FileReader variable
reader; //before it was: reader: FileReader = new FileReader();

//Inject PLATFORM_ID as follow:
    constructor(  @Inject(PLATFORM_ID) private platformId: any,
                  private readonly activatedRoute: ActivatedRoute,
                  private readonly fileUploadService: FileUploadService) {
    }

     ngOnInit() {
     //Create a code block that only gets executed when it's loaded in the browser:
        if (isPlatformBrowser(this.platformId)) {
          this.reader = new FileReader();
     }

}
</code>```

Body:
I'm setting Server Side Rendering in a large webapp. It works well for page without FileReader instance. Do you know how can I make FileReader to work with SSR enable?

I found an NPM package for filereader. I installed and import it in server.ts import * as FileReader from 'filereader'; but I got no result from that.

I also added the filereader package in the whitelist of webpack.server.config.ts with no luck again.

I tried to replace FileReader with new Response(blob).text(); but in that case it is the Response which is undefined too.

I also tried window.FileReader() and global.FileReader() and no luck again.

This is the method with FileReader:

function blobToText(blob: any): Observable<string> {
  return new Observable<string>((observer: any) => {
        if (!blob) {
            observer.next("");
            observer.complete();
        } else {
          let reader = new FileReader(); // FileReader is not defined
            reader.onload = event => {
                observer.next((<any>event.target).result);
                observer.complete();
            };
            reader.readAsText(blob);
        }
    });
}

Here is the error message

I got: ERROR { Error: Uncaught (in promise): ReferenceError:
  FileReader is not defined ReferenceError: FileReader is not defined
      at Observable._subscribe....

Body:
Maybe this answer comes too late but in case anybody else could run into this issue, this solution worked for me, when using Angular 9. So basically you need to create a block of code that only gets executed when your application is on the browser not in the server side:

//Import PLATFORM_ID and Inject from @angular/core
import { Component, OnInit, PLATFORM_ID, Inject } from '@angular/core';

@Component({
  selector: 'app-new-post',
  templateUrl: './new-post.component.html',
  styleUrls: ['./new-post.component.scss']
})
export class NewPostComponent implements OnInit {

//Change the FileReader variable
reader; //before it was: reader: FileReader = new FileReader();

//Inject PLATFORM_ID as follow:
    constructor(  @Inject(PLATFORM_ID) private platformId: any,
                  private readonly activatedRoute: ActivatedRoute,
                  private readonly fileUploadService: FileUploadService) {
    }

     ngOnInit() {
     //Create a code block that only gets executed when it's loaded in the browser:
        if (isPlatformBrowser(this.platformId)) {
          this.reader = new FileReader();
     }

}


问:
substring count in a string
Given a string s of length n. we have to count the number of substrings in which character s[i] of given string is present, where character s[i] is a vowel.

example : In this string "coding", character 'o' is present in 10 substrings and character 'i' is present in 12 substrings. so total 22 is answer.

constraints: string size can be up to 10^5 and number of test cases can be up to 10^2.

Note: string may contain upper case or lower case letter.

I have written a c++ program for this. But it is giving time limit exceed. It is running fine for a smaller size of the string. Can anyone help me for actual and better logic for such type of question.,which can run for larger string size also.

My attempt:

```<code>#include <bits/stdc++.h>
 using namespace std;

int main()
{
int t;
cin >> t;

while (t--)
 {
    int n,i;
    cin >> n;

    string str;
    cin >> str;

    unsigned long long int
  sum=0,pp;
    for(i=0;i<n;i++)
    {
        if(str[i]=='a' || str[i]=='A' || str[i]=='e' || str[i]=='E' || str[i]=='i' || str[i]=='I' || str[i]=='o' || str[i]=='O' || str[i]=='u' || str[i]=='U')
        {
            pp=(i+1)*(n-i);
            sum=sum+pp;
        }

    }

    cout <<sum << '\n';
}
</code>```

}

答:
Do not bruteforce. Do a combinatorics homework.

Hint #1: A string of length n has n*(n+1)/2 substrings.

Hint #2: Vowels partition the original string into a set of substrings of consonants. A substring of consonants of length k in turn generates k*(k+1)/2 substrings which should not be counted.

This should be enough to get you going.

Title: substring count in a string

Body:
Given a string s of length n. we have to count the number of substrings in which character s[i] of given string is present, where character s[i] is a vowel.

example : In this string "coding", character 'o' is present in 10 substrings and character 'i' is present in 12 substrings. so total 22 is answer.

constraints: string size can be up to 10^5 and number of test cases can be up to 10^2.

Note: string may contain upper case or lower case letter.

I have written a c++ program for this. But it is giving time limit exceed. It is running fine for a smaller size of the string. Can anyone help me for actual and better logic for such type of question.,which can run for larger string size also.

My attempt:

#include <bits/stdc++.h>
 using namespace std;

int main()
{
int t;
cin >> t;

while (t--)
 {
    int n,i;
    cin >> n;

    string str;
    cin >> str;

    unsigned long long int
  sum=0,pp;
    for(i=0;i<n;i++)
    {
        if(str[i]=='a' || str[i]=='A' || str[i]=='e' || str[i]=='E' || str[i]=='i' || str[i]=='I' || str[i]=='o' || str[i]=='O' || str[i]=='u' || str[i]=='U')
        {
            pp=(i+1)*(n-i);
            sum=sum+pp;
        }

    }

    cout <<sum << '\n';
}

}


问:
Checking whether current object is destroyed or not inside the same class in C++
I have to call a function of a class from another function of the same class. But the problem is for some cases the current object can be destroyed. So for this case calling the function is creating errors. Is there any way to check whether the current object is destroyed or not from inside the class?

Another thread may first delete the current object and then create another object of the same class before calling function1 from inside function2. In that case, calling function1 would be valid, right?

For example,

```<code>#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>

using namespace std;

class example {

public:
    example(){}
    ~example() {}

    void function1() {
        // some code here
        return;
    }

    void function2() {
        //some code here
        // I want to check whether the current object is destroyed or not before calling function1()
        function1();
    }
private:
    bool check;

};

int main()
{
    example *exp=new example();
    exp->function2();
}
</code>```

答:
Is there any way to check whether the current object is destroyed or not from inside the class?

No, there is no way to do that.

I presume that "from inside the class" means "by using state of the object". Well, if the object is destroyed, then there is no state that could be observed. Any attempt would result in undefined behaviour.

Also, when the object has been destroyed, member functions of the object may not be called, so it is pointless to test that in function2 because if the object had been destroyed, then calling function2 would already result in undefined behaviour.

Body:
I have to call a function of a class from another function of the same class. But the problem is for some cases the current object can be destroyed. So for this case calling the function is creating errors. Is there any way to check whether the current object is destroyed or not from inside the class?

Another thread may first delete the current object and then create another object of the same class before calling function1 from inside function2. In that case, calling function1 would be valid, right?

For example,

#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>

using namespace std;

class example {

public:
    example(){}
    ~example() {}

    void function1() {
        // some code here
        return;
    }

    void function2() {
        //some code here
        // I want to check whether the current object is destroyed or not before calling function1()
        function1();
    }
private:
    bool check;

};

int main()
{
    example *exp=new example();
    exp->function2();
}


问:
Generating Strings By Rotating Elements
I am trying to develop an algorithm which takes in an input string S and generate Strings by eliminating two characters at a time. Here's my code so far.

```<code>    String[] strings = {"a", "b", "c", "d", "e", "f"};
    int charsToBeRemoved = strings.length - 2;

    for( int i = 0; i < strings.length; i++ )
    {
        int counter = 1;
        StringJoiner p = new StringJoiner( "|" );
        p.add( strings[i] );
        for( int j = i + 1; j < strings.length; j++ )
        {
            p.add( strings[j] );
            counter += 1;
            if( counter == charsToBeRemoved )
            {
                counter = 1;
                j = ( charsToBeRemoved - 2 ) > 0 ? j - ( charsToBeRemoved - 2 ) : j;
                regexList.add( p.toString() );
                p = new StringJoiner( "|" );
                p.add( strings[i] );
            }
        }
    }
</code>```

This provides the output : [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, c|d|e|f] . However, what I am trying to get is a rotating array based solution. Something like [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, b|e|f|a, c|d|e|f, c|e|f|a, c|f|a|b], d|e|f|a, d|f|a|b, d|a|b|c. In my current code, these outputs b|e|f|a, c|e|f|a, c|f|a|b, d|e|f|a, d|f|a|b, d|a|b|care not formed because I need a way to access the previous elements of the array.

Can anyone suggest a way to do so, or how I should change my approach?

答:
To "wrap around" to the beginning of the array you'd use the % mod operator.

```<code>String[] strings = { "a", "b", "c", "d", "e", "f" };
int reduction = 2;

for(int i=0; i<strings.length; i++)
{
    for(int j=0; j<=reduction; j++)
    {
        StringJoiner p = new StringJoiner("|");
        p.add(strings[i]);
        for(int k=1; k<strings.length-reduction; k++)
            p.add(strings[(i + j + k) % strings.length]);
        System.out.println(p);
    }
}
</code>```

Output:

```<code>a|b|c|d
a|c|d|e
a|d|e|f
b|c|d|e
b|d|e|f
b|e|f|a
c|d|e|f
c|e|f|a
c|f|a|b
d|e|f|a
d|f|a|b
d|a|b|c
e|f|a|b
e|a|b|c
e|b|c|d
f|a|b|c
f|b|c|d
f|c|d|e
</code>```

Title: Generating Strings By Rotating Elements

Body:
I am trying to develop an algorithm which takes in an input string S and generate Strings by eliminating two characters at a time. Here's my code so far.

    String[] strings = {"a", "b", "c", "d", "e", "f"};
    int charsToBeRemoved = strings.length - 2;

    for( int i = 0; i < strings.length; i++ )
    {
        int counter = 1;
        StringJoiner p = new StringJoiner( "|" );
        p.add( strings[i] );
        for( int j = i + 1; j < strings.length; j++ )
        {
            p.add( strings[j] );
            counter += 1;
            if( counter == charsToBeRemoved )
            {
                counter = 1;
                j = ( charsToBeRemoved - 2 ) > 0 ? j - ( charsToBeRemoved - 2 ) : j;
                regexList.add( p.toString() );
                p = new StringJoiner( "|" );
                p.add( strings[i] );
            }
        }
    }

This provides the output : [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, c|d|e|f] . However, what I am trying to get is a rotating array based solution. Something like [a|b|c|d, a|c|d|e, a|d|e|f, b|c|d|e, b|d|e|f, b|e|f|a, c|d|e|f, c|e|f|a, c|f|a|b], d|e|f|a, d|f|a|b, d|a|b|c. In my current code, these outputs b|e|f|a, c|e|f|a, c|f|a|b, d|e|f|a, d|f|a|b, d|a|b|care not formed because I need a way to access the previous elements of the array.

Can anyone suggest a way to do so, or how I should change my approach?

Body:
To "wrap around" to the beginning of the array you'd use the % mod operator.

String[] strings = { "a", "b", "c", "d", "e", "f" };
int reduction = 2;

for(int i=0; i<strings.length; i++)
{
    for(int j=0; j<=reduction; j++)
    {
        StringJoiner p = new StringJoiner("|");
        p.add(strings[i]);
        for(int k=1; k<strings.length-reduction; k++)
            p.add(strings[(i + j + k) % strings.length]);
        System.out.println(p);
    }
}

Output:

a|b|c|d
a|c|d|e
a|d|e|f
b|c|d|e
b|d|e|f
b|e|f|a
c|d|e|f
c|e|f|a
c|f|a|b
d|e|f|a
d|f|a|b
d|a|b|c
e|f|a|b
e|a|b|c
e|b|c|d
f|a|b|c
f|b|c|d
f|c|d|e


问:
One ObservedObject needs to take in another ObservedObject as an argument; how do you do this?
```<code>struct ContentView {
    @ObservedObject var annotationsVM = AnnotationsVM()
    //I'd like to pass in the ViewModel() declared below into annotationsVM like AnnotationsVM(VModel: Vmodel)
    @ObservedObjects var VModel = ViewModel()

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    @ObservedObject var VModel = ViewModel()
    //I'd like to pass in the VModel in content view like: @ObservedObject var VModel: VModel
}
</code>```

Obviously, I can't pass in the VModel directly upon ContentView creation like I want to because the VModel object hasn't been created yet so it's inaccessible...

Recap: I want to pass in the VModel instance declared in ContentView into the annotationsVM instance (also declare in ContentView)

答:
You can do it in init like this:

```<code>struct ContentView {
    @ObservedObject var annotationsVM: AnnotationsVM
    @ObservedObject var vModel: ViewModel

    init() {
        let vm = ViewModel()
        vModel = vm
        annotationsVM = AnnotationsVM(vModel: vm)
    }

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    var vModel: ViewModel

    init(vModel: ViewModel) {
        vModel = vModel
    }
}
</code>```

And you can use @ObservedObject only in View.

Note: it may be better to pass ViewModels in init as parameters to follow the Dependency Injection pattern.

Body:
struct ContentView {
    @ObservedObject var annotationsVM = AnnotationsVM()
    //I'd like to pass in the ViewModel() declared below into annotationsVM like AnnotationsVM(VModel: Vmodel)
    @ObservedObjects var VModel = ViewModel()

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    @ObservedObject var VModel = ViewModel()
    //I'd like to pass in the VModel in content view like: @ObservedObject var VModel: VModel
}

Obviously, I can't pass in the VModel directly upon ContentView creation like I want to because the VModel object hasn't been created yet so it's inaccessible...

Recap: I want to pass in the VModel instance declared in ContentView into the annotationsVM instance (also declare in ContentView)

Body:
You can do it in init like this:

struct ContentView {
    @ObservedObject var annotationsVM: AnnotationsVM
    @ObservedObject var vModel: ViewModel

    init() {
        let vm = ViewModel()
        vModel = vm
        annotationsVM = AnnotationsVM(vModel: vm)
    }

    var body: some View {
        //All the SwiftUI view setup is in here
    }
}

class AnnotationsVM: ObservableObject {
    var vModel: ViewModel

    init(vModel: ViewModel) {
        vModel = vModel
    }
}

And you can use @ObservedObject only in View.

Note: it may be better to pass ViewModels in init as parameters to follow the Dependency Injection pattern.


问:
How to pass data from HTML page to PHP script without reloading the page?
Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.

Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.

Note: I don't want to reload my page.

HTML Code:

```<code><div id="section" style="display: none;">
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
        numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
        commodi voluptatum!
    </p>
</div>
<div id="myForm">
    <form id="testForm" method="post" action="#">
        <input id="form_name" type="text" name="name" class="form-control">
        <input type="submit" name="submit" class="btn btn-send" value="submit">
    </form>
</div>
</code>```

JavaScript Code:

```<code>const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    // Please suggest the flow and code for call PHP script from here

    form.style.display = 'none';
    sectionDiv.style.display = 'block';
});
</code>```

Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..

PHP Code:

```<code>include("db.php");

if (isset($_POST['submit']))
{
    $form_name=  $_POST['name'];
    $query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
    if(mysqli_query($conn, $query))
    {
        echo "asdfghjkl";
    }
    else
    {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
    }
}
</code>```

Thanks for your help in advance..

答:
You can do it many ways. I made this very simple way using Ajax with a single php file. You need to send the data via ajax and need to catch that using PHP. You can try the below code.

Note: Please make sure you have changed the your connection name, password and db name

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Insert Data from html form to MySQL Database using Ajax and PHP</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="message" style="display: none;">
            <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam quo ex pariatur aliquid vero!
                Voluptatibus harum accusamus amet maiores at sit, neque magni nulla ut optio quis culpa nisi nostrum!
            </p>
        </div>
        <form id="myForm">
            <label for="name">Name:</label>
            <input type="text" id="name" placeholder="Name" name="name" />
            <input type="submit" name="save" value="Submit" id="btn-save" />
        </form>

        <script>
            const submit = $('#btn-save').click(function (e) {
                e.preventDefault();

                const name = $('#name').val();

                if(!name) return alert('Please enter your name');

                $.ajax({
                    url: 'index.php',
                    type: 'POST',
                    data: { name: name },
                    success: function (data) {
                        $('.message').show();
                        $('#myForm').hide();
                    },
                });
            });
        </script>
    </body>
</html>

<?php
    $conn = mysqli_connect("localhost", "root", "","mydb");

    // Checking connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // If the form data found save and send response
    if(isset($_POST['name'])){
        $name=$_POST['name'];
        $sql = "INSERT INTO `users`( `name`) VALUES ('$name')";

        if (mysqli_query($conn, $sql)) {
            echo json_encode(array("statusCode"=>200));
        }
        else {
            echo json_encode(array("statusCode"=>201));
        }
        mysqli_close($conn);
    }
?>
</code>```

Body:
Goal: I want to Hide "myForm" div when data successfully post to the database and the "section" div will show component when submit button will clicked, its working properly.

Problem / Requirement: Problem is that data not posting to the database, how can i solve this problem to save data to the database and show / hide div after that database operation.

Note: I don't want to reload my page.

HTML Code:

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
        numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
        commodi voluptatum!

    <form id="testForm" method="post" action="#">
        <input id="form_name" type="text" name="name" class="form-control">
        <input type="submit" name="submit" class="btn btn-send" value="submit">
    </form>

JavaScript Code:

const sectionDiv = document.getElementById('section');
const form = document.getElementById('myForm');

form.addEventListener('submit', function (e) {
    e.preventDefault();

    // Please suggest the flow and code for call PHP script from here

    form.style.display = 'none';
    sectionDiv.style.display = 'block';
});

Please suggest flow and process in above Javascript code for how to pass my data to below PHP script..

PHP Code:

include("db.php");

if (isset($_POST['submit']))
{
    $form_name=  $_POST['name'];
    $query = "INSERT INTO `test` (`xxname`) VALUES ('$form_name')";
    if(mysqli_query($conn, $query))
    {
        echo "asdfghjkl";
    }
    else
    {
        echo "ERROR: Could not able to execute $query. " . mysqli_error($conn);
    }
}

Thanks for your help in advance..

Body:
You can do it many ways. I made this very simple way using Ajax with a single php file. You need to send the data via ajax and need to catch that using PHP. You can try the below code.

Note: Please make sure you have changed the your connection name, password and db name

<!DOCTYPE html>
<html>
    <head>
        <title>Insert Data from html form to MySQL Database using Ajax and PHP</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    <body>
        <div class="message" style="display: none;">
            <p>
                Lorem ipsum dolor sit amet consectetur adipisicing elit. Quibusdam quo ex pariatur aliquid vero!
                Voluptatibus harum accusamus amet maiores at sit, neque magni nulla ut optio quis culpa nisi nostrum!
            </p>
        </div>
        <form id="myForm">
            <label for="name">Name:</label>
            <input type="text" id="name" placeholder="Name" name="name" />
            <input type="submit" name="save" value="Submit" id="btn-save" />
        </form>

        <script>
            const submit = $('#btn-save').click(function (e) {
                e.preventDefault();

                const name = $('#name').val();

                if(!name) return alert('Please enter your name');

                $.ajax({
                    url: 'index.php',
                    type: 'POST',
                    data: { name: name },
                    success: function (data) {
                        $('.message').show();
                        $('#myForm').hide();
                    },
                });
            });
        </script>
    </body>
</html>

<?php
    $conn = mysqli_connect("localhost", "root", "","mydb");

    // Checking connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    // If the form data found save and send response
    if(isset($_POST['name'])){
        $name=$_POST['name'];
        $sql = "INSERT INTO `users`( `name`) VALUES ('$name')";

        if (mysqli_query($conn, $sql)) {
            echo json_encode(array("statusCode"=>200));
        }
        else {
            echo json_encode(array("statusCode"=>201));
        }
        mysqli_close($conn);
    }
?>


问:
Display data from MySQL to PHP page problem
I'm trying to display  some specific data from MySQL to the PHP web but I'm always getting 0 results .
the code i used is:</p>

```<code><?php
$conn = mysqli_connect("localhost", "root", "", "summary");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= .$user";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["money"];
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</code>```

答:
Your SQL string is wrong.

$sql = "SELECT money FROM users WHERE username= '$user'";
```

<p>However, I also strongly advise you to use prepared statements with parameter binding wither with mysqli_prepare or using PDO</p>

<p>So your code changes like this:</p>

<pre class="lang-php prettyprint-override"><code>$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= ?";
$stmt = $conn->prepare($sql);

if($stmt)
{
    $stmt->bind_param('s', $user);

    if($stmt->execute())
    {
        $result = $stmt->get_result();
        /...
    }
}
</code>```

Body:
I'm trying to display  some specific data from MySQL to the PHP web but I'm always getting 0 results .
the code i used is:

<?php
$conn = mysqli_connect("localhost", "root", "", "summary");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= .$user";
$result = $conn->query($sql);
if (!empty($result) && $result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
" . $row["money"];
}
echo "
";
} else { echo "0 results"; }
$conn->close();
?>

Body:
Your SQL string is wrong.

$sql = "SELECT money FROM users WHERE username= '$user'";

However, I also strongly advise you to use prepared statements with parameter binding wither with mysqli_prepare or using PDO

So your code changes like this:

$user= .$_SESSION["username"];
$sql = "SELECT money FROM users WHERE username= ?";
$stmt = $conn->prepare($sql);

if($stmt)
{
    $stmt->bind_param('s', $user);

    if($stmt->execute())
    {
        $result = $stmt->get_result();
        /...
    }
}


问:
React Table usePagination not applying pagination
Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

I am using the react-table package (version 7.1.0).

I have a table which shows some invoices.

I retrieve all the data on initial load. Then I want to apply client-side pagination to this data so that only some of the results show at any one time.

My data has 139 items in it.

The user will initially see 10 results and be able to 'Show More'. Currently this is implemented in a select field, which updates the pageSize

(In my example I am using fake data not coming from any endpoint.)

I am using the usePagination hook in the same way as in this official example: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination?file=/src/App.js

```<code>useTable(
    {
      columns,
      data,
      initialState: { pageIndex: 0, pageSize: 10 }
    },
    useSortBy,
    usePagination
  );
</code>```

However there must be something I am missing, because the pagination doesn't get applied, despite pageIndex and pageSize clearly being set.

```<code>  "pageIndex": 0,
  "pageSize": 10,
</code>```

All the results show at once, instead of only 10.

What is the cause of the pagination not being applied here?

Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

答:
You should try using these lines of code,

```<code>defaultPageSize={10}
pageSizeOptions={[10,20,30,40,50]}
showPaginationBottom={true}
</code>```

It will show only 10 rows in the table, and later you can change the page size and choose one from pageSizeOptions. showPaginationBottom={true} it will help showing pagination box at the end of the table.

Hope it will help you.

Body:
Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

I am using the react-table package (version 7.1.0).

I have a table which shows some invoices.

I retrieve all the data on initial load. Then I want to apply client-side pagination to this data so that only some of the results show at any one time.

My data has 139 items in it.

The user will initially see 10 results and be able to 'Show More'. Currently this is implemented in a select field, which updates the pageSize

(In my example I am using fake data not coming from any endpoint.)

I am using the usePagination hook in the same way as in this official example: https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination?file=/src/App.js

useTable(
    {
      columns,
      data,
      initialState: { pageIndex: 0, pageSize: 10 }
    },
    useSortBy,
    usePagination
  );

However there must be something I am missing, because the pagination doesn't get applied, despite pageIndex and pageSize clearly being set.

  "pageIndex": 0,
  "pageSize": 10,

All the results show at once, instead of only 10.

What is the cause of the pagination not being applied here?

Codesandbox example: https://codesandbox.io/s/react-table-pagination-not-working-xt4yw

Body:
You should try using these lines of code,

defaultPageSize={10}
pageSizeOptions={[10,20,30,40,50]}
showPaginationBottom={true}

It will show only 10 rows in the table, and later you can change the page size and choose one from pageSizeOptions. showPaginationBottom={true} it will help showing pagination box at the end of the table.

Hope it will help you.