问:
django models.ForeignKey("Tablename) or models.Foreignkey(Tablenamevariable)
Im looking at the django-generated model classes using inspectdb.

I noticed that sometimes strings and sometimes variable names are called based on their "read from top to bottom" appearance in the file.

here and example

```<code>class AuthGroup(models.Model):
    name = models.CharField(unique=True, max_length=150)

    class Meta:
        managed = True
        db_table = 'auth_group'

class AuthGroupPermissions(models.Model):
    id = models.BigAutoField(primary_key=True)
    group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
    permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)

    class Meta:
        managed = True
        db_table = 'auth_group_permissions'
        unique_together = (('group', 'permission'),)

class AuthPermission(models.Model):
    name = models.CharField(max_length=255)
    content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
    codename = models.CharField(max_length=100)

    class Meta:
        managed = True
        db_table = 'auth_permission'
        unique_together = (('content_type', 'codename'),)
</code>```

Using a legacy db (mysql) in my case.

Quesion is:
Can i not just always use the string name of the table insead of sometimes string sometimes variable? That would be safer in my case
Would these two statements not do the same thing?

```<code>group = models.ForeignKey('AuthGroup', models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)
</code>```

答:
Quesion is: Can i not just always use the string name of the table insead of sometimes string sometimes variable?

Yes: using ForeignKey(Foo, …) can be replaced with ForeignKey('Foo', …). A string literal is often used to refer to a model that will be defined further in the file, since you can not use Foo if the Foo class is not yet defined.

But if you want, you can use string literals for all the ForeignKeys. You can refer to a model with 'app_name.ModelName' or with simply 'ModelName' if the model is defined for the same app name as the model you are defining.

Body:
Im looking at the django-generated model classes using inspectdb.

I noticed that sometimes strings and sometimes variable names are called based on their "read from top to bottom" appearance in the file.

here and example

class AuthGroup(models.Model):
    name = models.CharField(unique=True, max_length=150)

    class Meta:
        managed = True
        db_table = 'auth_group'

class AuthGroupPermissions(models.Model):
    id = models.BigAutoField(primary_key=True)
    group = models.ForeignKey(AuthGroup, models.DO_NOTHING)
    permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)

    class Meta:
        managed = True
        db_table = 'auth_group_permissions'
        unique_together = (('group', 'permission'),)

class AuthPermission(models.Model):
    name = models.CharField(max_length=255)
    content_type = models.ForeignKey('DjangoContentType', models.DO_NOTHING)
    codename = models.CharField(max_length=100)

    class Meta:
        managed = True
        db_table = 'auth_permission'
        unique_together = (('content_type', 'codename'),)

Using a legacy db (mysql) in my case.

Quesion is:
Can i not just always use the string name of the table insead of sometimes string sometimes variable? That would be safer in my case
Would these two statements not do the same thing?

group = models.ForeignKey('AuthGroup', models.DO_NOTHING)
permission = models.ForeignKey('AuthPermission', models.DO_NOTHING)


来源: stackexchange

问:
List account which pass a condition and group out come by month
I have this database

```<code>CREATE TABLE Trainee(
TraineeID smallint unsigned auto_increment primary key,
Full_Name nvarchar(100) not null,
Birth_Date date not null,
Gender enum('male', 'female', 'unknown') not null,
ET_IQ tinyint not null,
CHECK (0<=ET_IQ<=20),
ET_Gmath tinyint not null,
CHECK (0<=ET_Gmath<=20),
ET_English tinyint not null,
CHECK (0<=ET_English<=50),
Training_Class varchar(15) not null,
Evaluation_Notes nvarchar (200),
 );
</code>```

I want to select Trainne which passed a condition and group those trainnees by their month of birth

```<code>SELECT Full_Name,
       Birth_Date
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
GROUP BY MONTH(Birth_Date);

('thomas', '1988-11-30', 'male', '10', '10', '40', '1')
('Tom', '1995-07-15', 'male', '15', '8', '30', '2')
('emma', '1990-08-20', 'female', '15', '15', '25', '3')
</code>```

But it is not working. Please help! Thanks

答:
Do you mean ORDER BY birth month?

Try this

