问:
Binding the Duration property of an animation in Silverlight
I have a DoubleAnimation that I want to bind its From, To and Duration Properties so they would change smoothly.

The binding of From and To works great, changes them smoothly, but the changes of the Duration are simply being ignored.

For debugging, I made a button that on click calls the Stop and Begin methods of the containing StoryBoard, and the animation started from the beginning with the correct duration. Also I checked and saw that the Duration property of the animation is actually being updated everytime, so the change is just being ignored by the animation. (Unlike the From and To that really react smoothly.)

Tried the same in WPF and got the same results, here's a snippet:

```<code>        <Canvas>
        <Canvas.Triggers>
            <EventTrigger RoutedEvent="Canvas.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="Story">
                        <DoubleAnimation x:Name="Anime"
                                         Duration="{Binding Duration}"
                                         RepeatBehavior="Forever"
                                         Storyboard.TargetName="Text1"
                                         Storyboard.TargetProperty="(Canvas.Left)"
                                         From="0"
                                         To="400"
                                         />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Canvas.Triggers>
        <TextBlock Text="Hello" Name="Text1"/>
    </Canvas>
</code>```

I would really appreciate an explanation why isn't this working and any workarounds that would make the binding work with a smooth transition.

Also, the actual final goal of mine is to have the TextBlock moving in constant speed despite changes in From and To. So if there is another way of achieving this, it would be even better.

Thanks.

答:
There are two concern: how is your binding source (ViewModel) written, and did you update your datacontext. Here is my code and it works.

the MainPage.xaml:

```<code><Canvas>
    <Canvas.Triggers>
        <EventTrigger RoutedEvent="Canvas.Loaded">
            <BeginStoryboard>
                <Storyboard x:Name="Story">
                    <DoubleAnimation x:Name="Anime"
                                     Duration="{Binding}"
                                     RepeatBehavior="Forever"
                                     Storyboard.TargetName="Text1"
                                     Storyboard.TargetProperty="(Canvas.Left)"
                                     From="0"
                                     To="400"
                                     />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Canvas.Triggers>
    <TextBlock Text="Hello" Name="Text1"/>
    <Button Content="Change" Margin="0, 100, 0, 0" Click="Button_Click" />
</Canvas>
</code>```

the MainPage.xaml.cs:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {
        AnimVM vm = new AnimVM();
        double dur = 5;

        public MainPage()
        {
            InitializeComponent();

            vm.Duration = new Duration(TimeSpan.FromSeconds(dur));

            this.DataContext = vm.Duration;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dur += 5;
            vm.Duration = new Duration(TimeSpan.FromSeconds(dur));
            this.DataContext = vm.Duration; // don't forget this line
        }
    }

    public class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        protected ViewModelBase()
        {
        }

        protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            //this.VerifyPropertyName(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        public void Dispose()
        {
            this.OnDispose();
        }

        protected virtual void OnDispose()
        {
        }
    }

    public class AnimVM : ViewModelBase
    {
        private Duration _duration = new Duration(TimeSpan.FromSeconds(5));
        public Duration Duration
        {
            get { return _duration; }
            set
            {
                if (object.ReferenceEquals(this._duration, value)) return;

                this._duration = value;
                base.OnPropertyChanged("Duration");
            }
        }
    }
}
</code>```

Body:
I have a DoubleAnimation that I want to bind its From, To and Duration Properties so they would change smoothly.

The binding of From and To works great, changes them smoothly, but the changes of the Duration are simply being ignored.

For debugging, I made a button that on click calls the Stop and Begin methods of the containing StoryBoard, and the animation started from the beginning with the correct duration. Also I checked and saw that the Duration property of the animation is actually being updated everytime, so the change is just being ignored by the animation. (Unlike the From and To that really react smoothly.)

Tried the same in WPF and got the same results, here's a snippet:

        <Canvas>
        <Canvas.Triggers>
            <EventTrigger RoutedEvent="Canvas.Loaded">
                <BeginStoryboard>
                    <Storyboard x:Name="Story">
                        <DoubleAnimation x:Name="Anime"
                                         Duration="{Binding Duration}"
                                         RepeatBehavior="Forever"
                                         Storyboard.TargetName="Text1"
                                         Storyboard.TargetProperty="(Canvas.Left)"
                                         From="0"
                                         To="400"
                                         />
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger>
        </Canvas.Triggers>
        <TextBlock Text="Hello" Name="Text1"/>
    </Canvas>

I would really appreciate an explanation why isn't this working and any workarounds that would make the binding work with a smooth transition.

Also, the actual final goal of mine is to have the TextBlock moving in constant speed despite changes in From and To. So if there is another way of achieving this, it would be even better.

Thanks.

Body:
There are two concern: how is your binding source (ViewModel) written, and did you update your datacontext. Here is my code and it works.

the MainPage.xaml:

<Canvas>
    <Canvas.Triggers>
        <EventTrigger RoutedEvent="Canvas.Loaded">
            <BeginStoryboard>
                <Storyboard x:Name="Story">
                    <DoubleAnimation x:Name="Anime"
                                     Duration="{Binding}"
                                     RepeatBehavior="Forever"
                                     Storyboard.TargetName="Text1"
                                     Storyboard.TargetProperty="(Canvas.Left)"
                                     From="0"
                                     To="400"
                                     />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger>
    </Canvas.Triggers>
    <TextBlock Text="Hello" Name="Text1"/>
    <Button Content="Change" Margin="0, 100, 0, 0" Click="Button_Click" />
</Canvas>

the MainPage.xaml.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace SilverlightApplication
{
    public partial class MainPage : UserControl
    {
        AnimVM vm = new AnimVM();
        double dur = 5;

        public MainPage()
        {
            InitializeComponent();

            vm.Duration = new Duration(TimeSpan.FromSeconds(dur));

            this.DataContext = vm.Duration;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            dur += 5;
            vm.Duration = new Duration(TimeSpan.FromSeconds(dur));
            this.DataContext = vm.Duration; // don't forget this line
        }
    }

    public class ViewModelBase : INotifyPropertyChanged, IDisposable
    {
        protected ViewModelBase()
        {
        }

        protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            //this.VerifyPropertyName(propertyName);

            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                var e = new PropertyChangedEventArgs(propertyName);
                handler(this, e);
            }
        }

        public void Dispose()
        {
            this.OnDispose();
        }

        protected virtual void OnDispose()
        {
        }
    }

    public class AnimVM : ViewModelBase
    {
        private Duration _duration = new Duration(TimeSpan.FromSeconds(5));
        public Duration Duration
        {
            get { return _duration; }
            set
            {
                if (object.ReferenceEquals(this._duration, value)) return;

                this._duration = value;
                base.OnPropertyChanged("Duration");
            }
        }
    }
}


来源: stackexchange

问:
Determine number of input neurons in image segmentation neural network using fastai?
Hello I am new to neural networks and specifically layers and neurons. I am doing image segmentation project were I have 200 input images and have labeled correctly. In fastai you are able to use a pre-trained model for transfer learning.I have finished training, used learn.summarry. I am confused on how I can determine the number of neurons of in the input layer( initial data)? I've believe it has something to with the shape but I am not sure how to find out the number of input neurons in input layer. May someone help me please! Thank You!</p>

```<code>
ImageDataBunch;