SELECT Full_Name,
       Birth_Date,
       MONTHNAME(Birth_Date)
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
ORDER BY MONTH(Birth_Date), Full_Name;
```
<p><code>ORDER BY</code>  is the SQLish way to control how your result set is sorted. <code>GROUP BY</code> allows you to summarize your data, doing things like this:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT MONTHNAME(Birth_Date),
       COUNT(*) How_Many_Birthdays
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
GROUP BY MONTH(Birth_Date)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this database

CREATE TABLE Trainee(
TraineeID smallint unsigned auto_increment primary key,
Full_Name nvarchar(100) not null,
Birth_Date date not null,
Gender enum('male', 'female', 'unknown') not null,
ET_IQ tinyint not null,
CHECK (0<=ET_IQ<=20),
ET_Gmath tinyint not null,
CHECK (0<=ET_Gmath<=20),
ET_English tinyint not null,
CHECK (0<=ET_English<=50),
Training_Class varchar(15) not null,
Evaluation_Notes nvarchar (200),
 );

I want to select Trainne which passed a condition and group those trainnees by their month of birth

SELECT Full_Name,
       Birth_Date
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
GROUP BY MONTH(Birth_Date);

('thomas', '1988-11-30', 'male', '10', '10', '40', '1')
('Tom', '1995-07-15', 'male', '15', '8', '30', '2')
('emma', '1990-08-20', 'female', '15', '15', '25', '3')

But it is not working. Please help! Thanks

Body:
Do you mean ORDER BY birth month?

Try this

SELECT Full_Name,
       Birth_Date,
       MONTHNAME(Birth_Date)
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
ORDER BY MONTH(Birth_Date), Full_Name;

ORDER BY  is the SQLish way to control how your result set is sorted. GROUP BY allows you to summarize your data, doing things like this:

SELECT MONTHNAME(Birth_Date),
       COUNT(*) How_Many_Birthdays
FROM Trainee
WHERE ET_IQ + ET_Gmath + ET_English >= 20
GROUP BY MONTH(Birth_Date)


问:
filtering text with double quotation marks
I'm trying to filter the following, but the double quotationmarks are confusing me.

```<code>(load "")
</code>```

the code I have so far is:

```<code>find /v ""(load "")" < C:\acadlsip.txt | find /v ""(load "")" > acad.lsp
</code>```

答:
```<code>findstr /v (load\"\")  th1.txt > th2.txt
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to filter the following, but the double quotationmarks are confusing me.

(load "")

the code I have so far is:

find /v ""(load "")" < C:\acadlsip.txt | find /v ""(load "")" > acad.lsp

Body: findstr /v (load\"\")  th1.txt > th2.txt


问:
Laravel 5.2 $this->dispatch didn't call handle function
Laravel 5.2 $this->dispatch
didn't call handle function

I use the following controller

```<code>namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;
use Redis;
class HomeController extends Controller
{
    /**
     * Send a reminder e-mail to a given user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail()
    {
        $this->dispatch(new SendReminderEmail());
    }
}
</code>```

and the job file is

```<code>namespace App\Jobs;

use Redis;
use Mail;
use App\User;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendReminderEmail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function __construct()
    {
    }
    public function handle()
    {
      $redis = Redis::connection();
      $redis->set('org', 'Mycompany');
    }
}
</code>```

when i call the controller function and check redis server for org variable i got null value!

How can i call the job function?

答:
locally you can run

```<code>php artisan queue:work
</code>```

it will run all jobs from the queue

Body:
Laravel 5.2 $this->dispatch
didn't call handle function

I use the following controller

namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Jobs\SendReminderEmail;
use App\Http\Controllers\Controller;
use Redis;
class HomeController extends Controller
{
    /**
     * Send a reminder e-mail to a given user.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function sendReminderEmail()
    {
        $this->dispatch(new SendReminderEmail());
    }
}

and the job file is

namespace App\Jobs;

use Redis;
use Mail;
use App\User;
use App\Jobs\Job;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendReminderEmail extends Job implements ShouldQueue
{
    use InteractsWithQueue, SerializesModels;

    public function __construct()
    {
    }
    public function handle()
    {
      $redis = Redis::connection();
      $redis->set('org', 'Mycompany');
    }
}

when i call the controller function and check redis server for org variable i got null value!

How can i call the job function?

Body:
locally you can run

php artisan queue:work

it will run all jobs from the queue


问:
How original data is getting updated on changing the value of an object?
I have the following function

export const massageData = (data) => ({
  title: data?.label,
  sections: data?.sections?.map((item) => {
    if (item.display === "HR") {
      const tableBody = [{ id: "new" }];
      item["tableData"] = tableBody;
    }
    return item;
  }),
});
```

Here, what is happing I am updating the item , here data is getting updated and this if condition is getting called two times. also I am updating item with new value, but when returning it gives me undefined.

Any help will be helpful .

答:
The behavior whereby the original data is being updated after you mutate where the data is copied lies in the distinction between Value Types and Reference Types, which are the two broad categories that all data types in JavaScript fall into. For value types, it means that a value is simply a value and not the value retrieved from pointing to a position in memory. However, reference types are those data types whose value is not directly stored, but rather what is stored is a reference to a point in memory, and the value for those types is retrieved every time by pointing to the point in memory for the most updated value stored there.

That takes us to how to copy values from reference types in an intentional way, and those are Value Copy and Reference Copy. By doing value copy, it means that the value stored in the memory of the original data is copied to another point in memory, while a reference copy means that the copy of the original data is made by simply pointing a new variable to the same place in memory where the original data is pointing to in memory. The implication of either approach is that in the case of value copy, modifying the value-copied data will not mutate the original data, in the case of reference copy, however, modifying the reference-copied data will mutate the original data since that will mutate the data stored in the same memory location that both the original data and reference-copied data are pointing to.

The trickier part is in when you have reference types stored within reference types as is the case of the data parameter that your code shows have a section property, whose value is an Array (a reference type), that is a collection of item objects, each of which is an Object (also a reference type). The trick here is that even though Array.prototype.map method is known to be a pure function that makes a value copy of the array it is operating upon; which is section in your case, yet, it will only make a value copy of the array and cares less about making a value copy of the items within the array, which is what caused how mutating those items ended up mutating the original data you passed as an argument into the function eventually.

Thus, the way to solve that is to make a deep value copy of your arguments before operating on them within your function once they are reference types, and making a value copy of their children that are also reference types.

The below approach is one of many approaches that can achieve that:

```<code>const pureMassageData = (data) => {
  let dataCopy = { ...data };
  // Make a value copy of other reference props as is done for sections and then items within section as below
  dataCopy.sections = dataCopy.sections.map(item => ({ ...item }));
  return {
      title: dataCopy?.label,
      sections: dataCopy?.sections?.map((item) => {
        if (item.display === "HR") {
          const tableBody = [{ id: "new" }];
          item["tableData"] = tableBody;
        }
        return item;
      }),
    }
}
</code>```

Body:
I have the following function

export const massageData = (data) => ({
  title: data?.label,
  sections: data?.sections?.map((item) => {
    if (item.display === "HR") {
      const tableBody = [{ id: "new" }];
      item["tableData"] = tableBody;
    }
    return item;
  }),
});

Here, what is happing I am updating the item , here data is getting updated and this if condition is getting called two times. also I am updating item with new value, but when returning it gives me undefined.

Any help will be helpful .

Body:
The behavior whereby the original data is being updated after you mutate where the data is copied lies in the distinction between Value Types and Reference Types, which are the two broad categories that all data types in JavaScript fall into. For value types, it means that a value is simply a value and not the value retrieved from pointing to a position in memory. However, reference types are those data types whose value is not directly stored, but rather what is stored is a reference to a point in memory, and the value for those types is retrieved every time by pointing to the point in memory for the most updated value stored there.

That takes us to how to copy values from reference types in an intentional way, and those are Value Copy and Reference Copy. By doing value copy, it means that the value stored in the memory of the original data is copied to another point in memory, while a reference copy means that the copy of the original data is made by simply pointing a new variable to the same place in memory where the original data is pointing to in memory. The implication of either approach is that in the case of value copy, modifying the value-copied data will not mutate the original data, in the case of reference copy, however, modifying the reference-copied data will mutate the original data since that will mutate the data stored in the same memory location that both the original data and reference-copied data are pointing to.

The trickier part is in when you have reference types stored within reference types as is the case of the data parameter that your code shows have a section property, whose value is an Array (a reference type), that is a collection of item objects, each of which is an Object (also a reference type). The trick here is that even though Array.prototype.map method is known to be a pure function that makes a value copy of the array it is operating upon; which is section in your case, yet, it will only make a value copy of the array and cares less about making a value copy of the items within the array, which is what caused how mutating those items ended up mutating the original data you passed as an argument into the function eventually.

Thus, the way to solve that is to make a deep value copy of your arguments before operating on them within your function once they are reference types, and making a value copy of their children that are also reference types.

The below approach is one of many approaches that can achieve that:

const pureMassageData = (data) => {
  let dataCopy = { ...data };
  // Make a value copy of other reference props as is done for sections and then items within section as below
  dataCopy.sections = dataCopy.sections.map(item => ({ ...item }));
  return {
      title: dataCopy?.label,
      sections: dataCopy?.sections?.map((item) => {
        if (item.display === "HR") {
          const tableBody = [{ id: "new" }];
          item["tableData"] = tableBody;
        }
        return item;
      }),
    }
}


问:
how to merge two arrays of objects in javascript?
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.</p>
```<code>let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]
</code>```

答:
You can use lodash for that

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = _.merge(_.keyBy(arr1, 'name'), _.keyBy(arr2, 'name'));

console.log(arr3)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script></code>```

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]

Body:
You can use lodash for that

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = _.merge(_.keyBy(arr1, 'name'), _.keyBy(arr2, 'name'));

console.log(arr3)

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


问:
Mypy does not detect errors regarding the use of NamedTuple inside functions
In the following code the defintions of x2 and x3 are obviously wrong, yet mypy does not complain.

```<code>from typing import NamedTuple

class X(NamedTuple):
    a: float
    b: float
    c: float

def foo():
    x1 = X(1, 2, 3)
    x2 = X(1, 2)
    x3 = X("1", 2, 3)

</code>```

If I remove the function declaration and put the three lines into the main file scope, then mypy correctly identifies both errors

```<code>from typing import NamedTuple

class X(NamedTuple):
    a: float
    b: float
    c: float

x1 = X(1, 2, 3)
x2 = X(1, 2)
x3 = X("1", 2, 3)

</code>```

Why is that, what can I do about it?

Im running
python                    3.9.5
mypy                      0.931

答:
Your foo function is untyped, you must say to mypy to type it with ->:

```<code>def foo() -> None:
</code>```

Body:
In the following code the defintions of x2 and x3 are obviously wrong, yet mypy does not complain.

from typing import NamedTuple

class X(NamedTuple):
    a: float
    b: float
    c: float

def foo():
    x1 = X(1, 2, 3)
    x2 = X(1, 2)
    x3 = X("1", 2, 3)

If I remove the function declaration and put the three lines into the main file scope, then mypy correctly identifies both errors

from typing import NamedTuple

class X(NamedTuple):
    a: float
    b: float
    c: float

x1 = X(1, 2, 3)
x2 = X(1, 2)
x3 = X("1", 2, 3)

Why is that, what can I do about it?

Im running
python                    3.9.5
mypy                      0.931

Body:
Your foo function is untyped, you must say to mypy to type it with ->:

def foo() -> None:


问:
Next.js - Can we call custom hooks in GetStaticProps()
Is there any way for us to use the custom hook in getStaticProps(). The reason for this, is beacuse, we are using the Contentful CMS to fetch the data, from the Delivery API, and it is easier for us to have custom hooks to fetch certain data.

Now when we call, for example useHomePageData in getStaticProps() function, we get the error when trying to use simple object destructing to get the data.

```<code>Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
</code>```

This is the code we have in getStaticProps()

```<code>export function getStaticProps() {
const { data, isPending, error } = useFetchPagesProps('phasePage');
const { name, title, slug, sections } = data;

return {
 props: {
     name,
     title,
     slug,
     sections
  }
 }
}
</code>```

I know what this error means, but still does someone know for example any npm library or something like that, so that we can use this custom-hook?

P.S: We are also using useEffect() inside the custom-hook so that can cause the problems I think

答: getStaticProps technically has nothing to do with React. In essence that is just a function with a special meaning and functionality to the Next.js framework itself. So no, you can't use hooks in there (at least not the ones that use setState useEffect etc.. inside of them.

Body:
Is there any way for us to use the custom hook in getStaticProps(). The reason for this, is beacuse, we are using the Contentful CMS to fetch the data, from the Delivery API, and it is easier for us to have custom hooks to fetch certain data.

Now when we call, for example useHomePageData in getStaticProps() function, we get the error when trying to use simple object destructing to get the data.

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

This is the code we have in getStaticProps()

export function getStaticProps() {
const { data, isPending, error } = useFetchPagesProps('phasePage');
const { name, title, slug, sections } = data;

return {
 props: {
     name,
     title,
     slug,
     sections
  }
 }
}

I know what this error means, but still does someone know for example any npm library or something like that, so that we can use this custom-hook?

P.S: We are also using useEffect() inside the custom-hook so that can cause the problems I think


问:
How to solve this problem in Tabbed MDIChild Forms?
what is this error :
Form that was specified to be the MdiParent for this form is not an MdiContainer.
Parameter name: value

here is the code
 public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

```<code>    private void Form1_MdiChildActivate(object sender, EventArgs e)
    {
        if (this.ActiveMdiChild == null)
            tabForms.Visible = false; // If no any child form, hide tabControl
        else
        {
            this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized

            // If child form is new and no has tabPage, create new tabPage
            if (this.ActiveMdiChild.Tag == null)
            {
                // Add a tabPage to tabControl with child form caption
                TabPage tp = new TabPage(this.ActiveMdiChild.Text);
                tp.Tag = this.ActiveMdiChild;
                tp.Parent = tabForms;
                tabForms.SelectedTab = tp;

                this.ActiveMdiChild.Tag = tp;
                this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
            }

            if (!tabForms.Visible) tabForms.Visible = true;
        }
    }

    // If child form closed, remove tabPage
    private void ActiveMdiChild_FormClosed(object sender, FormClosedEventArgs e)
    {
        ((sender as Form).Tag as TabPage).Dispose();
    }

    private void tabForms_SelectedIndexChanged(object sender, EventArgs e)
    {
        if ((tabForms.SelectedTab != null) && (tabForms.SelectedTab.Tag != null))
            (tabForms.SelectedTab.Tag as Form).Select();
    }

    private void projectsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form7 f7 = new Form7();

        f7.MdiParent = this;
        f7.Show();
    }

}
</code>```

答:
The problem is probably that in your Form5 class you are not specifying that the Form is a MdiContainer.

Try setting the IsMdiContainer property to true or set the property manualy after you call InitializeComponent in the constructor.

Body:
what is this error :
Form that was specified to be the MdiParent for this form is not an MdiContainer.
Parameter name: value

here is the code
 public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
        }

    private void Form1_MdiChildActivate(object sender, EventArgs e)
    {
        if (this.ActiveMdiChild == null)
            tabForms.Visible = false; // If no any child form, hide tabControl
        else
        {
            this.ActiveMdiChild.WindowState = FormWindowState.Maximized; // Child form always maximized

            // If child form is new and no has tabPage, create new tabPage
            if (this.ActiveMdiChild.Tag == null)
            {
                // Add a tabPage to tabControl with child form caption
                TabPage tp = new TabPage(this.ActiveMdiChild.Text);
                tp.Tag = this.ActiveMdiChild;
                tp.Parent = tabForms;
                tabForms.SelectedTab = tp;

                this.ActiveMdiChild.Tag = tp;
                this.ActiveMdiChild.FormClosed += new FormClosedEventHandler(ActiveMdiChild_FormClosed);
            }

            if (!tabForms.Visible) tabForms.Visible = true;
        }
    }

    // If child form closed, remove tabPage
    private void ActiveMdiChild_FormClosed(object sender, FormClosedEventArgs e)
    {
        ((sender as Form).Tag as TabPage).Dispose();
    }

    private void tabForms_SelectedIndexChanged(object sender, EventArgs e)
    {
        if ((tabForms.SelectedTab != null) && (tabForms.SelectedTab.Tag != null))
            (tabForms.SelectedTab.Tag as Form).Select();
    }

    private void projectsToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form7 f7 = new Form7();

        f7.MdiParent = this;
        f7.Show();
    }

}


问:
How to use explain() in Node.js mongoose
I am trying to see The executionStats on my console but I always get undefined or [object, object]. I just have a simple query where I want to see some stats. Can someone explain why this isn't working? If I just use my query for querying (while not using explain()) the query is successful.

This is my query when trying to use explain with all the other code. I want to see the performance of the query so I found out that the best way to get the performance time is by using explain().

```<code>  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });
</code>```

And this is my query code where I can sucssessfuly get data and show them on my page

```<code>  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

conn.collection('galery').find({ "user_id": req.session.userId}).toArray( (err, resultImg) =>{
.
.
.
});

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });
</code>```

This is my output of MongoDB Debug:

```<code>MongoDebug:  {
  queryPlanner: {
    plannerVersion: 1,
    namespace: 'nodejsnosql.galerija',
    indexFilterSet: false,
    parsedQuery: { uporabnik_id: [Object] },
    winningPlan: { stage: 'COLLSCAN', filter: [Object], direction: 'forward' },
    rejectedPlans: []
  },
  executionStats: {
    executionSuccess: true,

    nReturned: 3,
    executionTimeMillis: 0,
    totalKeysExamined: 0,
    totalDocsExamined: 5,
    executionStages: {
      stage: 'COLLSCAN',
      filter: [Object],
      nReturned: 3,
  ok: 1,
  '$clusterTime': {
    clusterTime: new Timestamp({ t: 1644428067, i: 1 }),
    signature: {
      hash: new Binary(Buffer.from("71a216b111009bfcef6bd4923029d8df7a219e1a", "hex"), 0),
      keyId: new Long("7027534341366349828")
    }
  },
  operationTime: new Timestamp({ t: 1644428067, i: 1 })
}
</code>```

答:
You need to change how you are logging the explain object to console.

```<code>      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });
</code>```

By using 'MongoDebug: ' + explain[0] you are implicitly calling .toString() on explain[0] as you are appending it to a string, so it must be a string. For objects, this converts them to [object, Object].

Instead you can pass it as a separate object to your console.log:

```<code>console.log('MongoDebug: ', explain);
</code>```

Or convert it to JSON with extra spacing for better readability:

```<code>console.log(JSON.stringify(explain, null, 2));
</code>```

Body:
I am trying to see The executionStats on my console but I always get undefined or [object, object]. I just have a simple query where I want to see some stats. Can someone explain why this isn't working? If I just use my query for querying (while not using explain()) the query is successful.

This is my query when trying to use explain with all the other code. I want to see the performance of the query so I found out that the best way to get the performance time is by using explain().

  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

And this is my query code where I can sucssessfuly get data and show them on my page

  const timeFunction2 = new Promise((resolve, reject) => {
    var startTime = performance.now();

    setTimeout(() => {

conn.collection('galery').find({ "user_id": req.session.userId}).toArray( (err, resultImg) =>{
.
.
.
});

      var endTime = performance.now();
      resolve(endTime - startTime);
    });
  });

  timeFunction2.then(time => {
    console.log(`${time} ms.`);
  });

This is my output of MongoDB Debug:

MongoDebug:  {
  queryPlanner: {
    plannerVersion: 1,
    namespace: 'nodejsnosql.galerija',
    indexFilterSet: false,
    parsedQuery: { uporabnik_id: [Object] },
    winningPlan: { stage: 'COLLSCAN', filter: [Object], direction: 'forward' },
    rejectedPlans: []
  },
  executionStats: {
    executionSuccess: true,

    nReturned: 3,
    executionTimeMillis: 0,
    totalKeysExamined: 0,
    totalDocsExamined: 5,
    executionStages: {
      stage: 'COLLSCAN',
      filter: [Object],
      nReturned: 3,
  ok: 1,
  '$clusterTime': {
    clusterTime: new Timestamp({ t: 1644428067, i: 1 }),
    signature: {
      hash: new Binary(Buffer.from("71a216b111009bfcef6bd4923029d8df7a219e1a", "hex"), 0),
      keyId: new Long("7027534341366349828")
    }
  },
  operationTime: new Timestamp({ t: 1644428067, i: 1 })
}

Body:
You need to change how you are logging the explain object to console.

      conn.collection('galery').find({ "user_id": req.session.userId}).explain("executionStats", (err, explain) => {
        console.log('MongoDebug: ' + explain[0]);
      });

By using 'MongoDebug: ' + explain[0] you are implicitly calling .toString() on explain[0] as you are appending it to a string, so it must be a string. For objects, this converts them to [object, Object].

Instead you can pass it as a separate object to your console.log:

console.log('MongoDebug: ', explain);

Or convert it to JSON with extra spacing for better readability:

console.log(JSON.stringify(explain, null, 2));


问:
reactivity disappears after the object was in the array
Why, after passing through the reactive array, did the element's reactive property turn into a non-reactive one? Can you explain please.

```<code><script setup lang="ts">
    import { ref, Ref } from 'vue'

    interface Obj {
      a: number;
      r: Ref<{s:string}>;
    }
    const obj: Obj = { a: 1, r: ref<string>({s:"one"}) }; //create an instance
    const valBeforeArr=obj.r.value  //the variable is displayed as it should be
    //put an instance in a reactive array, and get from it
    const arr = ref<Obj[]>([]);
    arr.value.push(obj)
    const valAfterArrRef=arr.value[0].r.value //reference value missing
    const valAfterArrNonRef=arr.value[0].r //and the original value is displayed normally
    </script>

    <template>
      <h2>valBeforeArr: {{ valBeforeArr }}</h2>
      <h2>valAfterArrRef: {{ valAfterArrRef ?? 'underfined' }}</h2>
      <h2>valAfterArrNonRef: {{ valAfterArrNonRef ?? 'underfined' }}</h2>
    </template>
</code>```

playground

As explained to me
Estus Flask, reactivity has not disappeared. You can verify this with the following code:

```<code><template>
  <h2>valBeforeArr: {{ valBeforeArr }}</h2>
  <h2>valAfterArrRef: {{ valAfterArrRef ?? 'underfined' }}</h2>
  <h2>valAfterArrNonRef: {{ valAfterArrNonRef ?? 'underfined' }}</h2>
  <button @click="obj.r.value.s='seven'">updateBeforeArr</button>
  <button @click="arr[0].r.s='five'">updateAfterArr</button>
</template>
</code>```

But in one case you have to access using ".value", and in the other, without it. This is inconvenient, given that the object, in accordance with the business logic, can either pass through the array or not. How to access a property universally?

答:
The documentation explains this:

When a ref is accessed or mutated as a property of a reactive object,
it automatically unwraps to the inner value so it behaves like a
normal property

<...>

Ref unwrapping only happens when nested inside a reactive Object.
There is no unwrapping performed when the ref is accessed from an
Array or a native collection type like Map

Since ref is deeply reactive, arr.value elements are reactive objects, and refs in obj properties are unwrapped when it's added to the array and becomes reactive.

shallowRef can be used in order to avoid unwrapping in nested refs.

Body:
Why, after passing through the reactive array, did the element's reactive property turn into a non-reactive one? Can you explain please.

    <template>

valBeforeArr: {{ valBeforeArr }}

valAfterArrRef: {{ valAfterArrRef ?? 'underfined' }}

valAfterArrNonRef: {{ valAfterArrNonRef ?? 'underfined' }}

    </template>

<a href="https://sfc.vuejs.org/#eyJBcHAudnVlIjoiPHNjcmlwdCBzZXR1cCBsYW5nPVwidHNcIj5cbmltcG9ydCB7IHJlZiwgUmVmIH0gZnJvbSAndnVlJ1xuXG5pbnRlcmZhY2UgT2JqIHtcbiAgYTogbnVtYmVyO1xuICByOiBSZWY8e3M6c3RyaW5nfT47XG59XG5jb25zdCBvYmo6IE9iaiA9IHsgYTogMSwgcjogcmVmPHN0cmluZz4oe3M6XCJvbmVcIn0pIH07XG5jb25zdCB2YWxCZWZvcmVBcnI9b2JqLnIudmFsdWUgIFxuY29uc3QgYXJyID0gcmVmPE9ialtdPihbXSk7XG5hcnIudmFsdWUucHVzaChvYmopICBcbmNvbnN0IHZhbEFmdGVyQXJyUmVmPWFyci52YWx1ZVswXS5yLnZhbHVlXG5jb25zdCB2YWxBZnRlckFyck5vblJlZj1hcnIudmFsdWVbMF0uclxuPC9zY3JpcHQ+XG5cbjx0ZW1wbGF0ZT5cbiAgPGgyPnZhbEJlZm9yZUFycjoge3sgdmFsQmVmb3JlQXJyIH19PC9oMj5cbiAgPGgyPnZhbEFmdGVyQXJyUmVmOiB7eyB2YWxBZnRlckFyclJlZiA/PyAndW5kZXJmaW5lZCcgfX08L2gyPlxuICA8aDI+dmFsQWZ0ZXJBcnJOb25SZWY6IHt7IHZhbEFmdGVyQXJyTm9uUmVmID8/ICd1bmRlcmZpbmVkJyB9fTwvaDI+XG48L3RlbXBsYXRlPiIsImltcG9ydC1tYXAuanNvbiI6IntcbiAgXCJpbXBvcnRzXCI6IHtcbiAgICBcInZ1ZVwiOiBcImh0dHBzOi8vc2ZjLnZ1ZWpzLm9yZy92dWUucnVudGltZS5lc20tYnJvd3Nlci5qc1wiXG4gIH1cbn0ifQ==" rel="nofollow noreferrer">playground

As explained to me
Estus Flask, reactivity has not disappeared. You can verify this with the following code:

<template>

valBeforeArr: {{ valBeforeArr }}

valAfterArrRef: {{ valAfterArrRef ?? 'underfined' }}

valAfterArrNonRef: {{ valAfterArrNonRef ?? 'underfined' }}

  <button @click="obj.r.value.s='seven'">updateBeforeArr</button>
  <button @click="arr[0].r.s='five'">updateAfterArr</button>
</template>

But in one case you have to access using ".value", and in the other, without it. This is inconvenient, given that the object, in accordance with the business logic, can either pass through the array or not. How to access a property universally?


问:
Call a Widget based on the result of an If statement Flutter
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

```<code>import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
</code>```

The flow diagram is maybe easier to get the whole picture from.

答:
You can use a if(condition)...[widgetA] else...[WidgetB] structure:

```<code>    class _FilterPageState extends State<FilterPage> {
      String firstDropdownValue = 'Option A';
      String secondDropdownValue = 'Option B';

      @override
      void dispose() {
        super.dispose();
      }

      static const String _title = 'Filter Code Sample';

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            actions: [
              Padding(
                padding: EdgeInsets.all(4),
              ),
            ],
            title: Column(
              children: [
                Text(
                  'Filter',
                  style: TextStyle(fontSize: 22, color: Colors.amberAccent),
                ),
              ],
            ),
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: [
                  Text(
                    'What are the Options ?',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),

                  /*
                  * This is the first dropdown that is called, This dropdown provides
                  * two possible options,
                  * */
                  DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: firstDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        firstDropdownValue = newValue!;
                      });
                    },
                    items: <String>['Option A', 'Option B']
                        .map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),

                  if(firstDropDownValue)...[
                  DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: secondDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        secondDropdownValue = newValue!;
                      });
                    },
                    items: <String>[
                      'Option 1',
                      'Option 2',
                      'Option 3',
                    ].map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),
               ] else ...[
                 DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: secondDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        secondDropdownValue = newValue!;
                      });
                    },
                    items: <String>[
                      'Option 4',
                      'Option 5',
                      'Option 6',
                    ].map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),
                 ]
                ],
              ),
            ),
          ),
        );
      }
    }