Train: LabelList (160 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/Umes2020/JPEGImages;

Valid: LabelList (40 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/Umes2020/JPEGImages;

</code>```

答:
I am assuming you meant the number of channels in the input since the number of neurons of the first layer is not limited by the image shape.

For a regular CNN, the number of channels is 3 (RGB).
For a fully connected network, the number of channels is 3*H*W since every pixel in every color channel (RGB) becomes 1 flattened channel.

ContentLicense: CC BY-SA 4.0

Body:
Hello I am new to neural networks and specifically layers and neurons. I am doing image segmentation project were I have 200 input images and have labeled correctly. In fastai you are able to use a pre-trained model for transfer learning.I have finished training, used learn.summarry. I am confused on how I can determine the number of neurons of in the input layer( initial data)? I've believe it has something to with the shape but I am not sure how to find out the number of input neurons in input layer. May someone help me please! Thank You!

ImageDataBunch;

Train: LabelList (160 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/Umes2020/JPEGImages;

Valid: LabelList (40 items)
x: SegmentationItemList
Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128),Image (3, 128, 128)
y: SegmentationLabelList
ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128),ImageSegment (1, 128, 128)
Path: /content/drive/My Drive/Umes2020/JPEGImages;


问:
How to Upload an Image to Django
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
```

<pre class="lang-py prettyprint-override"><code># forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]
</code>```

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)
```

<pre class="lang-py prettyprint-override"><code># views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")
</code>```

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}
```

<p>In the template, it appears as Pic object(1).
In the terminal, it appears as</p>

<blockquote>
  <p>Query set Pic: Pic object (1)</p>
</blockquote>

<p>Here's what I render to the template.</p>

<pre class="lang-py prettyprint-override"><code>def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)
</code>```

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```

答:
put parentheses after  ImageForm and add request.POST in ImageForm if it is Post request.

```<code>
def upload:
  form = ImageForm()
  if request.method == 'POST':
    # .is_valid checks the models parameters via forms method
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        print("succesful uploaded image")
        return redirect("/dashboard")
    else:
        print("Not a valid input from form....")
        messages.error(request,"Not a valid input")
return redirect("/dashboard")
</code>```

Also check maybe you haven't added url path for serving media files
so add these following lines in urls.py file of main project.

```<code>from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  # ..... all regular paths
]
if setting.DEBUG: # if true
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Check official documents here

Title: How to Upload an Image to Django

Body:
I have spent over three days on this. It appears that something saved to the db, but when I try to access it in the template, I can only get the object of the db. I can not access it. I believe it was not saved successfully because I don't see a media folder where it would be saved. This is what I have so far.

# settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), )
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# forms.py
from .models import Pic
from django import forms
class ImageForm(forms.ModelForm):
    class Meta:
        model= Pic
        fields= ["picture"]

# models.py
class Pic(models.Model):
    picture = models.ImageField(upload_to = 'media/', default = 'media/None/no-img.jpg', null=True, blank= True)

# views.py
def upload(request):
    form = ImageForm
    context = {}
    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    if request.method == 'POST':
        # .is_valid checks the models parameters via forms method
        form = ImageForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            print("succesful uploaded image")
            return redirect("/dashboard")
        else:
            print("Not a valid input from form....")
            messages.error(request,"Not a valid input")
    return redirect("/dashboard")

<form rule="form" class="border border--secondary" method="POST" action="/manageFile" enctype="multipart/form-data">
    {% csrf_token%}
    <input type="file" name = "update">
    <input type = "submit">
</form>
{% if pictures %}
    {% for pic in pictures%}

    {% endfor %}
{% endif%}

In the template, it appears as Pic object(1).
In the terminal, it appears as

Query set Pic: Pic object (1)

Here's what I render to the template.

def dash(request):
    try:
        _id = request.session['client']['id']
    except:
        return redirect("/loginPg")

    userBio = Bio.objects.get(userData = User.objects.get(id = request.session['client']['id']))
    print("its right here")
    theUploads = Pic.objects.all()
    print("This image object -", theUploads)

    content = {
        "title" : userBio.title,
        "qA" : userBio.quoteA,
        "qB" : userBio.quoteB,
        "desc" : userBio.desc,
        "authorA" : userBio.authorA,
        "authorB" : userBio.authorB,
        "pictures" : theUploads
    }

    return render(request, "GoEnigma/dashboard.html", content)

# urls.py
from django.conf.urls.static import static
from django.conf import settings
# urls []
if settings.DEBUG:
     urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Body:
put parentheses after  ImageForm and add request.POST in ImageForm if it is Post request.

def upload:
  form = ImageForm()
  if request.method == 'POST':
    # .is_valid checks the models parameters via forms method
    form = ImageForm(request.POST, request.FILES)
    if form.is_valid():
        form.save()
        print("succesful uploaded image")
        return redirect("/dashboard")
    else:
        print("Not a valid input from form....")
        messages.error(request,"Not a valid input")
return redirect("/dashboard")

Also check maybe you haven't added url path for serving media files
so add these following lines in urls.py file of main project.

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  # ..... all regular paths
]
if setting.DEBUG: # if true
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Check official documents here


问:
Python : Call list attribute from a list of defined attributes
I have a list with list operations, For example ["insert", "append"], For now I am doing like if list says insert then I am calling .insert.

Check below code

In [31]: list_ops = [ "insert" , "append" ]

In [32]: list1 = [ 1 , 3 , 5 ]

In [33]: if list_ops[0] == "insert" :
    ...:     list1.insert(3, 7)
    ...:

In [34]: list1
Out[34]: [1, 3, 5, 7]

In [35]: list1.list_ops[0](4, 9 )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-5db0dcceeac1> in <module>
----> 1 list1.list_ops[0](4, 9 )

AttributeError: 'list' object has no attribute 'list_ops'

In [36]:
```

How can I choose the operation from list_ops itself instead of doing if-else matching.

Thank you.

答:
You can't choose an operation from list_ops, because it's a list of strings, not of operations.  You need to choose the operation based on the string.  For instance:

```<code>list_ops = {
    "insert": list.insert,
    "append": list.append
}
</code>```

Now you can choose the operation based on the input string.  Can you take it from here?

Body:
I have a list with list operations, For example ["insert", "append"], For now I am doing like if list says insert then I am calling .insert.

Check below code

In [31]: list_ops = [ "insert" , "append" ]

In [32]: list1 = [ 1 , 3 , 5 ]

In [33]: if list_ops[0] == "insert" :
    ...:     list1.insert(3, 7)
    ...:

In [34]: list1
Out[34]: [1, 3, 5, 7]

In [35]: list1.list_ops[0](4, 9 )
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-35-5db0dcceeac1> in <module>
----> 1 list1.list_ops[0](4, 9 )

AttributeError: 'list' object has no attribute 'list_ops'

In [36]:

How can I choose the operation from list_ops itself instead of doing if-else matching.

Thank you.

Body:
You can't choose an operation from list_ops, because it's a list of strings, not of operations.  You need to choose the operation based on the string.  For instance:

list_ops = {
    "insert": list.insert,
    "append": list.append
}

Now you can choose the operation based on the input string.  Can you take it from here?


问:
How do I optimize a "latest sales" sql query?
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

```<code>create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)
</code>```

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

```<code>select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId
</code>```

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

```<code>create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)
</code>```

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
</code>```

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

```<code>select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId
</code>```

or

```<code>select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1
</code>```

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

```<code>select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId
</code>```

I tested this idea but the query optimizer still chooses to do a full table scan.

答: Does the optimizer do better if you partition by SalesmanID (with appropriate per-table index and CHECK constraint on the table)??</p>

ContentLicense: CC BY-SA 3.0

Body:
This query has become my nemesis over the past few years because I've never found a way to optimize it. Now my nemesis becomes your nemesis! :)

Consider the following table:

create table Sales (
  SaleId int identity(1,1) primary key,
  SalesmanId int not null,
  Amount smallmoney not null
)

For the sake of argument, assume that this table has 10^100 rows (business is brisk) and therefore a table scan is out of the question.

Now we want to determine the SaleId of each salesman's most recent sale. Simple enough, right? Here is the query for that:

select
  SalesmanId,
  max(SaleId) SaleId
from Sales
group by Sales.SalesmanId

When we run this query the query optimizer does a full table scan, which is expected because it has no way of knowing where each salesman's sales fall within the table. So let's help it out by adding the following index:

create unique nonclustered index IX_Sales on Sales
(
  SalesmanId asc,
  SaleId asc
)

Now it should be trivial (for a human, anyway) to find the most recent values because we use the values of the first column of the index to identify all possible salesmen and the last entries of the second column to locate each salesman's latest sale. Unfortunately, the query optimizer still does an index seek over the entire index (all 10^100 rows) in this case, so it takes just as long.

Interestingly, if we write the query to find the latest sale for a given salesman,

select max(SaleId)
from Sales
where SalesmanId = 1

the query optimizer uses an index seek on IX_Sales and gets it with one row of I/O. Even without IX_Sales, it does a clustered index scan that somehow gets it in one row of I/O (maybe using the table statistics?). But if we modify this to

select max(SaleId)
from Sales
where SalesmanId = 1
group by SalesmanId

or

select max(SaleId)
from Sales
group by SalesmanId
having SalesmanId = 1

we're back to a high row-count index seek over lots of rows (although less than if you'd omitted the filter altogether, again probably due to statistics).

So ... any ideas on how I could defeat my nemesis?

Update

Some have suggested joining against a table of possible SalesmanId values, like so

select Latest.*
from
(
  select
    SalesmanId,
    max(SaleId) SaleId
  from Sales
  group by SalesmanId
) Latest
inner join Salesmen on
  Salesmen.SalesmanId = Latest.SalesmanId

I tested this idea but the query optimizer still chooses to do a full table scan.


问:
python Each section below is a function that must implement, make sure the function's names and parameters match the documentation (Copy-Paste)
def productSum(x: int, y: int, z: int) -> int

This function should return:

The product of x and y, if the product of x and y is less than z.

Else it should return the sum of x and y, if the product of x and y is greater than or equal to z.

Example 1:
x = 5, y = 2, z = 9

Output: 7 = 5 + 2 because 5 * 2 > 9

Example 2:
x = 4, y = 3, z = 19

Output: 12 = 4 * 3 because 4 * 3 < 19

def functionSolver(function: callable)->str

You will be given a function as a parameter, the function you are given only accepts two number parameters and produces a float value. It is your job to figure out what mathematical operation the function you are given is performing by passing it many different parameters. The possible operations the function can perform are: add, subtract, multiply, and divide. The given function will only perform a single operation, it will not change after consecutive invocations. The function will execute the operation in the order the parameters are received. You must input your own values and test the expected responses to figure out the operation of the function. Once you have figured it out return the symbol of the operation (+, -, *, /).

Another way to explain what has to happen, your function will receive as a function a parameter lets call it f(x, y), and the output of f(x, y) is z. We know that x and y are numbers and you know that f(x, y) produces z, which is another number. Your job is to create a function that passes different numbers into f and evaluates the output z to find a pattern. The pattern you are looking for is to see if the function f is adding, subtracting, dividing or multiplying x and y. Once you find the pattern your function should return the mathematic symbol (+, -, *, /) that corresponds to function f’s operation. The return value should be a string.

Example:

Input: function

Internally you will do the following

Test:function(1, 1) == 2.0

Test: function(2, 3) == 5.0

Test: function(4,1) == 5.0

Output: '+'

def resultOverrider(x: int, y: int, op: str, override: callable)->int
This function will be given 2 values, x, and y, which will be integers. It will also have two optional values op and override. This function is expected to return an integer. Op will be a string representing a mathematical operation ('+', '-', '*', '/') to be performed between x and y. If op is not defined it should default to addition. Override is a function that accepts two integers and returns an integer as a value. If override is not defined it this function should return the result of x and y computed with the op value or there sum if op is not provided. If override is specified this function should always return the result of the invocation of override with x and y passed into it.

def nestedRemoval(text: str, leftPattern: str, rightPattern: str) -> str
You will be given three strings, the first string is a sentence known as text that contains at least one occurrence of leftPattern and rightPattern. Left pattern and right pattern are single characters strings that you are attempting to remove from the string. Your goal is to remove only the patterns when the left pattern has an equal number of corresponding right patterns. The patterns are removed in pairs only when there is a balanced number of left and right patterns. The patterns may be nested within the text and there is no guarantee that a left pattern will occur before the right pattern.

Example 1:

text = { { Muscat } } { } mecum tollgate } poultry quarrymen pantheon asteria

leftPattern =  {

rightPattern = }

return = Muscat     mecum tollgate } poultry quarrymen pantheon asteria

Example 2:

text = theretofore [ ] [ ] demography ] ] pirouetting morsel [ [ pesticide

leftPattern =  [

rightPattern = ]

return =. demography ] ] pirouetting morsel [ [ pesticide

Example 3:

text = ( castigate ) alfonso ( ) ) ) emitter sourdough ) taco ( schemata

leftPattern =  (

rightPattern = )

return = castigate  alfonso   ) ) emitter sourdough ) Lauren ( schemata

答:
For your first problem,

```<code>def productSum(x: int, y: int, z: int) -> int
    if x * y < z:     # Checks if the product of x and y is less than z
        return x * y  # Return the product
    else:
        return x + y  # Else return the sum
</code>```

For your second problem,

```<code>def functionSolver(function: callable)->str
    if function(2,6) == 8:
        return '+'
    elif function(2,6) == 12:
        return '*'
    elif abs(fucntion(2,6)) == 4:
        return '-'
    elif function(6,2) == 3 || function(2,6) == 3:
        return '/'
</code>```

For your third problem,

```<code>def resultOverrider(x: int, y: int, op: str = '+', override: callable = None)->int
    if override:
        return override(x, y)
    if op == '+':
        return x + y
    elif op == '-':
        return x - y
    elif op == '*':
        return x * y
    elif op == '/':
        return x / y
</code>```

Body:
For your first problem,

def productSum(x: int, y: int, z: int) -> int
    if x * y < z:     # Checks if the product of x and y is less than z
        return x * y  # Return the product
    else:
        return x + y  # Else return the sum

For your second problem,

def functionSolver(function: callable)->str
    if function(2,6) == 8:
        return '+'
    elif function(2,6) == 12:
        return '*'
    elif abs(fucntion(2,6)) == 4:
        return '-'
    elif function(6,2) == 3 || function(2,6) == 3:
        return '/'

For your third problem,

def resultOverrider(x: int, y: int, op: str = '+', override: callable = None)->int
    if override:
        return override(x, y)
    if op == '+':
        return x + y
    elif op == '-':
        return x - y
    elif op == '*':
        return x * y
    elif op == '/':
        return x / y


问:
Cypress assertion Equal and Greater than
how to write the assertion in cypress with greater than equal to.if my value = 5000.00 , and i have to write test case,if my value == 5000.00 than Pass and if my value >5000.00 than also pass, how to write it correctly to pass </p>

```<code>my_value= 5000.00
        expect(my_value).to.equal(5000.00)
        cy.wrap(my_value).should('be.greaterThan',5000.00 )
</code>```

答:
Refer here:

```<code>const my_value = 5000.00;

cy.wrap(my_value).should('be.gt', 4999.99); // greater than
cy.wrap(my_value).should('be.gte', 5000); // greater than equal to

cy.wrap(my_value).should('be.lt', 5000.1);// less than
cy.wrap(my_value).should('be.lte', 5000); // less than equal to
</code>```

When verifying from DOM element, we need to parse the value:

```<code>cy.get('div').invoke('text').then(parseFloat).should('be.gt', 10)
</code>```

Body:
how to write the assertion in cypress with greater than equal to.if my value = 5000.00 , and i have to write test case,if my value == 5000.00 than Pass and if my value >5000.00 than also pass, how to write it correctly to pass

my_value= 5000.00
        expect(my_value).to.equal(5000.00)
        cy.wrap(my_value).should('be.greaterThan',5000.00 )

Body:
Refer here:

const my_value = 5000.00;

cy.wrap(my_value).should('be.gt', 4999.99); // greater than
cy.wrap(my_value).should('be.gte', 5000); // greater than equal to

cy.wrap(my_value).should('be.lt', 5000.1);// less than
cy.wrap(my_value).should('be.lte', 5000); // less than equal to

When verifying from DOM element, we need to parse the value:

cy.get('div').invoke('text').then(parseFloat).should('be.gt', 10)


问:
show/hide tr on dropdown selection for a list in sharepoint
I have created a list in  sharepoint now in newform I'm trying to hide and show 3 tr alternatively when i click on dropdown value. for eg: I have 3 option in dropdown A, B, C and my tr have ids(A, B, C) click on A only A is there when B only B is there and when C only C is there. same for edit form how to achieve this?</p>

答:
Sample tested script for a previous thread( I can't remember the link), you could update the script based on your fields' definition.

SPUtility.js

```<code><script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="/siteassets/sputility.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            var employeetype = SPUtility.GetSPField('Employee Type');
            var showOrHideField = function () {
                var employeeValue = employeetype.GetValue();
                if (employeeValue == 'Existing Employee') {
                    SPUtility.GetSPField('Employee Name').Show();
                    SPUtility.GetSPField('Employee ID').Show();
                    SPUtility.GetSPField('Candidate Name').Hide();
                }
                else {
                    SPUtility.GetSPField('Employee Name').Hide();
                    SPUtility.GetSPField('Employee ID').Hide();
                    SPUtility.GetSPField('Candidate Name').Show();
                }
            }

            // run at startup (for edit form)
            showOrHideField();
            // make sure if the user changes the value we handle it
            $(employeetype.Dropdown).on('change', showOrHideField);
        });
</code>```

Body:
Sample tested script for a previous thread( I can't remember the link), you could update the script based on your fields' definition.

SPUtility.js

<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="/siteassets/sputility.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(function () {
            var employeetype = SPUtility.GetSPField('Employee Type');
            var showOrHideField = function () {
                var employeeValue = employeetype.GetValue();
                if (employeeValue == 'Existing Employee') {
                    SPUtility.GetSPField('Employee Name').Show();
                    SPUtility.GetSPField('Employee ID').Show();
                    SPUtility.GetSPField('Candidate Name').Hide();
                }
                else {
                    SPUtility.GetSPField('Employee Name').Hide();
                    SPUtility.GetSPField('Employee ID').Hide();
                    SPUtility.GetSPField('Candidate Name').Show();
                }
            }

            // run at startup (for edit form)
            showOrHideField();
            // make sure if the user changes the value we handle it
            $(employeetype.Dropdown).on('change', showOrHideField);
        });


问:
Different output shape at last layer and the predict
I have build a Keras sequencial model using a pretrained model with addition of some layers. The code is as below. Then tried to predict and expected prediction shape was number of (samples,16) but got the prrediction results as (samples,8). The code for model building and the shape printing are as below.

`

```<code>layer_output = base_model.get_layer(output_layer).output
x=layer_output
x = Dense(1024, activation='sigmoid',name='1024_out')(x)
x = Dense(512, activation='sigmoid', name='512_out')(x)
x = Dense(16, activation='sigmoid',name="final")(x)
model = Model(base_model.input, outputs=x)
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.load_weights(weight_path)
</code>```

The prediction shape andd the shape of last layer output
print("Pred ",model.predict(images[:2]).shape,"Last Layer:",model.layers[-1].output_shape)`
The output is Pred (2, 8) Last Layer: (None, 16)

答:
Got the answer to the above question/issue. The last layer was not sigmoid instead of softmax for the multi-class classification.
Changed

```<code>x = Dense(16, activation='sigmoid',name="final")(x)
</code>```

to

```<code>x = Dense(16, activation='softmax',name="final")(x)
</code>```

Body:
I have build a Keras sequencial model using a pretrained model with addition of some layers. The code is as below. Then tried to predict and expected prediction shape was number of (samples,16) but got the prrediction results as (samples,8). The code for model building and the shape printing are as below.

`

layer_output = base_model.get_layer(output_layer).output
x=layer_output
x = Dense(1024, activation='sigmoid',name='1024_out')(x)
x = Dense(512, activation='sigmoid', name='512_out')(x)
x = Dense(16, activation='sigmoid',name="final")(x)
model = Model(base_model.input, outputs=x)
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='mean_squared_error', optimizer=sgd)
model.load_weights(weight_path)

The prediction shape andd the shape of last layer output
print("Pred ",model.predict(images[:2]).shape,"Last Layer:",model.layers[-1].output_shape)`
The output is Pred (2, 8) Last Layer: (None, 16)

Body:
Got the answer to the above question/issue. The last layer was not sigmoid instead of softmax for the multi-class classification.
Changed

x = Dense(16, activation='sigmoid',name="final")(x)

to

x = Dense(16, activation='softmax',name="final")(x)


问:
Unable to connect PostgreSQL to remote database using pgAdmin
I installed PostgreSQL on my local server (Ubuntu) with IP 192.168.1.10.  Now, I'm trying to access the database from my client machine (Ubuntu) with IP 192.168.1.11 with pgAdmin.

I know I have to make changes in postgresql.conf and pg_hba.conf to allow the client to connect.  Could you please guide me?

答:
Connecting to PostgreSQL via SSH Tunneling

In the event that you don't want to open port 5432 to any traffic, or you don't want to configure PostgreSQL to listen to any remote traffic, you can use SSH Tunneling to make a remote connection to the PostgreSQL instance. Here's how:

Open PuTTY. If you already have a session set up to connect to the
EC2 instance, load that, but don't connect to it just yet. If you
don't have such a session, see this post.

Go to Connection > SSH > Tunnels

Enter 5433 in the Source Port field.

Enter 127.0.0.1:5432 in the Destination field.

Click the "Add" button.

Go back to Session, and save your session, then click "Open" to
connect.

This opens a terminal window. Once you're connected, you can leave
that alone.

Open pgAdmin and add a connection.

Enter localhost in the Host field and 5433  in the Port field.
Specify a Name for the connection, and the username and password.
Click OK when you're done.


问:
Mapping entities between two disparate company datasets
I have several datasets containing data about companies:
- entity_structure (columns: entity_id, parent_entity_id, ultimate_parent_id)
- entity_addresses (columns: address_id, entity_id, location_city, state, postal_code, zip, street, ...)
- vendor (columns: vendor_id, parent_vendor_id, top_vendor_id, cnt_children, orgtype_id, geo_id, name, email, ...)
- geo (columns: geo_id, zipcode, is_primary, latitude, longtitude, elevation, state, ...)
- entity_coverage (entity_id, name, proper_name, sic_code, industry_code, sector_code, iso, ...)

I need to automatically map entities between the datasets, for example, there may be a company named "Google" in one data set, and a company named "Google 123" in another. I need to be able to determine with a high enough confidence that those are the same entities. In most cases, the data does not share a unique key. In most cases, the data does not share a unique key.

Would named entity linking be the best approach here? Are there any Python examples on how to approach this problem?

答: Based on your example, Levenshtein Distance may help.</p>


问:
Set userform width from a module by looping through userforms
Been having a very frustrating problem that I can't seem to find a solution for anywhere - help would be greatly appreciated!

I know how to change the width of a userform from within the userform itself (Me.Width).

The problem is that I am writing a module that will format userforms dynamically. The module is passed a form and it does some manipulations on that form. So far everything works as long as I'm referring to objects on the form.

But I'm now trying to refer to the form itself, and when I try to change the width (of the form, not of a control on the form) I get the error: "Object doesn't support this property or method".

I've tried declaring it as both a UserForm and an Object and all of the other code works in both cases, but resizing the width doesn't. I can see in the immediate window that width isn't available, which is obviously why the code won't execute.

Here's the code that I've tried without succses:

```<code>Sub frmLoadLayoutTest()