</code>```

Body:
I want to be able to call either one of two different widgets based on the result of an if statement.
I am able to get a Text Widget to show two different answers based on the result of the first dropdown box, but I am not able to call another widget the same way ...

import 'package:flutter/material.dart';

class FilterPage extends StatefulWidget {
  const FilterPage({Key? key}) : super(key: key);

  @override
  State<FilterPage> createState() => _FilterPageState();
}

class _FilterPageState extends State<FilterPage> {
  String firstDropdownValue = 'Option A';
  String secondDropdownValue = 'Option B';

  @override
  void dispose() {
    super.dispose();
  }

  static const String _title = 'Filter Code Sample';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: [
          Padding(
            padding: EdgeInsets.all(4),
          ),
        ],
        title: Column(
          children: [
            Text(
              'Filter',
              style: TextStyle(fontSize: 22, color: Colors.amberAccent),
            ),
          ],
        ),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(8.0),
          child: Column(
            children: [
              Text(
                'What are the Options ?',
                style: TextStyle(fontSize: 16, color: Colors.white),
              ),

              /*
              * This is the first dropdown that is called, This dropdown provides
              * two possible options,
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: firstDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    firstDropdownValue = newValue!;
                  });
                },
                items: <String>['Option A', 'Option B']
                    .map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * So this is the if Statement that works based upon the first
              * drop down box's answer...
              *
              * The problem is I can not get the system to call another Drop down Butten
              * Widget based on the answer of the first DropdownBox,
              * However, i can get a Text Widget to print...
              * */
              Text((() {
                if (firstDropdownValue == 'Option A') {
                  return "Option is Option A";
                }
                return "Option is Option B";
              })()),

              /*
              * This is the second dropbox that I would like to be called if the
              * previous statement is met instead of the Text Widget above...
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 1',
                  'Option 2',
                  'Option 3',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),

              /*
              * This is also drop box two, but this dropbox with these different
              * options should be called when the if statement is not met ..
              *(DROPBOX 2)
              * */
              DropdownButton<String>(
                dropdownColor: Colors.blueGrey.shade700,
                value: secondDropdownValue,
                icon: const Icon(Icons.arrow_downward),
                elevation: 16,
                style: const TextStyle(color: Colors.white),
                underline: Container(
                  height: 2,
                  color: Colors.blueGrey.shade900,
                ),
                onChanged: (String? newValue) {
                  setState(() {
                    secondDropdownValue = newValue!;
                  });
                },
                items: <String>[
                  'Option 4',
                  'Option 5',
                  'Option 6',
                ].map<DropdownMenuItem<String>>((String doaValue) {
                  return DropdownMenuItem<String>(
                    value: doaValue,
                    child: Text(doaValue),
                  );
                }).toList(),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

The flow diagram is maybe easier to get the whole picture from.

Body:
You can use a if(condition)...[widgetA] else...[WidgetB] structure:

    class _FilterPageState extends State<FilterPage> {
      String firstDropdownValue = 'Option A';
      String secondDropdownValue = 'Option B';

      @override
      void dispose() {
        super.dispose();
      }

      static const String _title = 'Filter Code Sample';

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            actions: [
              Padding(
                padding: EdgeInsets.all(4),
              ),
            ],
            title: Column(
              children: [
                Text(
                  'Filter',
                  style: TextStyle(fontSize: 22, color: Colors.amberAccent),
                ),
              ],
            ),
          ),
          body: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Column(
                children: [
                  Text(
                    'What are the Options ?',
                    style: TextStyle(fontSize: 16, color: Colors.white),
                  ),

                  /*
                  * This is the first dropdown that is called, This dropdown provides
                  * two possible options,
                  * */
                  DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: firstDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        firstDropdownValue = newValue!;
                      });
                    },
                    items: <String>['Option A', 'Option B']
                        .map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),

                  if(firstDropDownValue)...[
                  DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: secondDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        secondDropdownValue = newValue!;
                      });
                    },
                    items: <String>[
                      'Option 1',
                      'Option 2',
                      'Option 3',
                    ].map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),
               ] else ...[
                 DropdownButton<String>(
                    dropdownColor: Colors.blueGrey.shade700,
                    value: secondDropdownValue,
                    icon: const Icon(Icons.arrow_downward),
                    elevation: 16,
                    style: const TextStyle(color: Colors.white),
                    underline: Container(
                      height: 2,
                      color: Colors.blueGrey.shade900,
                    ),
                    onChanged: (String? newValue) {
                      setState(() {
                        secondDropdownValue = newValue!;
                      });
                    },
                    items: <String>[
                      'Option 4',
                      'Option 5',
                      'Option 6',
                    ].map<DropdownMenuItem<String>>((String doaValue) {
                      return DropdownMenuItem<String>(
                        value: doaValue,
                        child: Text(doaValue),
                      );
                    }).toList(),
                  ),
                 ]
                ],
              ),
            ),
          ),
        );
      }
    }


问:
CSS submit button weird on Iphone
A line like a border-right added on iPhone button submit, it's working fine on Android

I tried this property but it's still not working

```<code>-webkit-appearance: button;
</code>```

The HTML of the button

```<code><button
    id="ta-quantity-selector__custom-ok"
    className="QuantitySelectorCustomField__button-ok"
    type="button"
  >
    OK
  </button>