frmLoadLayout frmTest
frmTest.Show

End Sub

Private Sub frmLoadLayout(frmActive As Object) 'Also tried (frmActive as UserForm)

'Setting the width of a control works
frmActive.Controls("labelTest").Width = 100

'Setting the width of the form itself doesn't work
frmActive.Width = 100

End Sub
</code>```

If anyone can provide an elegant solution, that would be fantastic. Alternatively, is there a way I can refer to the userform by name? (Something like Userform(frm1.name).Width = 100)

Thanks in advance!

答:
Try this:

```<code>Sub frmLoadLayoutTest()

    Dim frm As frmTest

    Set frm = New frmTest  '<<< create an instance of the form

    frmLoadLayout frm      '<<< pass in the instance
    frm.Show               '<<< show the instance

End Sub

Private Sub frmLoadLayout(frm As Object)
    With frm
        .Controls("labelTest").Width = 100
        .Width = 300
    End With
End Sub
</code>```

See also why it's good practice to avoid the "default instance" and create your own explicit instance of a form before using it:

https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/

Body:
Been having a very frustrating problem that I can't seem to find a solution for anywhere - help would be greatly appreciated!

I know how to change the width of a userform from within the userform itself (Me.Width).

The problem is that I am writing a module that will format userforms dynamically. The module is passed a form and it does some manipulations on that form. So far everything works as long as I'm referring to objects on the form.

But I'm now trying to refer to the form itself, and when I try to change the width (of the form, not of a control on the form) I get the error: "Object doesn't support this property or method".

I've tried declaring it as both a UserForm and an Object and all of the other code works in both cases, but resizing the width doesn't. I can see in the immediate window that width isn't available, which is obviously why the code won't execute.

Here's the code that I've tried without succses:

Sub frmLoadLayoutTest()

frmLoadLayout frmTest
frmTest.Show

End Sub

Private Sub frmLoadLayout(frmActive As Object) 'Also tried (frmActive as UserForm)

'Setting the width of a control works
frmActive.Controls("labelTest").Width = 100

'Setting the width of the form itself doesn't work
frmActive.Width = 100

End Sub

If anyone can provide an elegant solution, that would be fantastic. Alternatively, is there a way I can refer to the userform by name? (Something like Userform(frm1.name).Width = 100)

Thanks in advance!

Body:
Try this:

Sub frmLoadLayoutTest()

    Dim frm As frmTest

    Set frm = New frmTest  '<<< create an instance of the form

    frmLoadLayout frm      '<<< pass in the instance
    frm.Show               '<<< show the instance

End Sub

Private Sub frmLoadLayout(frm As Object)
    With frm
        .Controls("labelTest").Width = 100
        .Width = 300
    End With
End Sub

See also why it's good practice to avoid the "default instance" and create your own explicit instance of a form before using it:

https://rubberduckvba.wordpress.com/2017/10/25/userform1-show/


问:
NHibernate ThenFetchMany is retrieving duplicate children
I have a parent object with a child collection containing one element, the child collection contains a "grandchild" collection containing 3 elements.

I am loading the parent object from the database using NHibernate as follows

```<code>Parent parentObject = session.Query<Parent>()
    .FetchMany(x => x.Children)
    .ThenFetchMany(x => x.GrandChildren)
    .Where(x => x.Id = "someparentid")
    .Single();
</code>```

What I'm finding is that there are duplicate children objects (3 in total) attached to the parent object when there should be only one. (There are 3 grandchild objects correctly attached to each child.) Eager loading the children collection only works correctly.

Do you know how I can achieve loading of the full parent object without duplicate children?

答: I was able to use the answer here using QueryOver, it correctly loads the objects while generating efficient SQL (selects per table instead of one huge join).</p>

Body:
I have a parent object with a child collection containing one element, the child collection contains a "grandchild" collection containing 3 elements.

I am loading the parent object from the database using NHibernate as follows

Parent parentObject = session.Query<Parent>()
    .FetchMany(x => x.Children)
    .ThenFetchMany(x => x.GrandChildren)
    .Where(x => x.Id = "someparentid")
    .Single();

What I'm finding is that there are duplicate children objects (3 in total) attached to the parent object when there should be only one. (There are 3 grandchild objects correctly attached to each child.) Eager loading the children collection only works correctly.

Do you know how I can achieve loading of the full parent object without duplicate children?


问:
Click and scrape 'a href' links by class name using Selenium in Python
I have the following a href link with only a class identifier. I'm trying to have Selenium recursively click through each link, but Selenium isn't returning the proper page sources from each 'a href' links.

```<code><div class="row">
 <div class="item">
  ↳<a href /path/to/link/ class="link-box">
 <div class="item">
 <div class="item">
 <div class="item">
</code>```

What am I doing wrong here:

```<code>driver = webdriver.Chrome("/Users/me/Downloads/chromedriver", options=options)
driver.get("https://the_website")
link_box = driver.find_elements_by_class_name('link-box')

for i in range(len(link_box)):
  driver.execute_script("arguments[0].click();", link_box[i])
page_source = driver.page_source
pprint(page_source)
</code>```

答:
I wrote another code to do it.

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver = webdriver.Firefox(executable_path='geckodriver')
driver.get("url")
l=[]
for a in driver.find_elements_by_class_name('link-box'):
    link = a.get_attribute('href')
    l.append(link)
print(l)

for b in range(len(l)):
    driver.execute_script("window.open('');")
    driver.switch_to.window(driver.window_handles[b+1])
    driver.get(l[b])
    print(l[b])
</code>```

First, it will take all the link which has class link-box. Then it will open all the links in new tabs. Otherwise, there might be an error. I did this with Firefox but if you are doing with Chrome comment line 4 and uncomment line 3. Then give the right path.

Body:
I have the following a href link with only a class identifier. I'm trying to have Selenium recursively click through each link, but Selenium isn't returning the proper page sources from each 'a href' links.

  ↳

What am I doing wrong here:

driver = webdriver.Chrome("/Users/me/Downloads/chromedriver", options=options)
driver.get("https://the_website")
link_box = driver.find_elements_by_class_name('link-box')

for i in range(len(link_box)):
  driver.execute_script("arguments[0].click();", link_box[i])
page_source = driver.page_source
pprint(page_source)

Body:
I wrote another code to do it.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver = webdriver.Firefox(executable_path='geckodriver')
driver.get("url")
l=[]
for a in driver.find_elements_by_class_name('link-box'):
    link = a.get_attribute('href')
    l.append(link)
print(l)

for b in range(len(l)):
    driver.execute_script("window.open('');")
    driver.switch_to.window(driver.window_handles[b+1])
    driver.get(l[b])
    print(l[b])

First, it will take all the link which has class link-box. Then it will open all the links in new tabs. Otherwise, there might be an error. I did this with Firefox but if you are doing with Chrome comment line 4 and uncomment line 3. Then give the right path.


问:
what does parameter before method means in asp.net core?
I am using asp.net core 3, in a video tutorial I see use [parameter]. I want to know whats its name and whats its application?

what does [parameter] before method means?

```<code> [parameter]
 public int incrementgap{ get; set; } = 1;

    void inccount()

    { currentCount+=incrementgap; }
</code>```

答:
[Parameter] is used to mark the component parameters that can be set when the component is used in another page.

Reference:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.1#component-parameters

For more detailed exlpanation,in this code below:

```<code><div class="panel panel-default">
    <div class="panel-heading">@Title</div>
    <div class="panel-body">@ChildContent</div>

    <button class="btn btn-primary" @onclick="OnClick">
        Trigger a Parent component method
    </button>
</div>

@code {
    public string Title { get; set; }

    public RenderFragment ChildContent { get; set; }

    public EventCallback<MouseEventArgs> OnClick { get; set; }
}
</code>```

If you do not add [Parameter] attribute, those are just public properties that can't be set from other pages.That is to say the following line would be invalid :

```<code><ChildComponent Title="Panel Title from Parent" />
</code>```

The correct way should be:

```<code><div class="panel panel-default">
    <div class="panel-heading">@Title</div>
    <div class="panel-body">@ChildContent</div>

    <button class="btn btn-primary" @onclick="OnClickCallback">
        Trigger a Parent component method
    </button>
</div>

@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}
</code>```

Then it allows you could set the parameters whenever we use that component:

```<code><ChildComponent Title="Panel Title from Parent"
                OnClickCallback="@ShowMessage">
    Content of the child component is supplied
    by the parent component.
</ChildComponent>
</code>```