</code>```

Do you have any fix for this issue, please?

答:
I used Arman Ebrahimi's answer it's working using

```<code>button{ width: 100%; }
</code>```

Thank you Arman Ebrahimi

Title: CSS submit button weird on Iphone

Body:
A line like a border-right added on iPhone button submit, it's working fine on Android

I tried this property but it's still not working

-webkit-appearance: button;

The HTML of the button

<button
    id="ta-quantity-selector__custom-ok"
    className="QuantitySelectorCustomField__button-ok"
    type="button"
  >
    OK
  </button>

Do you have any fix for this issue, please?

Body:
I used Arman Ebrahimi's answer it's working using

button{ width: 100%; }

Thank you Arman Ebrahimi


问:
rawurlencode not encoding white spaces
Here is a snippet of my code:

```<code>print ('href="files/'.rawurlencode($projectDesc).'/'.rawurlencode($file["FILENAME"]).'.pdf#zoom=100&view=Fit&pagemode='.$file["MODE"].'&page='.$file["PAGE"].'" class="pdfselector" target="_blank">');
</code>```

the $file["FILENAME"] variable often has white-space in it, when I use plain old urlencode() it converts my white spaces to +symbols. However this is not appropriate outside the querystring so I switched to rawurlencode() which now appears to ignore white space all together.

Here is an example output of my rawurlencode():

```<code>eHealth flyer_Final
</code>```

notice how it completely ignores the white space, anyone got any ideas as to why this would be happening?

答:
Works for me

http://sandbox.phpcode.eu/g/44af2.php

```<code><?php
$projectDesc = "eHealth flyer_Final";
$file["FILENAME"] = "eHealth flyer_Final";
$file["MODE"] = "test";

print ('href="files/'.rawurlencode($projectDesc).'/'.rawurlencode($file["FILENAME"]).'.pdf#zoom=100&view=Fit&pagemode='.$file["MODE"].'&page='.$file["PAGE"].'" class="pdfselector" target="_blank">');
</code>```

Title: rawurlencode not encoding white spaces

Body:
Here is a snippet of my code:

print ('href="files/'.rawurlencode($projectDesc).'/'.rawurlencode($file["FILENAME"]).'.pdf#zoom=100&view=Fit&pagemode='.$file["MODE"].'&page='.$file["PAGE"].'" class="pdfselector" target="_blank">');

the $file["FILENAME"] variable often has white-space in it, when I use plain old urlencode() it converts my white spaces to +symbols. However this is not appropriate outside the querystring so I switched to rawurlencode() which now appears to ignore white space all together.

Here is an example output of my rawurlencode():

eHealth flyer_Final

notice how it completely ignores the white space, anyone got any ideas as to why this would be happening?

Body:
Works for me

http://sandbox.phpcode.eu/g/44af2.php

<?php
$projectDesc = "eHealth flyer_Final";
$file["FILENAME"] = "eHealth flyer_Final";
$file["MODE"] = "test";

print ('href="files/'.rawurlencode($projectDesc).'/'.rawurlencode($file["FILENAME"]).'.pdf#zoom=100&view=Fit&pagemode='.$file["MODE"].'&page='.$file["PAGE"].'" class="pdfselector" target="_blank">');


问:
How to create spaces between characters in power point using pptx python?
I have a string and I want to use character spacing in this string, it is 'normal' but I want to choose 'loose' option. How can I do it using pptx python? I know I can put spaces manually between each character to look like spaced but I want to use this character spacing. So can anyone help me with this?

答:
You can easily set any character spacing for text in PowerPoint presentations using Aspose.Slides for Python as shown below:

import aspose.slides as slides

file_name = "example.pptx"
slide_index = 0
shape_index = 0
paragraph_index = 0
portion_index = 0

with slides.Presentation(file_name) as presentation:

    # Get a shape with a text.
    shape = presentation.slides[slide_index].shapes[shape_index]

    # Get a text portion to change the spacing.
    text_portion = shape.text_frame.paragraphs[paragraph_index].portions[portion_index]

    # Set the character spacing to 10, for example.
    text_portion.portion_format.spacing = 10
```
<p>You can also evaluate Aspose.Slides Cloud for presentation manipulating. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to do the same using Aspose.Slides Cloud:</p>
<pre class="lang-py prettyprint-override"><code>import asposeslidescloud