Body:
I am using asp.net core 3, in a video tutorial I see use [parameter]. I want to know whats its name and whats its application?

what does [parameter] before method means?

 [parameter]
 public int incrementgap{ get; set; } = 1;

    void inccount()

    { currentCount+=incrementgap; }

Body:
[Parameter] is used to mark the component parameters that can be set when the component is used in another page.

Reference:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.1#component-parameters

For more detailed exlpanation,in this code below:

<div class="panel panel-default">
    <div class="panel-heading">@Title</div>
    <div class="panel-body">@ChildContent</div>

    <button class="btn btn-primary" @onclick="OnClick">
        Trigger a Parent component method
    </button>
</div>

@code {
    public string Title { get; set; }

    public RenderFragment ChildContent { get; set; }

    public EventCallback<MouseEventArgs> OnClick { get; set; }
}

If you do not add [Parameter] attribute, those are just public properties that can't be set from other pages.That is to say the following line would be invalid :

<ChildComponent Title="Panel Title from Parent" />

The correct way should be:

<div class="panel panel-default">
    <div class="panel-heading">@Title</div>
    <div class="panel-body">@ChildContent</div>

    <button class="btn btn-primary" @onclick="OnClickCallback">
        Trigger a Parent component method
    </button>
</div>

@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    [Parameter]
    public EventCallback<MouseEventArgs> OnClickCallback { get; set; }
}

Then it allows you could set the parameters whenever we use that component:

<ChildComponent Title="Panel Title from Parent"
                OnClickCallback="@ShowMessage">
    Content of the child component is supplied
    by the parent component.
</ChildComponent>


问:
g++ warning when using optional 'struct' keyword
If I write this program:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it with:

```<code>g++ main.cxx -Wall -Wextra
</code>```

It gives me this warning:

```<code>main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]
</code>```

However, if I take out the struct keyword after the new keyword:

```<code>#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}
</code>```

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

答:
Just to post the minimal code that does and does not illustrate the problem:

```<code>namespace N {
struct A {};
}

struct B {};

int main() {
    struct N::A * a  = new struct N::A; // problem
    struct B * b  = new struct B;       // ok
}
</code>```

Personally, I think this is a small GCC bug, but I am not wise in the myriad ways of namespaces.

Body:
If I write this program:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new struct foo::bar;
    delete a;
    return 0;
}

and compile it with:

g++ main.cxx -Wall -Wextra

It gives me this warning:

main.cxx: In function ‘int main()’:
main.cxx:10:39: warning: declaration ‘struct foo::bar’ does not declare anything [enabled by default]

However, if I take out the struct keyword after the new keyword:

#include <iostream>

namespace foo {
    struct bar {
        int x;
    };
}

int main (void) {
    struct foo::bar *a = new foo::bar;
    delete a;
    return 0;
}

and compile it the same way, g++ outputs no warnings.  Why does g++ output that warning if I use the struct keyword?

Body:
Just to post the minimal code that does and does not illustrate the problem:

namespace N {
struct A {};
}

struct B {};

int main() {
    struct N::A * a  = new struct N::A; // problem
    struct B * b  = new struct B;       // ok
}

Personally, I think this is a small GCC bug, but I am not wise in the myriad ways of namespaces.


问:
How to add 5 second waiting in url refer script?
I have url redirection script or url refer script.

I want to add 5 second waiting and then url redirect to desired url.

```<code> <script>
 var url_index = window.location.href.indexOf('url=');
 if (url_index != -1)
 {
    url_go = window.location.href;
    url_go = url_go.substring(url_index + 4);
    //document.write(url_go);
    window.location.href = url_go;
 }
 var $_ = function(x){if(!document.getElementById){return;} else{ return document.getElementById(x);}}
 </script>
</code>```

Output is  http://transistortechnology.blogspot.com?url=http://imgur.com

When I open above url then it redirect suddenly, but I want add 5 second wait.

Is it possible in above script code.

I put that script in blogger header section

答:
```<code><script>
   var count = 15; // Number of seconds to wait
   var counter; // Handle for the countdown event.

   function start() {
    counter = setInterval(timer, 1000);
   }

   function timer() {
    // Show the number of remaining seconds on the web page.
    var output = document.getElementById("displaySeconds");
    output.innerHTML = count;

    // Decrease the remaining number of seconds by one.
    count--;

    // Check if the counter has reached zero.
    if (count < 0) { // If the counter has reached zero...
     // Stop the counter.
     clearInterval(counter);

     // Start the download.
     window.location.href = "URL to open";
//if you want to open in new window then use window.open(url);
     return;
    }
   }

   window.addEventListener("load", start, false);
  </script>

  <div>
  Your download will begin in <span id="displaySeconds">15</span> seconds.<br />
</div>
</code>```

Thanks to technovedant for this script. I found this at his blog

Body:
I have url redirection script or url refer script.

I want to add 5 second waiting and then url redirect to desired url.

Output is  http://transistortechnology.blogspot.com?url=http://imgur.com

When I open above url then it redirect suddenly, but I want add 5 second wait.

Is it possible in above script code.

I put that script in blogger header section

Body:
<script>
   var count = 15; // Number of seconds to wait
   var counter; // Handle for the countdown event.

   function start() {
    counter = setInterval(timer, 1000);
   }

   function timer() {
    // Show the number of remaining seconds on the web page.
    var output = document.getElementById("displaySeconds");
    output.innerHTML = count;

    // Decrease the remaining number of seconds by one.
    count--;

    // Check if the counter has reached zero.
    if (count < 0) { // If the counter has reached zero...
     // Stop the counter.
     clearInterval(counter);

     // Start the download.
     window.location.href = "URL to open";
//if you want to open in new window then use window.open(url);
     return;
    }
   }

   window.addEventListener("load", start, false);
  </script>

  <div>
  Your download will begin in <span id="displaySeconds">15</span> seconds.<br />
</div>

Thanks to technovedant for this script. I found this at his blog


问:
Firefox and Chrome return value of date toISOstring() is different
There appears to be a difference in the ISO String representation of a date object in Chrome and Firefox. If one runs the below sample code in Chrome and Firefox, different results are obtained:

```<code>new Date(  "1-Nov-2010 00:00 UTC").toISOString();
</code>```

Firefox: -002010-11-01T00:00:00.000Z

Chrome: 2010-11-01T00:00:00.000Z

What is -00 and why does Firefox behave differently to Chrome?

答: It's just a non-standard date format. Firefox is parsing it and sees "oh, you want the year -2010", Chrome seems to parse it a bit better, but I'd just suggest not using that particular string format for the dates.

Body:
There appears to be a difference in the ISO String representation of a date object in Chrome and Firefox. If one runs the below sample code in Chrome and Firefox, different results are obtained:

new Date(  "1-Nov-2010 00:00 UTC").toISOString();

Firefox: -002010-11-01T00:00:00.000Z

Chrome: 2010-11-01T00:00:00.000Z

What is -00 and why does Firefox behave differently to Chrome?


问:
How do I pass a visual range to a function without numbers or using :command in vim?
How do I pass a visual selection to a function from a script and NOT command line / mapping. I was wondering if something like this was possible? Or if there is a function that gets a range ?

What I want:

```<code>:call LowerToUpper('<,'>)
:call LowerToUpper(GetVisualRange())
</code>```

NOT THIS

```<code>:call LowerToUpper(1,5)
command! -range Edit call LowerToUpper(<line1>,<line2>)
:'<,'>LowerToUpper
</code>```

Here is the function example:

```<code>function! LowerToUpper(first,last) abort
for lineno in range(a:first,a:last)
    let line = getline(lineno)
    let newLine= substitute(line, '\v(\w)','\U\1','g')
    call setline(lineno,newLine)
endfor
endfunction
</code>```

The solution might be a hack to make a function that returns the visual selection GetVisualSelection().

答:
You can have your function with range modifier.

```<code>function! LowerToUpper() abort range
    for lineno in range(a:firstline, a:lastline)
        let line = getline(lineno)
        let newLine = substitute(line, '\v(\w)','\U\1','g')
        call setline(lineno, newLine)
    endfor
endfunction

'<,'>call LowerToUpper()
</code>```

This mostly serves as a shortcut for passing line("'<") and line("'>") implicitly. The argument names a:firstline and a:lastline are fixed.

Body:
How do I pass a visual selection to a function from a script and NOT command line / mapping. I was wondering if something like this was possible? Or if there is a function that gets a range ?

What I want:

:call LowerToUpper('<,'>)
:call LowerToUpper(GetVisualRange())

NOT THIS

:call LowerToUpper(1,5)
command! -range Edit call LowerToUpper(<line1>,<line2>)
:'<,'>LowerToUpper

Here is the function example:

function! LowerToUpper(first,last) abort
for lineno in range(a:first,a:last)
    let line = getline(lineno)
    let newLine= substitute(line, '\v(\w)','\U\1','g')
    call setline(lineno,newLine)
endfor
endfunction

The solution might be a hack to make a function that returns the visual selection GetVisualSelection().

Body:
You can have your function with range modifier.

function! LowerToUpper() abort range
    for lineno in range(a:firstline, a:lastline)
        let line = getline(lineno)
        let newLine = substitute(line, '\v(\w)','\U\1','g')
        call setline(lineno, newLine)
    endfor
endfunction

'<,'>call LowerToUpper()

This mostly serves as a shortcut for passing line("'<") and line("'>") implicitly. The argument names a:firstline and a:lastline are fixed.


问:
textarea onresize not working
according to w3 schools <textarea> supports onresize however it is not working.

http://www.w3schools.com/jsref/event_onresize.asp

browsers tried:

Chrome 25.0.1364.172

Safari 6.0.3 (7536.28.10)

Firefox 19.0

FIDDLE: http://jsfiddle.net/btevfik/5abR3/

update

as i learned my lesson not to trust w3schools 100%, i found this