from asposeslidescloud.apis.slides_api import SlidesApi

slides_api = SlidesApi(None, "my_client_id", "my_client_key")

file_name = "example.pptx"

# 1-based indices
slide_index = 1
shape_index = 1
paragraph_index = 1
portion_index = 1

# Get a text portion to change the spacing.
text_portion = slides_api.get_portion(
    file_name, slide_index, shape_index, paragraph_index, portion_index)

# Set the character spacing to 10, for example.
text_portion.spacing = 10

# Update the text portion.
slides_api.update_portion(
    file_name, slide_index, shape_index, paragraph_index, portion_index, text_portion)
</code>```

I work as a Support Developer at Aspose.

Body:
You can easily set any character spacing for text in PowerPoint presentations using Aspose.Slides for Python as shown below:

import aspose.slides as slides

file_name = "example.pptx"
slide_index = 0
shape_index = 0
paragraph_index = 0
portion_index = 0

with slides.Presentation(file_name) as presentation:

    # Get a shape with a text.
    shape = presentation.slides[slide_index].shapes[shape_index]

    # Get a text portion to change the spacing.
    text_portion = shape.text_frame.paragraphs[paragraph_index].portions[portion_index]

    # Set the character spacing to 10, for example.
    text_portion.portion_format.spacing = 10

You can also evaluate Aspose.Slides Cloud for presentation manipulating. This REST-based API allows you to make 150 free API calls per month for API learning and presentation processing. The following code example shows you how to do the same using Aspose.Slides Cloud:

import asposeslidescloud

from asposeslidescloud.apis.slides_api import SlidesApi

slides_api = SlidesApi(None, "my_client_id", "my_client_key")

file_name = "example.pptx"

# 1-based indices
slide_index = 1
shape_index = 1
paragraph_index = 1
portion_index = 1

# Get a text portion to change the spacing.
text_portion = slides_api.get_portion(
    file_name, slide_index, shape_index, paragraph_index, portion_index)

# Set the character spacing to 10, for example.
text_portion.spacing = 10

# Update the text portion.
slides_api.update_portion(
    file_name, slide_index, shape_index, paragraph_index, portion_index, text_portion)

I work as a Support Developer at Aspose.


问:
Difference between PRTG and Grafana
I would like to know the difference between Grafana and PRTG from a functional point of view.

We use PRTG at work and I have to do a proof of concept on Grafana.

Every morning I look at the errors / warnings reported by PRTG but I lack overall visibility. So after some research I saw that PRTG offer to create MAPS (dashboards) but it seems limited to infra / network.

My objective is initially to make an easy correlation between the infrastructure's monitored elements (storage, vmware, switchs, etc...) and PRTG Maps seem to more or less meet the needs. Also I want to do daily/weekly reporting and easily follow the evolution of the infra over the month.

But on the other hand, I would like to be able to offer application dashboards and potentially dedicated to other teams (helpdesk, change manager, etc.)..

Grafana looks more friendly and especially seems to be able to create dashboards on other perimeters.

Can the two tools be complementary or PRTG is ok on its own ?

Thank you.

答:
PRTG allows you to create application dashboards - you are limited only by sensors you have in your system. This means if you create only system level sensors like Ping, CPU, network utilization - then you cannot really say much about your application since you monitor only infrastructure.
PRTG is good in creating Maps in comparison to other monitoring tools and they are now working on improvement of this functionality (see their roadmap). Creating maps specific to teams in your company is possible with PRTG (permissions can be set) and is good idea in general.

To make weekly/daily reports there is possibility to let PRTG send you email with attached PDF related to sensor[s] you choose. Similar functionality has Grafana (cloud/enterprise version)

The difference between PRTG and Grafana as of January 2022 is that PRTG does not allow you to zoom into charts dynamically (meaning with your mouse at specific start/stop date/time range) - its much more "static" in this regard and you as user wish to have this option. If you create application map in PRTG then you can forget any zooming or changing of date on that dashboard - its just not built for it. Its more like "what is status now" dashboard, but never for analysis of issues which happened yesterday which is exactly what you want if something happened during weekend and its Monday.

I see that Grafana has some Machine Learning possibility where PRTG has none - it only shows you similar behavior of sensors but that is good for a cat (at least i never needed it in my 7+ years of using PRTG)

Grafana as far i know it is just a frontend but PRTG is whole monitoring system inclusive frontend so you are not comparing sensor capabilities here - in this PRTG is really very good and they are adding new sensors every month (meaning for new vendors/hardware you have possibility to monitor them with specialised sensors built just for this hardware)

I don't think you can combine Grafana and PRTG - its either or since you have different monitoring engine on background of Grafana.

Hope it answers your questions

Title: Difference between PRTG and Grafana


问:
How to make a circle on the LaunchScreen?
I made a Cocoa Touch Class called BlackCircle, a UILabel subview which called the drawRect() method to make a black circular label. I dragged a UILabel onto the LaunchScreen.xib file, and when I assigned the Cocoa Touch Class File as the class of the UILabel, I got an error-

"Launch Screen may not use instances of BlackCircle".

It works fine on the main.storyboard file, but it doesn't work on the LaunchScreen.xib file. How can I fix this? Thanks!

答:
Yes there is a way!

You can add an image view and use SF image like "circle.fill" (just enter the name in the topmost text field) and use tint color to style it in your way.


问:
xml node name validation
I want to create regex which will validate xml node name. I have found grammar for names, but I don't know what some parts of it means. http://www.xml.com/pub/a/2001/07/25/namingparts.html

```<code>[4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
[5] Name ::= (Letter | '_' | ':') (NameChar)*
</code>```

What does CombiningChar and Extender mean?

Thanks.

答:
According to your spec I think this should do the trick:

```<code>(\w|_|:)(\w|\d|\.|-|_|:)*
</code>```

That's without CombiningChar and Extender. In the official spec you can find what exactly is meant with CombiningChar and Extender (Ctrl+F for these on that page), you'd however have to translate the unicode codes.

Title: xml node name validation

Body:
I want to create regex which will validate xml node name. I have found grammar for names, but I don't know what some parts of it means. http://www.xml.com/pub/a/2001/07/25/namingparts.html

[4] NameChar ::= Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender
[5] Name ::= (Letter | '_' | ':') (NameChar)*

What does CombiningChar and Extender mean?

Thanks.

Body:
According to your spec I think this should do the trick:

(\w|_|:)(\w|\d|\.|-|_|:)*

That's without CombiningChar and Extender. In the official spec you can find what exactly is meant with CombiningChar and Extender (Ctrl+F for these on that page), you'd however have to translate the unicode codes.


问:
Original exception text was: 'int' object has no attribute 'name'. in django rest framework
I am trying to call a get api but it gives me this error everytime.

The error:

AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.

Original exception text was: 'int' object has no attribute 'name'.

My models:

```<code>class Destination(models.Model):
    Continent_Name = (
        ('Europe', 'Europe',),
        ('Asia', 'Asia',),
        ('North America', 'North America',),
        ('South America', 'South America',),
        ('Africa', 'Africa',),
        ('Oceania', 'Oceania',),
        ('Polar', 'Polar',),
        ('Regions', 'Regions',),
    )
    name = models.CharField(max_length=255, unique=True)
    continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
    top = models.BooleanField(default=False)
    dest_image = models.ImageField(blank=True)

    def __str__(self):
        return self.name

class Package(models.Model):
    TOUR_TYPE = (
        ('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
        ('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
        ('Group Tour', 'Group Tour',),
        ('Cruise Tour', 'Cruise Tour',),
    )

    operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
    package_name = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    featured = models.BooleanField(default=False)
    price = models.IntegerField(verbose_name="Price in Nrs")
    price_2 = models.IntegerField(verbose_name="Price in $")
    duration = models.IntegerField(default=5)
    duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
    discount = models.IntegerField(verbose_name="Discount %", default=15)
    #discounted_price = models.IntegerField(default=230)
    #savings = models.IntegerField(default=230)
    tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
    new_activity = models.ManyToManyField(NewActivity)
    accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
    transport = models.CharField(max_length=150, default='Flight')
    age_range = models.CharField(max_length=100, default='6 to 79 years old')
    fix_departure = models.BooleanField(default=False)
    rating = models.IntegerField(choices=((1, 1),
                                          (2, 2),
                                          (3, 3),
                                          (4, 4),
                                          (5, 5))
                                 )

    image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")

    content =RichTextField()
    highlights = RichTextField()
    inclusions = RichTextField()
    exclusions = RichTextField()
    # itinerary = models.ManyToManyField(Itinerary)
    itinerary_text = RichTextField()
    faqs = RichTextField(blank=True)
    image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
    image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
    image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
    date_created = models.DateField()

    def __str__(self):
        return self.package_name
</code>```

My views:

```<code>class PackageSearchAPi(ListAPIView):
    queryset = Package.objects.all().order_by('package_name')
    serializer_class = PackageSerializer

    def get(self, request, *args, **kwargs):

        search = self.request.query_params.get('search',None)
        if search is not None:
            qs = Package.objects.filter(Q(destination__name__icontains=search)|
                                        Q(destination__continent__icontains=search)|
                                        Q(package_name__icontains=search)|
                                        Q(city__icontains=search)).disctinct()

        else:
            qs = Package.objects.values('id','destination','package_name','city')

        serializer = PackageSerializer(qs,many=True)
        return Response(serializer.data,status=200)
</code>```

My serializers:

```<code>class PackageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]

        depth = 1
</code>```

Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.

Traceback:

```<code>File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
    return Response(serializer.data,status=200)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
    ret = super().data
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
    return [
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
    attribute = field.get_attribute(instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
    raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.
</code>```

答:
For nested relations you have to define nested serializer</p>
```<code>class DestinationSerializer(serializers.Serializer):
    name = serializers.CharField()
    top = serializers.BooleanField()
    continent = serializers.CharField()

class PackageSerializer(serializers.ModelSerializer):
    destination = DestinationSerializer()
    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]

</code>```

Body:
I am trying to call a get api but it gives me this error everytime.

The error:

AttributeError: Got AttributeError when attempting to get a value for field name on serializer NestedSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the int instance.

Original exception text was: 'int' object has no attribute 'name'.

My models:

class Destination(models.Model):
    Continent_Name = (
        ('Europe', 'Europe',),
        ('Asia', 'Asia',),
        ('North America', 'North America',),
        ('South America', 'South America',),
        ('Africa', 'Africa',),
        ('Oceania', 'Oceania',),
        ('Polar', 'Polar',),
        ('Regions', 'Regions',),
    )
    name = models.CharField(max_length=255, unique=True)
    continent = models.CharField(max_length=255, choices=Continent_Name, default='Europe')
    top = models.BooleanField(default=False)
    dest_image = models.ImageField(blank=True)

    def __str__(self):
        return self.name

class Package(models.Model):
    TOUR_TYPE = (
        ('Custom-made trip with guide and/or driver', 'Custom-made trip with guide and/or driver',),
        ('Custom-made trip without guide and driver', 'Custom-made trip without guide and driver',),
        ('Group Tour', 'Group Tour',),
        ('Cruise Tour', 'Cruise Tour',),
    )

    operator = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
    destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
    package_name = models.CharField(max_length=255)
    city = models.CharField(max_length=255)
    featured = models.BooleanField(default=False)
    price = models.IntegerField(verbose_name="Price in Nrs")
    price_2 = models.IntegerField(verbose_name="Price in $")
    duration = models.IntegerField(default=5)
    duration_hours = models.PositiveIntegerField(blank=True,null=True,verbose_name="Hours If One day Tour")
    discount = models.IntegerField(verbose_name="Discount %", default=15)
    #discounted_price = models.IntegerField(default=230)
    #savings = models.IntegerField(default=230)
    tour_type = models.CharField(max_length=100, choices=TOUR_TYPE, default='Group Tour')
    new_activity = models.ManyToManyField(NewActivity)
    accommodation = models.CharField(max_length=255, default='Guest House & Hotel')
    transport = models.CharField(max_length=150, default='Flight')
    age_range = models.CharField(max_length=100, default='6 to 79 years old')
    fix_departure = models.BooleanField(default=False)
    rating = models.IntegerField(choices=((1, 1),
                                          (2, 2),
                                          (3, 3),
                                          (4, 4),
                                          (5, 5))
                                 )

    image = models.ImageField(blank=True, verbose_name="Thumbnail Image-Vertical")

    content =RichTextField()
    highlights = RichTextField()
    inclusions = RichTextField()
    exclusions = RichTextField()
    # itinerary = models.ManyToManyField(Itinerary)
    itinerary_text = RichTextField()
    faqs = RichTextField(blank=True)
    image_1= models.ImageField(blank=True,null = True,verbose_name="Image-Horizontal")
    image_2= models.ImageField(blank=True,null = True,verbose_name="Image-Square")
    image_3= models.ImageField(blank=True,null = True,verbose_name="Image-Sqaure")
    date_created = models.DateField()

    def __str__(self):
        return self.package_name

My views:

class PackageSearchAPi(ListAPIView):
    queryset = Package.objects.all().order_by('package_name')
    serializer_class = PackageSerializer

    def get(self, request, *args, **kwargs):

        search = self.request.query_params.get('search',None)
        if search is not None:
            qs = Package.objects.filter(Q(destination__name__icontains=search)|
                                        Q(destination__continent__icontains=search)|
                                        Q(package_name__icontains=search)|
                                        Q(city__icontains=search)).disctinct()

        else:
            qs = Package.objects.values('id','destination','package_name','city')

        serializer = PackageSerializer(qs,many=True)
        return Response(serializer.data,status=200)

My serializers:

class PackageSerializer(serializers.ModelSerializer):

    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]

        depth = 1

Here I checked the code and nothing seems to be wrong in any part but keeps getting the same above error.

Traceback:

File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception
    raise exc
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\Saroj\Desktop\TravelCRM\apps\packages\views.py", line 251, in get
    return Response(serializer.data,status=200)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 760, in data
    ret = super().data
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 260, in data
    self._data = self.to_representation(self.instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 677, in to_representation
    return [
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 678, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 529, in to_representation
    ret[field.field_name] = field.to_representation(attribute)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\serializers.py", line 516, in to_representation
    attribute = field.get_attribute(instance)
  File "C:\Users\Saroj\Desktop\TravelCRM\myvenv\lib\site-packages\rest_framework\fields.py", line 487, in get_attribute
    raise type(exc)(msg)
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `NestedSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'name'.

Body:
For nested relations you have to define nested serializer

class DestinationSerializer(serializers.Serializer):
    name = serializers.CharField()
    top = serializers.BooleanField()
    continent = serializers.CharField()

class PackageSerializer(serializers.ModelSerializer):
    destination = DestinationSerializer()
    class Meta:
        model = Package
        fields = ['id', 'operator','destination', 'package_name', 'duration', 'featured', 'price','price_2', 'discount',
                   'city', 'tour_type','new_activity', 'accommodation', 'transport', 'age_range',
                   'fix_departure', 'rating', 'image', 'date_created', ]


问:
Does React Native works well on MacBook M1?
I have to buy MacBook Air with M1. As I see, it supports react native (npm, expo etc.). Yes?

Edited 11.02: ok, solved. Thank you all!

答: Yes. I use M1 MacBook Pro and develop React Native using Vscode. Everything works perfectly well.</p>


问:
CTest.exe on Windows splits PATH environment property on semicolons
I have a Jenkins pipeline which runs tests on a Windows VM using ctest.exe in a bat script, like this:

```<code>// Run all tests in parallel, timeout after 1 hour, exclude any tests needing opengl
bat ''' "C:/Program Files/CMake/bin/ctest.exe" --timeout 3600 --verbose -C Release -j4 -E "(_gl)|(GL)" '''
</code>```

In my CTest setup, I'm setting the environment using the code below. I have already been looking around and found that I need to escape the backslashes in the PATH to avoid CMake interpreting it as a list, but that doesn't seem to make it all the way through to the end:

```<code>set(test_dll_path)
set(PATH_STRING "")

# Add the paths I want to a list
list(APPEND test_dll_path "${PROJECT_SOURCE_DIR}/../bin64")
list(APPEND test_dll_path "${PROJECT_SOURCE_DIR}/../bin64/plugins")

# Concatenate that list and convert it to a string
cmake_path(APPEND_STRING test_dll_path ";$ENV{PATH}")
cmake_path(CONVERT "${test_dll_path}" TO_NATIVE_PATH_LIST test_dll_path NORMALIZE)

# Escape the backslashes to avoid CTest interpreting it as a list
string(REPLACE ";" "\\;" test_dll_path "${test_dll_path}")

# Join it to the existing path using more escaped backslashes
list(JOIN test_dll_path "\\;" PATH_STRING)

# Assign the environment to blank first ("append_string" only works if the property existed already)
set_property( TEST ${TEST_TARGET} PROPERTY ENVIRONMENT "" )
set_property( TEST ${TEST_TARGET} APPEND_STRING PROPERTY ENVIRONMENT "PATH=${PATH_STRING}" )

# This comes through as one full string when printed as a message, but still interpreted as a list when CTest uses it later :(
message(DEBUG "Test ${TEST_TARGET} PATH = \"${PATH_STRING}\"")
</code>```

Then, when I run the jenkins pipeline, the --verbose setting prints the environment for the test.
When this happens, the PATH is split on each semicolon and the tests act as though only the first item is in the PATH:

```<code>1: Test command: C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\Tests\tut.exe "-cppunitreport"
1: Environment variables:
1:  PATH=C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\bin64
1:  C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\bin64\plugins
1:  C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
1:  C:\Program Files (x86)\MSBuild\14.0\bin\amd64
1:  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64
1:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319

...etc
</code>```

答:
From a week of searching I hadn't seen this, but a colleague just sent me this answer:
How do I make a list in CMake with the semicolon value?

So the answer is, if in doubt, keep adding more backslashes. I needed three when joining the path up, like so:

```<code># Escape the backslashes to avoid CTest interpreting it as a list
string(REPLACE ";" "\\\;" test_dll_path "${test_dll_path}")

# Join it to the existing path using more escaped backslashes
list(JOIN test_dll_path "\\\;" PATH_STRING)
</code>```

Body:
I have a Jenkins pipeline which runs tests on a Windows VM using ctest.exe in a bat script, like this:

// Run all tests in parallel, timeout after 1 hour, exclude any tests needing opengl
bat ''' "C:/Program Files/CMake/bin/ctest.exe" --timeout 3600 --verbose -C Release -j4 -E "(_gl)|(GL)" '''

In my CTest setup, I'm setting the environment using the code below. I have already been looking around and found that I need to escape the backslashes in the PATH to avoid CMake interpreting it as a list, but that doesn't seem to make it all the way through to the end:

set(test_dll_path)
set(PATH_STRING "")

# Add the paths I want to a list
list(APPEND test_dll_path "${PROJECT_SOURCE_DIR}/../bin64")
list(APPEND test_dll_path "${PROJECT_SOURCE_DIR}/../bin64/plugins")

# Concatenate that list and convert it to a string
cmake_path(APPEND_STRING test_dll_path ";$ENV{PATH}")
cmake_path(CONVERT "${test_dll_path}" TO_NATIVE_PATH_LIST test_dll_path NORMALIZE)

# Escape the backslashes to avoid CTest interpreting it as a list
string(REPLACE ";" "\\;" test_dll_path "${test_dll_path}")

# Join it to the existing path using more escaped backslashes
list(JOIN test_dll_path "\\;" PATH_STRING)

# Assign the environment to blank first ("append_string" only works if the property existed already)
set_property( TEST ${TEST_TARGET} PROPERTY ENVIRONMENT "" )
set_property( TEST ${TEST_TARGET} APPEND_STRING PROPERTY ENVIRONMENT "PATH=${PATH_STRING}" )

# This comes through as one full string when printed as a message, but still interpreted as a list when CTest uses it later :(
message(DEBUG "Test ${TEST_TARGET} PATH = \"${PATH_STRING}\"")

Then, when I run the jenkins pipeline, the --verbose setting prints the environment for the test.
When this happens, the PATH is split on each semicolon and the tests act as though only the first item is in the PATH:

1: Test command: C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\Tests\tut.exe "-cppunitreport"
1: Environment variables:
1:  PATH=C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\bin64
1:  C:\jenkins\workspace\ows-IncrementalBuild-Test_PR-856\source\bin64\plugins
1:  C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow
1:  C:\Program Files (x86)\MSBuild\14.0\bin\amd64
1:  C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\amd64
1:  C:\Windows\Microsoft.NET\Framework64\v4.0.30319

...etc

Body:
From a week of searching I hadn't seen this, but a colleague just sent me this answer:
How do I make a list in CMake with the semicolon value?

So the answer is, if in doubt, keep adding more backslashes. I needed three when joining the path up, like so:

# Escape the backslashes to avoid CTest interpreting it as a list
string(REPLACE ";" "\\\;" test_dll_path "${test_dll_path}")

# Join it to the existing path using more escaped backslashes
list(JOIN test_dll_path "\\\;" PATH_STRING)


答:
The map part covers every item in arr1, so you can add it as is or merge with the ones both in arr1 and arr2. Then you need a final pass to add those that are in arr2 but not in arr1

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

const merge = (a1,a2) => {

return a1.map( (x) => {
  const y = a2.find( item => x.name === item.name);
  if (y) {
    return Object.assign({},x,y);
  } else
    return x
}).concat(a2.filter(item => a1.every( x => x.name !== item.name)));

}

arr3 = merge(arr1, arr2)

console.log(arr3)```

Title: how to merge two arrays of objects in javascript?

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]


问:
Fastify: avoiding writing boiler plate handler in every routes
Is there a possibility in Fastify to avoid writing the similar handler always?

My handler looks like (a proxy sort of):

handler: async (request, reply) => {
      reply.from(proxyMap[request.url]);
      return reply;
}
```
<p>where the <code>proxyMap</code> is just a mapping of my proxy routes to target/upstream route path. However the handler is always same.</p>
<p>Say a sample <code>proxyMap</code> content can be:</p>
<pre class="lang-js prettyprint-override"><code>  const proxyMap = {
      "/api/path1/proxy1" : "/api/backend/api1",
      "/api/path2/proxy2" : "/api/backend/api2",
          ....
  };
</code>```

How can I move to handler somewhere common (say in some lifecycle hook or somewhere appropriate) such that every route I need not to write it. Like when I will write the route, it will be executed based on the proxyMap look up.

Is there a way in fastify to achieve that?

答:
You can automate it with some coding:

async function handler(request, reply) {
  reply.from(proxyMap[request.url])
  return reply
}

const proxyMap = {
  '/api/path1/proxy1': '/api/backend/api1',
  '/api/path2/proxy2': '/api/backend/api2',
}

Object.keys(proxyMap).forEach((url) => {
  fastify.get(url, { handler })
})
```

Body:
Is there a possibility in Fastify to avoid writing the similar handler always?

My handler looks like (a proxy sort of):

handler: async (request, reply) => {
      reply.from(proxyMap[request.url]);
      return reply;
}

where the proxyMap is just a mapping of my proxy routes to target/upstream route path. However the handler is always same.

Say a sample proxyMap content can be:

  const proxyMap = {
      "/api/path1/proxy1" : "/api/backend/api1",
      "/api/path2/proxy2" : "/api/backend/api2",
          ....
  };

How can I move to handler somewhere common (say in some lifecycle hook or somewhere appropriate) such that every route I need not to write it. Like when I will write the route, it will be executed based on the proxyMap look up.

Is there a way in fastify to achieve that?