https://developer.mozilla.org/en-US/docs/DOM/element.onresize

答:
I like to stick to vanilla js for whatever reason. so here's a simple solution in vanilla:

<textarea
  onmousedown="storeDimensions(this)"
  onmouseup="onresizeMaybe(this)"
></textarea>

```

and for homework, use onmousemove to trigger the resize event instead of onmouseup (I didn't need that in my particular case).

:) hope it helps someone someday... seeing as how this question is now 5 years old.

Title: textarea onresize not working

Body:
I like to stick to vanilla js for whatever reason. so here's a simple solution in vanilla:

<textarea
  onmousedown="storeDimensions(this)"
  onmouseup="onresizeMaybe(this)"
></textarea>

<script>
  function storeDimensions(element){
    element.textWidth = element.offsetWidth;
    element.textHeight = element.offsetHeight;
    element.value = "is it gonna change? we don't know yet...";
  }

  function onresizeMaybe(element){
    if (element.textWidth===element.offsetWidth
     && element.textHeight===element.offsetHeight)
      element.value = "no change.\n";
    else element.value ="RESIZED!\n";

    element.value +=
       `width: ${element.textWidth}\n`
      +`height: ${element.textHeight}`;
  }
</script>

and for homework, use onmousemove to trigger the resize event instead of onmouseup (I didn't need that in my particular case).

:) hope it helps someone someday... seeing as how this question is now 5 years old.


问:
multiple files upload using same input name in django
i m having trouble in uploading multiple files with same input name:

```<code><input type=file name="file">
<input type=file name="file">
<input type=file name="file">
</code>```

at django side

```<code>print request.FILES :

<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>
</code>```

so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here?

答:
This code is the example</p>

```<code>    for f in request.FILES.getlist('myfile[]'):
        if request.method == 'POST' and f:
            myfile = f
            filesystem = FileSystemStorage()
            filename = filesystem.save(myfile.name, myfile)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i m having trouble in uploading multiple files with same input name:

<input type=file name="file">
<input type=file name="file">
<input type=file name="file">

at django side

print request.FILES :

<MultiValueDict: {u'file': [
<TemporaryUploadedFile: captcha_bg.jpg (image/jpeg)>,
<TemporaryUploadedFile: 001_using_git_with_django.mov (video/quicktime)>,
<TemporaryUploadedFile: ejabberd-ust.odt (application/vnd.oasis.opendocument.text)>
]}>

so all three files are under single request.FILES['file'] object . how do i handle for each files uploaded from here?

Body:
This code is the example

    for f in request.FILES.getlist('myfile[]'):
        if request.method == 'POST' and f:
            myfile = f
            filesystem = FileSystemStorage()
            filename = filesystem.save(myfile.name, myfile)


问:
Map the value of a new column by searching another dataframe
I have two dataframes: df_geo and df_event. I want to create two new columns in df_event.  The data frames resemble the following, although additional columns have been removed for the sake of simplicity:

```<code>data_geo =  [['040','01','000','00000','00000','00000','Alabama'],
             ['050','01','001','00000','00000','00000','Autauga County'],
             ['050','01','097','00000','00000','00000','Mobile County'],
             ['050','01','101','00000','00000','00000','Montgomery County'],
             ['050','01','115','00000','00000','00000','St. Clair County'],
             ['040','09','000','00000','00000','00000','Connecticut'],
             ['061','09','001','04720','00000','00000','Bethel town'],
             ['040','17','000','00000','00000','00000','Illinois'],
             ['061','17','109','05638','00000','00000','Bethel township'],
             ['050','17','163','00000','00000','00000','St. Clair County']]

dfgeo = pd.DataFrame(data_geo, columns = ['summary_level', 'state_fips','county_fips','subdivision_code_fips','place_code_fips','city_code_fips','area_name'])

df_geo.info()

RangeIndex: 43847 entries, 0 to 43846
Data columns (total 7 columns):
summary_level            43847 non-null object
state_fips               43847 non-null object
county_fips              43847 non-null object
subdivision_code_fips    43847 non-null object
place_code_fips          43847 non-null object
city_code_fips           43847 non-null object
area_name                43847 non-null object
</code>```

```<code>data_event = [['event_id','_','Alabama'],
              ['event_id','_','Connecticut'],
              ['event_id','Autauga County','Alabama'],
              ['event_id','Fairfield County','Connecticut'],
              ['event_id','Fairbanks North Star Borough','Alaska']]

df_event = pd.DataFrame(data_event, columns = ['event_id','county','state'])

df_event.info()

RangeIndex: 1261 entries, 0 to 1260
Data columns (total 3 columns):
event_id                1261 non-null object
county                   999 non-null object
state                   1261 non-null object
dtypes: object(3)

</code>```

GOAL to create a function that can take the county and state inputs from df_event and in order to create two new columns in the same dataframe.  The new columns are based on the values of state_fips and county_fips in df_geo.  An example of this would look like the following:

```<code>inputA fun('df_geo','Connecticut','Fairfield County'):

resultA = ['event_id','Connecticut','Fairfield County','09','001']
                                                       ^New columns

inputB fun('df_geo','Alaska','Fairbanks North Star Borough'):

resultB = ['event_id','Alaska','Fairbanks North Star Borough','02','090']
                                                              ^New columns

</code>```

This is a PROBLEM because I also need to use this function on a list of 1,200 (and growing) events the function would have to work within a lamba function or something else that can map it across the entire dataframe.

This is complicated by identical County names like "St. Clair County" that appear in several states.  Although their area_names are identical the value of state_fips will be different.

The state_fips of St. Clair Illinois is 17, the same as all other counties in Illinois and the state itself.  The state_fips of St. Clair Alabama is 01, the same as all other counties in Alabama, and so on...

I would like to use the same search and map function all the way down to city_code_fips.  At that level any search terms have to be exactly the same to avoid picking up "Bethel town" when I intend to find "Bethel township".  Exact inputs are also important because some states, like Louisiana, call their county level geographies by another name.

In df_event a '_' indicates that the county is unknown.

df_event['event_id'] is a unique string.  There are rows in the dataframe that are nearly identical but with different ids indicating that an event has occurred on multiple occasions.  This has no affect on the. state_fips or county_fips.

I know this is a multi step process but all help is appreciated. Thank you.

答:
If there are duplicates in use area_name column first remove them by DataFrame.drop_duplicates:

```<code>dfgeo = dfgeo.drop_duplicates('area_name')
</code>```

And then Series.map, what is faster like merge, so it should be preferable:

```<code>df_event['state_fips'] = df_event['state'].map(dfgeo.set_index('area_name')['state_fips'])
df_event['county_fips'] = df_event['county'].map(dfgeo.set_index('area_name')['county_fips'])
print (df_event)
  unique_str                        county        state state_fips county_fips
0   Event Id                             _      Alabama         01         NaN
1   Event Id                             _  Connecticut         09         NaN
2   Event Id                Autauga County      Alabama         01         001
3   Event Id              Fairfield County  Connecticut         09         001
4   Event Id  Fairbanks North Star Borough       Alaska         02         090
</code>```

Body:
I have two dataframes: df_geo and df_event. I want to create two new columns in df_event.  The data frames resemble the following, although additional columns have been removed for the sake of simplicity:

data_geo =  [['040','01','000','00000','00000','00000','Alabama'],
             ['050','01','001','00000','00000','00000','Autauga County'],
             ['050','01','097','00000','00000','00000','Mobile County'],
             ['050','01','101','00000','00000','00000','Montgomery County'],
             ['050','01','115','00000','00000','00000','St. Clair County'],
             ['040','09','000','00000','00000','00000','Connecticut'],
             ['061','09','001','04720','00000','00000','Bethel town'],
             ['040','17','000','00000','00000','00000','Illinois'],
             ['061','17','109','05638','00000','00000','Bethel township'],
             ['050','17','163','00000','00000','00000','St. Clair County']]

dfgeo = pd.DataFrame(data_geo, columns = ['summary_level', 'state_fips','county_fips','subdivision_code_fips','place_code_fips','city_code_fips','area_name'])

df_geo.info()

RangeIndex: 43847 entries, 0 to 43846
Data columns (total 7 columns):
summary_level            43847 non-null object
state_fips               43847 non-null object
county_fips              43847 non-null object
subdivision_code_fips    43847 non-null object
place_code_fips          43847 non-null object
city_code_fips           43847 non-null object
area_name                43847 non-null object

data_event = [['event_id','_','Alabama'],
              ['event_id','_','Connecticut'],
              ['event_id','Autauga County','Alabama'],
              ['event_id','Fairfield County','Connecticut'],
              ['event_id','Fairbanks North Star Borough','Alaska']]

df_event = pd.DataFrame(data_event, columns = ['event_id','county','state'])

df_event.info()

RangeIndex: 1261 entries, 0 to 1260
Data columns (total 3 columns):
event_id                1261 non-null object
county                   999 non-null object
state                   1261 non-null object
dtypes: object(3)

GOAL to create a function that can take the county and state inputs from df_event and in order to create two new columns in the same dataframe.  The new columns are based on the values of state_fips and county_fips in df_geo.  An example of this would look like the following:

inputA fun('df_geo','Connecticut','Fairfield County'):

resultA = ['event_id','Connecticut','Fairfield County','09','001']
                                                       ^New columns

inputB fun('df_geo','Alaska','Fairbanks North Star Borough'):

resultB = ['event_id','Alaska','Fairbanks North Star Borough','02','090']
                                                              ^New columns

This is a PROBLEM because I also need to use this function on a list of 1,200 (and growing) events the function would have to work within a lamba function or something else that can map it across the entire dataframe.

This is complicated by identical County names like "St. Clair County" that appear in several states.  Although their area_names are identical the value of state_fips will be different.

The state_fips of St. Clair Illinois is 17, the same as all other counties in Illinois and the state itself.  The state_fips of St. Clair Alabama is 01, the same as all other counties in Alabama, and so on...

I would like to use the same search and map function all the way down to city_code_fips.  At that level any search terms have to be exactly the same to avoid picking up "Bethel town" when I intend to find "Bethel township".  Exact inputs are also important because some states, like Louisiana, call their county level geographies by another name.

In df_event a '_' indicates that the county is unknown.

df_event['event_id'] is a unique string.  There are rows in the dataframe that are nearly identical but with different ids indicating that an event has occurred on multiple occasions.  This has no affect on the. state_fips or county_fips.

I know this is a multi step process but all help is appreciated. Thank you.

Body:
If there are duplicates in use area_name column first remove them by DataFrame.drop_duplicates:

dfgeo = dfgeo.drop_duplicates('area_name')

And then Series.map, what is faster like merge, so it should be preferable:

df_event['state_fips'] = df_event['state'].map(dfgeo.set_index('area_name')['state_fips'])
df_event['county_fips'] = df_event['county'].map(dfgeo.set_index('area_name')['county_fips'])
print (df_event)
  unique_str                        county        state state_fips county_fips
0   Event Id                             _      Alabama         01         NaN
1   Event Id                             _  Connecticut         09         NaN
2   Event Id                Autauga County      Alabama         01         001
3   Event Id              Fairfield County  Connecticut         09         001
4   Event Id  Fairbanks North Star Borough       Alaska         02         090


问:
Getting widgetId from reCAPTCHA v2 from g-recaptcha tag?
Hi this is my first attempt posting question here.

I want to know if I can ever get widgetId from the g-recaptcha tag and not from the returning value of grecaptcha.render() of reCAPTCHA v2.

The reason behind this is that I have 2 different scripts that handles each 2 forms on a same page.
I want to be able to reset the reCAPTCHA individually.

Each scripts have thier own onload callback that supposed to get their own widgetId.
But this does not work because it seems there is only 1 onload callback functions can be called by the url parameter of the google reCAPTCHA code.

I couldn't have multiple onload callback functions set to the recaptcha source url like below.

"https://www.google.com/recaptcha/api.js?onload=onloadCallback1,onloadCallback2&render=onload"

"https://www.google.com/recaptcha/api.js?onload[]=onloadCallback1&onload[]=onloadCallback2&render=onload"

So I thought maybe I can get the widget Id from the g-recaptcha tag after loaded...

Any idea or solution???

答:
Hmmm,,, it's not sophisticated but I came up with an idea of getting the widget id based on the order of g-recapctha class. The function accpets an id of the target recaptcha box as an argument and returns the index of the g-recaptcha class that is associated with.</p>

```<code>// recaptha box 1
<div id="recaptchaBox-1" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn1" type="button" value="Reset1">

// recaptha box 2
<div id="recaptchaBox-2" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn2" type="button" value="Reset2">

/**
 * Returns widgetId from a given element id
 * @param {string} elementId
 * @return {number} i
 */
function getWidgetId(elementId) {
  const recaptchaBoxes = document.querySelectorAll('.g-recaptcha');
  const targetBox = document.querySelector(`#${elementId}`);
  for (let i = 0; i < recaptchaBoxes.length; i++) {
    if (recaptchaBoxes[i].id === targetBox.id) {
      return i;
    }
  }
}

// Get the widgetId for each boxes.
const widgetId1 = getWidgetId('recaptchaBox-1');
const widgetId2 = getWidgetId('recaptchaBox-2');

// Assign grecaptcha.reset() for each buttons on click event.
document.getElementById('resetBtn-1').addEventListener('click', () => grecaptcha.reset(widgetId1));
document.getElementById('resetBtn-2').addEventListener('click', () => grecaptcha.reset(widgetId2));
</code>```

Body:
Hmmm,,, it's not sophisticated but I came up with an idea of getting the widget id based on the order of g-recapctha class. The function accpets an id of the target recaptcha box as an argument and returns the index of the g-recaptcha class that is associated with.

// recaptha box 1
<div id="recaptchaBox-1" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn1" type="button" value="Reset1">

// recaptha box 2
<div id="recaptchaBox-2" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn2" type="button" value="Reset2">

/**
 * Returns widgetId from a given element id
 * @param {string} elementId
 * @return {number} i
 */
function getWidgetId(elementId) {
  const recaptchaBoxes = document.querySelectorAll('.g-recaptcha');
  const targetBox = document.querySelector(`#${elementId}`);
  for (let i = 0; i < recaptchaBoxes.length; i++) {
    if (recaptchaBoxes[i].id === targetBox.id) {
      return i;
    }
  }
}

// Get the widgetId for each boxes.
const widgetId1 = getWidgetId('recaptchaBox-1');
const widgetId2 = getWidgetId('recaptchaBox-2');

// Assign grecaptcha.reset() for each buttons on click event.
document.getElementById('resetBtn-1').addEventListener('click', () => grecaptcha.reset(widgetId1));
document.getElementById('resetBtn-2').addEventListener('click', () => grecaptcha.reset(widgetId2));


问:
Print optimal solution for coin change algorithm
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, what is the optimal way to make change for N cents.

Example:

```<code>S = {2, 5, 10}
N = 6, then optimal solution is : 2, 2, 2
</code>```

I have below working code:

```<code>public static void main(String argv[]) {
        long n = 10L;
        int[] combo = new int[100];
        int[] amounts = { 2, 5, 10 };
        ways(n, amounts, combo, 0, 0, 0);
    }

    public static void ways(long n, int[] amounts, int[] combo, int startIndex, int sum, int index) {
        if (sum == n) {
            printArray(combo, index);
        }

        if (sum > n) {
            return;
        }

        for (int i = 0; i < amounts.length; i++) {
            sum = sum + amounts[i];
            combo[index] = amounts[i];
            ways(n, amounts, combo, startIndex, sum, index + 1);
            sum = sum - amounts[i];
        }
    }

    public static void printArray(int[] combo, int index) {
        for (int i = 0; i < index; i++) {
            System.out.print(combo[i] + " ");
        }
        System.out.println();
    }
</code>```

Output:

```<code>2 2 2 2 2
5 5
10
</code>```

Here I just need to optimal combination with less number of coins so only 10 in this example code.

But this code uses recursive approach, my value for N is Long type so as the value of N increases I am getting stackoverflow error.

The recursive approach I am following here is not correct, What is the correct way to solve this problem?

Update:

Based on MBo answer I tried below program, but I am not able to get the correct results:

```<code>static void testcase() {
        // make int array A of size N+1
        int N = 6;
        int[] A = new int[N + 1];
        // make int array P of size N+1
        int[] P = new int[N + 1];
        // fill A[] with large value (len(S) + 1)
        int[] S = { 2, 5, 10 };
        int lengthOfS = S.length;
        for (int i = 0; i < A.length; i++) {
            A[i] = lengthOfS + 1;
        }

        A[0] = 0;

        for (int s : S) {// coin value
            for (int i = s; i <= N; i++) {
                if (A[i - s] < A[i] + 1) { // using this coin we can get better
                                            // result for sum i
                    A[i] = A[i - s] + 1;
                    P[i] = s; // write down coin for this sum
                }
            }
        }
        System.out.println(Arrays.toString(P)); // [0, 0, 2, 2, 2, 5, 2]
        System.out.println(A[N]);// 3
        int idx = N;
        for (int i = 0; i < A[N]; i++) {
            int result = idx - P[idx];
            System.out.println(result); // 4 2 0
            idx = result;
        }
    }
</code>```

This code prints:

```<code>[0, 0, 2, 2, 2, 5, 2]
3

4
2
0
</code>```

How to fix this code?

答:
For fixed set S = {2, 5, 10} solution is rather simple:

No solutions for N=1,3

if N is odd, you must use 5 - so N=N-5

Now use greedy approach: get as much 10-s as possible, then as much 2-s as possible

```<code>def best(N):
    print(N, end = ":  ")
    if (N % 2):
        print("5", end = "    ")
        N = N - 5
    if N >= 10:
        print("10*", N//10, end = "    ")
        N = N % 10
    if N > 1:
        print("2*", N//2, end = "    ")

21:  5    10* 1    2* 3
22:  10* 2    2* 1
23:  5    10* 1    2* 4
24:  10* 2    2* 2
</code>```

In general you can find optimal solution using dynamic programming.

The first way is "memoization" - you have to implement recursive approach with the choice of the best solution, then add storing intermediate results in hashmap or another structure. Simple implementation:

```<code>S = [2, 3, 5, 7, 11]
dic = {}

def rec(summ):
    if summ == 0:
        return 0
    rd = dic.get(summ)
    if rd != None:
        return rd
    minn = 9999999999999
    for s in S:
        if s <= summ:
            minn = min(minn, 1 + rec(summ - s))
    dic[summ] = minn
    return minn

N = 1000
print(rec(N))

>>92
</code>```

Another way is using table - you fill it with the best possible results using the first item, then update solution using the second item and so on.

Pseudocode

```<code>make int array A of size N+1
make int array P of size N+1
fill A[] with large value (MaxInt` or at least `N/min(S))
A[0] = 0
for s in S:  //coin value
    for (i = s; i <= N; i++)
        if A[i - s] < A[i] + 1    //using this coin we can get better result for sum i
             A[i] = A[i - s] + 1
             P[i] = s            //write down coin for this sum
</code>```

Now we have A[N] with the best count, and can retrieve needed coins using P[N], P[N - P[N]]...  sequence.

Working Python code

```<code>S = [2, 3, 5, 7, 11]
N = 17
A = [0] + [10000] * N
P = [0] * (N + 1)
for s in S:  #coin value
    for i in range(s, N + 1):
        if A[i - s] < A[i] + 1:    #using this coin we can get better result for sum i
             A[i] = A[i - s] + 1
             P[i] = s            #write down coin for this sum

print(A) #for reference
i = N
while i > 0:
    print(P[i], end = " ")
    i = i - P[i]

>> [0, 10000, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 2, 3]
>> 11 3 3
</code>```

Note - if we can use every coin only once, we have to make inner loop in backward direction to avoid multiple adding the same coin

Body:
Given a value N, if we want to make change for N cents, and we have infinite supply of each of S = { S1, S2, .. , Sm} valued coins, what is the optimal way to make change for N cents.

Example:

S = {2, 5, 10}
N = 6, then optimal solution is : 2, 2, 2

I have below working code:

public static void main(String argv[]) {
        long n = 10L;
        int[] combo = new int[100];
        int[] amounts = { 2, 5, 10 };
        ways(n, amounts, combo, 0, 0, 0);
    }

    public static void ways(long n, int[] amounts, int[] combo, int startIndex, int sum, int index) {
        if (sum == n) {
            printArray(combo, index);
        }

        if (sum > n) {
            return;
        }

        for (int i = 0; i < amounts.length; i++) {
            sum = sum + amounts[i];
            combo[index] = amounts[i];
            ways(n, amounts, combo, startIndex, sum, index + 1);
            sum = sum - amounts[i];
        }
    }

    public static void printArray(int[] combo, int index) {
        for (int i = 0; i < index; i++) {
            System.out.print(combo[i] + " ");
        }
        System.out.println();
    }

Output:

2 2 2 2 2
5 5
10

Here I just need to optimal combination with less number of coins so only 10 in this example code.

But this code uses recursive approach, my value for N is Long type so as the value of N increases I am getting stackoverflow error.

The recursive approach I am following here is not correct, What is the correct way to solve this problem?

Update:

Based on MBo answer I tried below program, but I am not able to get the correct results:

static void testcase() {
        // make int array A of size N+1
        int N = 6;
        int[] A = new int[N + 1];
        // make int array P of size N+1
        int[] P = new int[N + 1];
        // fill A[] with large value (len(S) + 1)
        int[] S = { 2, 5, 10 };
        int lengthOfS = S.length;
        for (int i = 0; i < A.length; i++) {
            A[i] = lengthOfS + 1;
        }

        A[0] = 0;

        for (int s : S) {// coin value
            for (int i = s; i <= N; i++) {
                if (A[i - s] < A[i] + 1) { // using this coin we can get better
                                            // result for sum i
                    A[i] = A[i - s] + 1;
                    P[i] = s; // write down coin for this sum
                }
            }
        }
        System.out.println(Arrays.toString(P)); // [0, 0, 2, 2, 2, 5, 2]
        System.out.println(A[N]);// 3
        int idx = N;
        for (int i = 0; i < A[N]; i++) {
            int result = idx - P[idx];
            System.out.println(result); // 4 2 0
            idx = result;
        }
    }

This code prints:

[0, 0, 2, 2, 2, 5, 2]
3

4
2
0

How to fix this code?

Body:
For fixed set S = {2, 5, 10} solution is rather simple:

No solutions for N=1,3

if N is odd, you must use 5 - so N=N-5

Now use greedy approach: get as much 10-s as possible, then as much 2-s as possible

def best(N):
    print(N, end = ":  ")
    if (N % 2):
        print("5", end = "    ")
        N = N - 5
    if N >= 10:
        print("10*", N//10, end = "    ")
        N = N % 10
    if N > 1:
        print("2*", N//2, end = "    ")

21:  5    10* 1    2* 3
22:  10* 2    2* 1
23:  5    10* 1    2* 4
24:  10* 2    2* 2

In general you can find optimal solution using dynamic programming.

The first way is "memoization" - you have to implement recursive approach with the choice of the best solution, then add storing intermediate results in hashmap or another structure. Simple implementation:

S = [2, 3, 5, 7, 11]
dic = {}

def rec(summ):
    if summ == 0:
        return 0
    rd = dic.get(summ)
    if rd != None:
        return rd
    minn = 9999999999999
    for s in S:
        if s <= summ:
            minn = min(minn, 1 + rec(summ - s))
    dic[summ] = minn
    return minn

N = 1000
print(rec(N))

>>92

Another way is using table - you fill it with the best possible results using the first item, then update solution using the second item and so on.

Pseudocode

make int array A of size N+1
make int array P of size N+1
fill A[] with large value (MaxInt` or at least `N/min(S))
A[0] = 0
for s in S:  //coin value
    for (i = s; i <= N; i++)
        if A[i - s] < A[i] + 1    //using this coin we can get better result for sum i
             A[i] = A[i - s] + 1
             P[i] = s            //write down coin for this sum

Now we have A[N] with the best count, and can retrieve needed coins using P[N], P[N - P[N]]...  sequence.

Working Python code

S = [2, 3, 5, 7, 11]
N = 17
A = [0] + [10000] * N
P = [0] * (N + 1)
for s in S:  #coin value
    for i in range(s, N + 1):
        if A[i - s] < A[i] + 1:    #using this coin we can get better result for sum i
             A[i] = A[i - s] + 1
             P[i] = s            #write down coin for this sum

print(A) #for reference
i = N
while i > 0:
    print(P[i], end = " ")
    i = i - P[i]

>> [0, 10000, 1, 1, 2, 1, 2, 1, 2, 2, 2, 1, 2, 2, 2, 3, 2, 3]
>> 11 3 3

Note - if we can use every coin only once, we have to make inner loop in backward direction to avoid multiple adding the same coin


问:
jQuery Accordion - hover trigger
is there any way to open this accordion using class on hover? (e.g. ".accordion--hover" or data-on-hover)

I tried to add the .open class on hover and it didn't work for me.

Thanks for any solution.

https://vctrfrnndz.github.io/jquery-accordion/

```<code><div data-accordion data-on-hover>
  <div data-control>Control</div>
  <div data-content>
    <div>Row</div>
    <div>Row</div>
    <div>Row</div>
  </div>
</div>

$('.accordion').accordion({
  "transitionSpeed": 400
});
</code>```

答:
If you are ok with custom solution, then go with it, or if you really want to go with the plugin solution then try firing open and close events of the accordion plugin mentioned in its documentation.

Events
accordion.open fires when any accordion opens

accordion.close fires when any accordion closes

Fire open event on mouseEnter and fire close event on mouseLeave

find my custom solution below if this works for you

$(document).ready(function(){
  $('.accordionHeader').on('mouseenter',function(){
    $(this).find('.accordionContent').slideDown();
  });
  $('.accordionHeader').on('mouseleave',function(){
    $(this).find('.accordionContent').slideUp();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.accordionContent {
  display: none;
}
.accordionWrapper {margin-bottom: 50px;}
.accordionHeader {padding: 10px;border: 1px solid;}</code>```

    Hover Me

    Content Go here

Row

Row

Row

    Hover Me

    Content Go here

Row

Row

Row

    Hover Me

    Content Go here

Row

Row

Row

```

Title: jQuery Accordion - hover trigger

Body:
is there any way to open this accordion using class on hover? (e.g. ".accordion--hover" or data-on-hover)

I tried to add the .open class on hover and it didn't work for me.

Thanks for any solution.

https://vctrfrnndz.github.io/jquery-accordion/

Control

Row

Row

Row

$('.accordion').accordion({
  "transitionSpeed": 400
});

Body:
If you are ok with custom solution, then go with it, or if you really want to go with the plugin solution then try firing open and close events of the accordion plugin mentioned in its documentation.

Events
accordion.open fires when any accordion opens

accordion.close fires when any accordion closes

Fire open event on mouseEnter and fire close event on mouseLeave

find my custom solution below if this works for you

$(document).ready(function(){
  $('.accordionHeader').on('mouseenter',function(){
    $(this).find('.accordionContent').slideDown();
  });
  $('.accordionHeader').on('mouseleave',function(){
    $(this).find('.accordionContent').slideUp();
  });
});

.accordionContent {
  display: none;
}
.accordionWrapper {margin-bottom: 50px;}
.accordionHeader {padding: 10px;border: 1px solid;}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="accordionWrapper">
  <div class="accordionHeader">
    Hover Me
  <div class="accordionContent">
    Content Go here
    <div>Row</div>
    <div>Row</div>
    <div>Row</div>
  </div>
  </div>

</div>
<div class="accordionWrapper">
  <div class="accordionHeader">
    Hover Me
  <div class="accordionContent">
    Content Go here
    <div>Row</div>
    <div>Row</div>
    <div>Row</div>
  </div>
  </div>

</div>
<div class="accordionWrapper">
  <div class="accordionHeader">
    Hover Me
  <div class="accordionContent">
    Content Go here
    <div>Row</div>
    <div>Row</div>
    <div>Row</div>
  </div>
  </div>

</div>


问:
How do we can make a image to take the whole space available in the floating action button in flutter
I am trying to add a image in floating action button which I have done easily but the problem I am facing is that I don't know how to make this image to take the whole space available in the floating action button ... I tried my best researched in the internet but did not not fount anything ...any help is appreciated thanks in advance </p>

```<code>floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: MediaQuery.of(context).size.width * 0.24,
width: MediaQuery.of(context).size.width * 0.24,
child: FloatingActionButton(
//backgroundColor:Colors.lightGreen,
child: Image.asset("assets/home_unselected.png"),
onPressed: () {}),
),
</code>```

答:
Have you tried warping the "Image" widget with "Expanded" widget? </p>

<p>Not sure about this though. </p>

Body:
I am trying to add a image in floating action button which I have done easily but the problem I am facing is that I don't know how to make this image to take the whole space available in the floating action button ... I tried my best researched in the internet but did not not fount anything ...any help is appreciated thanks in advance

floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
floatingActionButton: Container(
height: MediaQuery.of(context).size.width * 0.24,
width: MediaQuery.of(context).size.width * 0.24,
child: FloatingActionButton(
//backgroundColor:Colors.lightGreen,
child: Image.asset("assets/home_unselected.png"),
onPressed: () {}),
),

Body:
Have you tried warping the "Image" widget with "Expanded" widget?

Not sure about this though.