问:
How to mock document.evaluate() and XPathResult in a mocha unit test?
I have following JavaScript class wrapping document.evaluate() selecting a DOM element using a XPath:

```<code>'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
class ElementByXPath {
  constructor(elementXPath) {
    this.elementXPath = elementXPath
  }
  element(document) {
    return document.evaluate(
      this.elementXPath,
      document.documentElement,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null,
    ).singleNodeValue
  }
}
exports.ElementByXPath = ElementByXPath
</code>```

Following test written in mocha shall verify the method element():

```<code>describe('ElementByXPath function test', () => {
  it('should return element of given XPath', () => {
    const dom = new JSDOM(`<p id = "test-id"/p>`)
    const result = new ElementByXpath('//*[@id="test-id"]').element(
      dom.window.document,
    )

    expect(result.tagName).to.equal('P')
  })
})
</code>```

Using JSDOM I was able to mock the window element. Unfortunately, I cannot mock XPathResult:

```<code>ReferenceError: XPathResult is not defined
</code>```

Has someone maybe a hint? Thanks.

答:
Add jsdom-global next to jsdom (described here):

```<code>npm i -D jsdom jsdom-global
</code>```

Register jsdom-global when mocha executes the tests

```<code>mocha -r jsdom-global/register test/**/*.test.js
</code>```

Body:
I have following JavaScript class wrapping document.evaluate() selecting a DOM element using a XPath:

'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
class ElementByXPath {
  constructor(elementXPath) {
    this.elementXPath = elementXPath
  }
  element(document) {
    return document.evaluate(
      this.elementXPath,
      document.documentElement,
      null,
      XPathResult.FIRST_ORDERED_NODE_TYPE,
      null,
    ).singleNodeValue
  }
}
exports.ElementByXPath = ElementByXPath

Following test written in mocha shall verify the method element():

describe('ElementByXPath function test', () => {
  it('should return element of given XPath', () => {
    const dom = new JSDOM(`<p id = "test-id"/p>`)
    const result = new ElementByXpath('//*[@id="test-id"]').element(
      dom.window.document,
    )

    expect(result.tagName).to.equal('P')
  })
})

Using JSDOM I was able to mock the window element. Unfortunately, I cannot mock XPathResult:

ReferenceError: XPathResult is not defined

Has someone maybe a hint? Thanks.

Body:
Add jsdom-global next to jsdom (described here):

npm i -D jsdom jsdom-global

Register jsdom-global when mocha executes the tests

mocha -r jsdom-global/register test/**/*.test.js


来源: stackexchange

问:
Laravel Updating both data and files in one form using Ajax? when method/type='PUT'
Well, when I do not use ajax to send data to server directly from form by adding  hidden _method parameter where value is 'PUT'-> everything just work like a charm for updating a form. But when I tried same things with ajax receiving null for $request object in controller update function. Right now I am feeling frightened that for delete I have to use method='POST'.

I used both method='POST' or type='POST' but no luck.

```<code>Route::resource('contents', 'ContentController');
let url_content_update = "{{ route('contents.update', ':id') }}";

WebApp.ContentController.onClickUpdateButton = function () {
    var _id = $("#form_id").data('_id');
    var form = $("#form_id")[0];
    var formData = new FormData(form);
    console.log(formData.get('title'));// console print "I am title" just fine.
    $.ajax({
         headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: url_content_update.replace(':id', _id),
        method: 'PUT',
        contentType:false ,
        processData: false,
        data: formData,
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    $('#status').html('Upload a file (compulsory):<b> Uploading -> ' + (Math.round(percentComplete * 100)) + '% </b>');
                }
            }, false);

            return xhr;
        },
        success: function (result) {

        },
        error: function (jqXHR, exception) {
        }

    })

}
</code>```

Controller:
received value of $id=383 successfully.
But null found in $request object;

```<code> public function update(Request $request,  $id)
    {
        $content = Content::find($id);
        $content->app_id=$request->app_cat;
        $content->cat_id=$request->category;
        $content->sub_cat_id=$request->subcategory;
        $content->title=$request->title;
        $content->content_type=$request->type;
        if($request->type==3||$request->type==4||$request->type==5){
            //return json_encode($request->hasFile('any_file'));
            if($request->hasFile('any_file')){
                $content->content=$this->storeFile($request);
            }
        }else{
            $content->content=$request->content;
        }

        $fileNameToStore='no_image.jpg';
        if($request->hasFile('cover_image')){
            $this->validate($request,[
                'cover_image'=>'image|nullable|max:1999'
            ]);
            $content->cover_image=$this->storeImage($request);
        }

        $content->save();
        $output = array("message"=>"Content updated successfully", "status" => "200");
        echo json_encode($output);
    }

</code>```

答:
This is a known issue since 2016, here is how you submit a put in traditional form.

<form action="/foo/bar" method="POST">
    @method('PUT')
    @csrf
</form>
```

<p>so basically if you want to use <code>FormData</code> you cannot use <code>put</code> or <code>patch</code> as the method, you have to use <code>post</code>. Also, you need to tell laravel the request was supposed to be <code>PUT</code> so your code has to be like this</p>

<pre class="lang-js prettyprint-override"><code>   ...
            var formData = new FormData(form);
            //this line is equivalent with @method('PUT') in traditional form
            formData.append('_method', 'PUT');
   ...
            //this line is equivalent with method="POST" in traditional form
            method: 'POST',
</code>```

Unfortunately, this is the only solution if you want to use FormData.

ContentLicense: CC BY-SA 4.0

Body:
Well, when I do not use ajax to send data to server directly from form by adding  hidden _method parameter where value is 'PUT'-> everything just work like a charm for updating a form. But when I tried same things with ajax receiving null for $request object in controller update function. Right now I am feeling frightened that for delete I have to use method='POST'.

I used both method='POST' or type='POST' but no luck.

Route::resource('contents', 'ContentController');
let url_content_update = "{{ route('contents.update', ':id') }}";

WebApp.ContentController.onClickUpdateButton = function () {
    var _id = $("#form_id").data('_id');
    var form = $("#form_id")[0];
    var formData = new FormData(form);
    console.log(formData.get('title'));// console print "I am title" just fine.
    $.ajax({
         headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        url: url_content_update.replace(':id', _id),
        method: 'PUT',
        contentType:false ,
        processData: false,
        data: formData,
        xhr: function() {
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = evt.loaded / evt.total;
                    $('#status').html('Upload a file (compulsory): Uploading -> ' + (Math.round(percentComplete * 100)) + '% ');
                }
            }, false);

            return xhr;
        },
        success: function (result) {

        },
        error: function (jqXHR, exception) {
        }

    })

}

Controller:
received value of $id=383 successfully.
But null found in $request object;

 public function update(Request $request,  $id)
    {
        $content = Content::find($id);
        $content->app_id=$request->app_cat;
        $content->cat_id=$request->category;
        $content->sub_cat_id=$request->subcategory;
        $content->title=$request->title;
        $content->content_type=$request->type;
        if($request->type==3||$request->type==4||$request->type==5){
            //return json_encode($request->hasFile('any_file'));
            if($request->hasFile('any_file')){
                $content->content=$this->storeFile($request);
            }
        }else{
            $content->content=$request->content;
        }

        $fileNameToStore='no_image.jpg';
        if($request->hasFile('cover_image')){
            $this->validate($request,[
                'cover_image'=>'image|nullable|max:1999'
            ]);
            $content->cover_image=$this->storeImage($request);
        }

        $content->save();
        $output = array("message"=>"Content updated successfully", "status" => "200");
        echo json_encode($output);
    }

Body:
This is a known issue since 2016, here is how you submit a put in traditional form.

<form action="/foo/bar" method="POST">
    @method('PUT')
    @csrf
</form>

so basically if you want to use FormData you cannot use put or patch as the method, you have to use post. Also, you need to tell laravel the request was supposed to be PUT so your code has to be like this

   ...
            var formData = new FormData(form);
            //this line is equivalent with @method('PUT') in traditional form
            formData.append('_method', 'PUT');
   ...
            //this line is equivalent with method="POST" in traditional form
            method: 'POST',

Unfortunately, this is the only solution if you want to use FormData.


问:
Update Stock Line graph based on DateRangeInput user Selection - Shiny App
I am using stock data from Quantmod and looking for a way to use DateRangeInput within a shiny app and have the user selection be reflected in a ggplot graph.

```<code>ui <- fluidPage(
  titlePanel("Stock App"),

  mainPanel(
    selectInput("stock", "Select a Stock(s):", choices = unique(all_stocks_df$Stock), multiple = TRUE, selected = "AAPL"),
    dateRangeInput("daterange", "Select a timeframe to be plotted", start = "2010-01-01", end = "2020-01-01")),

  tabsetPanel(
    tabPanel("Line Graph", plotOutput("line"))

  )
)

server <- function(input, output, session) {
  output$line <- renderPlot({
    stock_subset <- subset(all_stocks_df, Stock == input$stock)
    ggplot () +
      geom_line(aes(x=input$daterange, y=Close, color = Stock),
                data = stock_subset)
  })

}

shinyApp(ui=ui, server=server)
</code>```

The all_stocks_df dataframe I am generating the plot with looks like this:

```<code>Date       Close     Stock
2019-12-31 293.65     AAPL
...
2007-01-03 11.97      AAPL

2019-12-31 1847.84    AMZN
...
2007-01-03 38.70      AMZN
</code>```

When I enter input$daterange as my X argument for my ggplot line graph, it is not working. Ideally the user would change the timeframe and the graph would update.

答:
For subset would use %in% instead of == since you can have multiple stocks selected in your selectInput. Also would filter/subset by input$daterange before plotting.

```<code>server <- function(input, output, session) {
  output$line <- renderPlot({
    stock_subset <- subset(all_stocks_df, Stock %in% input$stock & Date>= input$daterange[1] & Date <= input$daterange[2])
    ggplot () +
      geom_line(aes(x=Date, y=Close, color = Stock), data = stock_subset)
  })
}
</code>```

Body:
I am using stock data from Quantmod and looking for a way to use DateRangeInput within a shiny app and have the user selection be reflected in a ggplot graph.

ui <- fluidPage(
  titlePanel("Stock App"),

  mainPanel(
    selectInput("stock", "Select a Stock(s):", choices = unique(all_stocks_df$Stock), multiple = TRUE, selected = "AAPL"),
    dateRangeInput("daterange", "Select a timeframe to be plotted", start = "2010-01-01", end = "2020-01-01")),

  tabsetPanel(
    tabPanel("Line Graph", plotOutput("line"))

  )
)

server <- function(input, output, session) {
  output$line <- renderPlot({
    stock_subset <- subset(all_stocks_df, Stock == input$stock)
    ggplot () +
      geom_line(aes(x=input$daterange, y=Close, color = Stock),
                data = stock_subset)
  })

}

shinyApp(ui=ui, server=server)

The all_stocks_df dataframe I am generating the plot with looks like this:

Date       Close     Stock
2019-12-31 293.65     AAPL
...
2007-01-03 11.97      AAPL

2019-12-31 1847.84    AMZN
...
2007-01-03 38.70      AMZN

When I enter input$daterange as my X argument for my ggplot line graph, it is not working. Ideally the user would change the timeframe and the graph would update.

Body:
For subset would use %in% instead of == since you can have multiple stocks selected in your selectInput. Also would filter/subset by input$daterange before plotting.

server <- function(input, output, session) {
  output$line <- renderPlot({
    stock_subset <- subset(all_stocks_df, Stock %in% input$stock & Date>= input$daterange[1] & Date <= input$daterange[2])
    ggplot () +
      geom_line(aes(x=Date, y=Close, color = Stock), data = stock_subset)
  })
}


问:
PHOTO FIELD IN EASYADMIN IS NOT SHOWING
I am trying to display some images in my bundle (using easyadmin bundle) & symfony 3.4
However, for some reason, the photos aren't showing.
here's my code:
in config.yml:

```<code>       Employee:
        class: BackofficeBundle\Entity\Employee
        role_prefix: ROLE_EMPLOYEE_MANAGER
        list:
            fields:
                - id
                - Name
                - { property: 'photo', label: 'EMPLOYEE AVATAR', type: 'image' , base_path: '/images/' }
</code>```

in my Employee entity:

```<code> /**
 * @ORM\Column(name="photo", type="string", length=500)
 * @Assert\File(maxSize="500k", mimeTypes={"image/jpeg", "image/jpg", "image/png", "image/GIF"})
 */
private $photo;
</code>```

in my EmployeeType.php

```<code> $builder->add('photo', FileType::class, array('data_class'=>null, 'required'=>false
    ));
</code>```

The photo aren't showing in the List page and when i click on the edit i get this error :

```<code>The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.
</code>```

答: For this case, please consider using VichUploadBundle https://symfony.com/doc/master/bundles/EasyAdminBundle/integration/vichuploaderbundle.html</p>

Title: PHOTO FIELD IN EASYADMIN IS NOT SHOWING

Body:
I am trying to display some images in my bundle (using easyadmin bundle) & symfony 3.4
However, for some reason, the photos aren't showing.
here's my code:
in config.yml:

       Employee:
        class: BackofficeBundle\Entity\Employee
        role_prefix: ROLE_EMPLOYEE_MANAGER
        list:
            fields:
                - id
                - Name
                - { property: 'photo', label: 'EMPLOYEE AVATAR', type: 'image' , base_path: '/images/' }

in my Employee entity:

 /**
 * @ORM\Column(name="photo", type="string", length=500)
 * @Assert\File(maxSize="500k", mimeTypes={"image/jpeg", "image/jpg", "image/png", "image/GIF"})
 */
private $photo;

in my EmployeeType.php

 $builder->add('photo', FileType::class, array('data_class'=>null, 'required'=>false
    ));

The photo aren't showing in the List page and when i click on the edit i get this error :

The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.


问:
"do" in "do Application.Run(form)" sentence
What is the difference between

```<code>do Application.Run(form)
</code>```

and, simply:

```<code>Application.Run(form) ?
</code>```

What is the role of do keyword in the first sentence?

答:
Whereas 'do' was a required keyword in many places in the language in some of the earlier releases, nowadays you rarely need 'do'.  The remaining exceptions that I can think of are that 'do' is still part of loop syntax (e.g. "while e1 do e2") and if you want to put an assembly-level attribute or an attribute on the startup method, you can put the attribute before the explicit 'do' of a final code block in a module.  Often times in F# samples you'll see

```<code>[<STAThread>]
do Application.Run(form)
</code>```

as the last two lines of a file, and I think the 'do' is still required there in order to be able to attach the attribute on the line above it.

OwnerDisplayName: Vladimir Aks

LastEditorDisplayName: Drew Noakes

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between

do Application.Run(form)

and, simply:

Application.Run(form) ?

What is the role of do keyword in the first sentence?

Body:
Whereas 'do' was a required keyword in many places in the language in some of the earlier releases, nowadays you rarely need 'do'.  The remaining exceptions that I can think of are that 'do' is still part of loop syntax (e.g. "while e1 do e2") and if you want to put an assembly-level attribute or an attribute on the startup method, you can put the attribute before the explicit 'do' of a final code block in a module.  Often times in F# samples you'll see

[<STAThread>]
do Application.Run(form)

as the last two lines of a file, and I think the 'do' is still required there in order to be able to attach the attribute on the line above it.

OwnerDisplayName: Brian


问:
What does it mean when you set an array[index] equal to quotation marks?
I've been working on a problem where the goal is to take a string and return the longest repeated pattern if a pattern is present. For example, if the string is "aabbbaa", "yes aa" would be returned. If the string is "aavbbbvaabbb", "yes bbb" would be returned. I took a look at someone else's solution and believe to understand each piece of code aside from this one line which seems to be key: copy[idx..idx2]=""

Here's the whole solution:

```<code>def PatternChaser(str)
  patterns = {}

  (0..str.length-1).each do |idx|
    (idx + 1..str.length - 1).each do |idx2|
        copy = str.dup
        chunk = str[idx..idx2]
        len = chunk.length
        copy[idx..idx2] = ""
        patterns[chunk] = len if copy.include?(chunk) && !patterns.include?(chunk)
     end
  end
  return "no null" if patterns.empty?
  patterns.each { |k,v| return "yes" + " " + k if v == patterns.values.max }
end

puts PatternChaser(STDIN.gets)
</code>```

Forgive me if this is fairly common syntax. I've been coding for less than a year thus far and haven't been able to find an answer so far on StackOverflow. Help would be much appreciated! :)

答:
A string can be seen as a sequence of charaters. By writing:

```<code>copy[idx..idx2]=""
</code>```

You are setting the characters between idx and idx2 to the empty string, so that means that you are removing the characters from idx (inclusive) and idx2 (inclusive) from the copy string.

For example:

```<code>irb(main):001:0> s = "foobar"
=> "foobar"
irb(main):002:0> s[1..3] = ""
=> ""
irb(main):003:0> s
=> "far"
</code>```

We can also insert another string that contains less, an equal amount or more characters than the sequence. For example:

```<code>irb(main):007:0> s = "foobar"
=> "foobar"
irb(main):008:0> s[1..3] = "oofoob"
=> "oofoob"
irb(main):009:0> s
=> "foofoobar"
</code>```

Body:
I've been working on a problem where the goal is to take a string and return the longest repeated pattern if a pattern is present. For example, if the string is "aabbbaa", "yes aa" would be returned. If the string is "aavbbbvaabbb", "yes bbb" would be returned. I took a look at someone else's solution and believe to understand each piece of code aside from this one line which seems to be key: copy[idx..idx2]=""

Here's the whole solution:

def PatternChaser(str)
  patterns = {}

  (0..str.length-1).each do |idx|
    (idx + 1..str.length - 1).each do |idx2|
        copy = str.dup
        chunk = str[idx..idx2]
        len = chunk.length
        copy[idx..idx2] = ""
        patterns[chunk] = len if copy.include?(chunk) && !patterns.include?(chunk)
     end
  end
  return "no null" if patterns.empty?
  patterns.each { |k,v| return "yes" + " " + k if v == patterns.values.max }
end

puts PatternChaser(STDIN.gets)

Forgive me if this is fairly common syntax. I've been coding for less than a year thus far and haven't been able to find an answer so far on StackOverflow. Help would be much appreciated! :)

Body:
A string can be seen as a sequence of charaters. By writing:

copy[idx..idx2]=""

You are setting the characters between idx and idx2 to the empty string, so that means that you are removing the characters from idx (inclusive) and idx2 (inclusive) from the copy string.

For example:

irb(main):001:0> s = "foobar"
=> "foobar"
irb(main):002:0> s[1..3] = ""
=> ""
irb(main):003:0> s
=> "far"

We can also insert another string that contains less, an equal amount or more characters than the sequence. For example:

irb(main):007:0> s = "foobar"
=> "foobar"
irb(main):008:0> s[1..3] = "oofoob"
=> "oofoob"
irb(main):009:0> s
=> "foofoobar"


问:
Django and HTML : Too many values to unpack (expected 2)
I'm new to django and html and I have to do a project for school. I tried to learn how forms works with django and I think I got it django forms right. But I simply don't know how to make it work with my html.
I got the too many values to unpack (expected 2).
Here is the important part of my form:

```<code>class ConfiguratorForm(forms.Form):
  queryOfProject = TypeOfProgram.objects.values_list('name')
  queryOfFramework = Framework.objects.values_list('name','version')
  listFramework = []
  listProject = []
  listFramework=[(q[0],q[1])for q in queryOfFramework]
  listProject =[(q[0])for q in queryOfProject]

  print("list of")
  print(listFramework)
  print(listProject)
  typeOfTheproject = forms.ChoiceField(choices = listProject)
  wantedFramework = forms.MultipleChoiceField(choices = listFramework)
</code>```

Where listProject and listFramework are both list containing elements.
And I know it is no good code but  I'm learning how everything works and I haven't much time.

For the html code. I absolutly don't know what exactly I wrote. I've search so lang and tried a lot of things I've seen.

```<code>{% block content %}

   <form method="post">
      {% csrf_token %}
      {{form}}
      <input type="submit" value="Submit">
   </form>
{% endblock %}
</code>```

If anyone could tell me how to correct the html file or if my form is wrong?

EDIT: Here is the full trace, my model and the view:

Models:

```<code>class web(models.Model):
   typeOfWeb = models.CharField(max_length=50)
   def __str__(self):
   template = '{0.typeOfWeb}'
   return template.format(self)

class TypeOfProgram(models.Model):
    name = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.name}'
        return template.format(self)
    def __iter__(self):
        return iter(self.name)

class Language(models.Model):
    name = models.CharField(max_length=200)
    version = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.name} {0.version}'
        return template.format(self)

class Pro(models.Model):
    advantage = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.advantage}'
        return template.format(self)

class Con(models.Model):
    disadvantage = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.disadvantage}'
        return template.format(self)

class Framework(models.Model):
    name = models.CharField(max_length=200)
    language = models.ManyToManyField(Language)
    version = models.CharField(max_length=20)
    typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE)
    cotationOfFramework = models.IntegerField(default = 5) #need to increase from pros and cons
    pros = models.ManyToManyField(Pro)
    cons = models.ManyToManyField(Con)
    additionalInformation =  models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE)
    def __str__(self):
        template = '{0.name} {0.version} {0.typeOfFramework} {0.cotationOfFramework} {0.additionalInformation}'
        return template.format(self)

    def __iter__(self):
        return [ self.name,
                 self.language,
                 self.version,
                 self.typeOfFramework,
                 self.cotationOfFramework,
                 self.pros,
                 self.cons,
                 self.additionalInformation]
</code>```

View:

```<code>    def index(request):
        context = {}
        context['form'] = ConfiguratorForm()
        return render(request, "forms/configurator.html", context)
        """all the configurator algorithm"""
        if request.method == 'POST':

               form = ConfiguratorForm(request.POST)

            #Check if the form is valid:
            if form.is_valid():
                typeOfProject = form.cleaned_data['typeOfTheproject']
                wantedFramework = form.cleaned_data['wantedFramework']
                listOfmember = form.cleaned_data['listOfmember']
                print(typeOfProject, wantedFramework, listOfmember)
#if the project is a web application, then 2 kind of framework are needed
            #need to parse instances of the form
            #get the database

            listOfProject = TypeOfProgram.objects.all()
            listOfFramework = Framework.objects.all()
            listOfLanguages = Language.objects.all()

            easiestChoice = ""
            bestChoice = ""
            otherChoices = [""]

            if typeOfproject == 'Web Application':
                typeOfproject = ["Backend", "Frontend"]
            else:
                print("hello world")
            neededFramework = []

            #take all the needed framework asked by the team
            for i in range(len(wantedFramework)):
                neededFramework.append(wantedFramework[i])

            #configure easiest choice
            #for all type of the project (needed for web development)
            for i in range(len(typeOfproject)):

                #for all asked framework
                for j in neededFramework:

                    #for all framework
                    for k in Framework.objects.value_list("name"):

                        #check if k is a good framework for the project
                        for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=k)
                            if l == currentFramework.typeOfFramework:

                                #verify they are the same
                                if k == i:
                                    if easiestChoice == "":
                                        easiestChoice = i
                                    #check the cotation
                                    else:
                                        check = Framework.objects.filter(name = i)
                                        check2 = Framework.objects.filter(name = easiestChoice)

                                        if check.cotationOfFramework > check2.cotationOfFramework:
                                            easiestChoice = i

            #configure best choice
            for i in range(len(typeOfproject)):
                for j in listOfFramework:
                    for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=j)
                            if l == currentFramework.typeOfFramework:
                                if bestChoice =="":
                                    bestChoice = j
                                else:
                                    check = Framework.objects.filter(name = bestChoice)
                                    if j.cotation > check.cotation:
                                        bestChoice = j.name

            #give all other choices

            for i in range(len(typeOfproject)):
                for j in listOfFramework:
                    for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=j)
                            if l == currentFramework.typeOfFramework:
                                otherChoices.append(j.name)

            return render(request, 'forms/configurator.html')

    return render(request, 'forms/configurator.html')
</code>```

Trace:

```<code>Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/configurator/

Django Version: 3.0
Python Version: 3.7.2
Installed Applications:
['configurator.apps.ConfiguratorConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template C:\Users\victo\OneDrive\Documents\BAC 3\Projet Individuel\1920_INFOB318_CPDI\code\ProjetIndividuel\CPDI\configurator\templates\forms\configurator.html, error at line 5
   too many values to unpack (expected 2)
   1 : {% block content %}
   2 :
   3 : <form method="post">
   4 :     {% csrf_token %}
   5 :      {{ form }}
   6 :     <input type="submit" value="Submit">
   7 : </form>
   8 : {% endblock %}

Traceback (most recent call last):
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\victo\OneDrive\Documents\BAC 3\Projet Individuel\1920_INFOB318_CPDI\code\ProjetIndividuel\CPDI\configurator\views.py", line 18, in index
    return render(request, "forms/configurator.html", context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\loader_tags.py", line 53, in render
    result = self.nodelist.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 992, in render
    return render_value_in_context(output, context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 971, in render_value_in_context
    value = str(value)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\utils\html.py", line 373, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 137, in __str__
    return self.as_table()
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 279, in as_table
    errors_on_separate_row=False,
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 238, in _html_output
    'field_name': bf.html_name,
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\utils\html.py", line 373, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 33, in __str__
    return self.as_widget()
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 89, in as_widget
    attrs = self.build_widget_attrs(attrs, widget)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 224, in build_widget_attrs
    if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\widgets.py", line 702, in use_required_attribute
    return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\widgets.py", line 688, in _choice_has_empty_value
    value, _ = choice

Exception Type: ValueError at /configurator/
Exception Value: too many values to unpack (expected 2)
</code>```

答:
You code is ver wired...

Choice fields expect to obtain a tuple or a list type: key - value

to fix too many values to unpack (expected 2) change this lines in your form:

```<code>typeOfTheproject = forms.ChoiceField(choices = listProject)
wantedFramework = forms.MultipleChoiceField(choices = listFramework)
</code>```

for:

FIRST VERSION CODE:

```<code>class ConfiguratorForm(forms.Form):
    queryOfProject = TypeOfProgram.objects.values_list('name')
    queryOfFramework = Framework.objects.values_list('name', 'version')
    listOfProject = []
    listOfFramework = []
    listOfFramework += queryOfFramework
    listOfProject += queryOfProject
    listFramework = []
    listProject = []

    for i in range(0,len(listOfFramework)):
       listFramework.append(listOfFramework[i]['name'] + " " +listOfFramework[i]['version'])
    for i in range(0,len(listOfProject)):
       listProject.append(listOfProject[i]['name'])

    typeOfTheproject = forms.ChoiceField(choices=[(x, x) for x in listProject])  # <---
    wantedFramework = forms.MultipleChoiceField(choices=[(x, x) for x in listFramework])  # <---
</code>```

SECOND VERSION CODE:

```<code>class ConfiguratorForm(forms.Form):
    queryOfProject = TypeOfProgram.objects.values_list('name')
    queryOfFramework = Framework.objects.values_list('name','version')
    listFramework = []
    listProject = []
    listFramework=[(q['name'], q['version'])for q in queryOfFramework]    # <---
    listProject =[(q['name'])for q in queryOfProject]    # <---

    print("list of")
    print(listFramework)
    print(listProject)
    typeOfTheproject = forms.ChoiceField(choices = listProject)
    wantedFramework = forms.MultipleChoiceField(choices = listFramework)
</code>```

Body:
I'm new to django and html and I have to do a project for school. I tried to learn how forms works with django and I think I got it django forms right. But I simply don't know how to make it work with my html.
I got the too many values to unpack (expected 2).
Here is the important part of my form:

class ConfiguratorForm(forms.Form):
  queryOfProject = TypeOfProgram.objects.values_list('name')
  queryOfFramework = Framework.objects.values_list('name','version')
  listFramework = []
  listProject = []
  listFramework=[(q[0],q[1])for q in queryOfFramework]
  listProject =[(q[0])for q in queryOfProject]

  print("list of")
  print(listFramework)
  print(listProject)
  typeOfTheproject = forms.ChoiceField(choices = listProject)
  wantedFramework = forms.MultipleChoiceField(choices = listFramework)

Where listProject and listFramework are both list containing elements.
And I know it is no good code but  I'm learning how everything works and I haven't much time.

For the html code. I absolutly don't know what exactly I wrote. I've search so lang and tried a lot of things I've seen.

{% block content %}

   <form method="post">
      {% csrf_token %}
      {{form}}
      <input type="submit" value="Submit">
   </form>
{% endblock %}

If anyone could tell me how to correct the html file or if my form is wrong?

EDIT: Here is the full trace, my model and the view:

Models:

class web(models.Model):
   typeOfWeb = models.CharField(max_length=50)
   def __str__(self):
   template = '{0.typeOfWeb}'
   return template.format(self)

class TypeOfProgram(models.Model):
    name = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.name}'
        return template.format(self)
    def __iter__(self):
        return iter(self.name)

class Language(models.Model):
    name = models.CharField(max_length=200)
    version = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.name} {0.version}'
        return template.format(self)

class Pro(models.Model):
    advantage = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.advantage}'
        return template.format(self)

class Con(models.Model):
    disadvantage = models.CharField(max_length=200)
    def __str__(self):
        template = '{0.disadvantage}'
        return template.format(self)

class Framework(models.Model):
    name = models.CharField(max_length=200)
    language = models.ManyToManyField(Language)
    version = models.CharField(max_length=20)
    typeOfFramework = models.ForeignKey(TypeOfProgram, on_delete=models.CASCADE)
    cotationOfFramework = models.IntegerField(default = 5) #need to increase from pros and cons
    pros = models.ManyToManyField(Pro)
    cons = models.ManyToManyField(Con)
    additionalInformation =  models.ForeignKey(web,blank=True,null=True ,default = None ,on_delete=models.CASCADE)
    def __str__(self):
        template = '{0.name} {0.version} {0.typeOfFramework} {0.cotationOfFramework} {0.additionalInformation}'
        return template.format(self)

    def __iter__(self):
        return [ self.name,
                 self.language,
                 self.version,
                 self.typeOfFramework,
                 self.cotationOfFramework,
                 self.pros,
                 self.cons,
                 self.additionalInformation]

View:

    def index(request):
        context = {}
        context['form'] = ConfiguratorForm()
        return render(request, "forms/configurator.html", context)
        """all the configurator algorithm"""
        if request.method == 'POST':

               form = ConfiguratorForm(request.POST)

            #Check if the form is valid:
            if form.is_valid():
                typeOfProject = form.cleaned_data['typeOfTheproject']
                wantedFramework = form.cleaned_data['wantedFramework']
                listOfmember = form.cleaned_data['listOfmember']
                print(typeOfProject, wantedFramework, listOfmember)
#if the project is a web application, then 2 kind of framework are needed
            #need to parse instances of the form
            #get the database

            listOfProject = TypeOfProgram.objects.all()
            listOfFramework = Framework.objects.all()
            listOfLanguages = Language.objects.all()

            easiestChoice = ""
            bestChoice = ""
            otherChoices = [""]

            if typeOfproject == 'Web Application':
                typeOfproject = ["Backend", "Frontend"]
            else:
                print("hello world")
            neededFramework = []

            #take all the needed framework asked by the team
            for i in range(len(wantedFramework)):
                neededFramework.append(wantedFramework[i])

            #configure easiest choice
            #for all type of the project (needed for web development)
            for i in range(len(typeOfproject)):

                #for all asked framework
                for j in neededFramework:

                    #for all framework
                    for k in Framework.objects.value_list("name"):

                        #check if k is a good framework for the project
                        for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=k)
                            if l == currentFramework.typeOfFramework:

                                #verify they are the same
                                if k == i:
                                    if easiestChoice == "":
                                        easiestChoice = i
                                    #check the cotation
                                    else:
                                        check = Framework.objects.filter(name = i)
                                        check2 = Framework.objects.filter(name = easiestChoice)

                                        if check.cotationOfFramework > check2.cotationOfFramework:
                                            easiestChoice = i

            #configure best choice
            for i in range(len(typeOfproject)):
                for j in listOfFramework:
                    for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=j)
                            if l == currentFramework.typeOfFramework:
                                if bestChoice =="":
                                    bestChoice = j
                                else:
                                    check = Framework.objects.filter(name = bestChoice)
                                    if j.cotation > check.cotation:
                                        bestChoice = j.name

            #give all other choices

            for i in range(len(typeOfproject)):
                for j in listOfFramework:
                    for l in typeOfproject:
                            currentFramework = Framework.objects.filter(name=j)
                            if l == currentFramework.typeOfFramework:
                                otherChoices.append(j.name)

            return render(request, 'forms/configurator.html')

    return render(request, 'forms/configurator.html')

Trace:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/configurator/

Django Version: 3.0
Python Version: 3.7.2
Installed Applications:
['configurator.apps.ConfiguratorConfig',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']

Template error:
In template C:\Users\victo\OneDrive\Documents\BAC 3\Projet Individuel\1920_INFOB318_CPDI\code\ProjetIndividuel\CPDI\configurator\templates\forms\configurator.html, error at line 5
   too many values to unpack (expected 2)
   1 : {% block content %}
   2 :
   3 : <form method="post">
   4 :     {% csrf_token %}
   5 :      {{ form }}
   6 :     <input type="submit" value="Submit">
   7 : </form>
   8 : {% endblock %}

Traceback (most recent call last):
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\victo\OneDrive\Documents\BAC 3\Projet Individuel\1920_INFOB318_CPDI\code\ProjetIndividuel\CPDI\configurator\views.py", line 18, in index
    return render(request, "forms/configurator.html", context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\shortcuts.py", line 19, in render
    content = loader.render_to_string(template_name, context, request, using=using)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\loader.py", line 62, in render_to_string
    return template.render(context, request)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\backends\django.py", line 61, in render
    return self.template.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 171, in render
    return self._render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 163, in _render
    return self.nodelist.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\loader_tags.py", line 53, in render
    result = self.nodelist.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 936, in render
    bit = node.render_annotated(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 903, in render_annotated
    return self.render(context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 992, in render
    return render_value_in_context(output, context)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\template\base.py", line 971, in render_value_in_context
    value = str(value)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\utils\html.py", line 373, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 137, in __str__
    return self.as_table()
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 279, in as_table
    errors_on_separate_row=False,
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\forms.py", line 238, in _html_output
    'field_name': bf.html_name,
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\utils\html.py", line 373, in <lambda>
    klass.__str__ = lambda self: mark_safe(klass_str(self))
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 33, in __str__
    return self.as_widget()
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 89, in as_widget
    attrs = self.build_widget_attrs(attrs, widget)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\boundfield.py", line 224, in build_widget_attrs
    if widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute:
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\widgets.py", line 702, in use_required_attribute
    return use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice)
  File "C:\Users\victo\OneDrive\Documents\Django\ProjetIndividuel\env\lib\site-packages\django\forms\widgets.py", line 688, in _choice_has_empty_value
    value, _ = choice

Exception Type: ValueError at /configurator/
Exception Value: too many values to unpack (expected 2)

Body:
You code is ver wired...

Choice fields expect to obtain a tuple or a list type: key - value

to fix too many values to unpack (expected 2) change this lines in your form:

typeOfTheproject = forms.ChoiceField(choices = listProject)
wantedFramework = forms.MultipleChoiceField(choices = listFramework)

for:

FIRST VERSION CODE:

class ConfiguratorForm(forms.Form):
    queryOfProject = TypeOfProgram.objects.values_list('name')
    queryOfFramework = Framework.objects.values_list('name', 'version')
    listOfProject = []
    listOfFramework = []
    listOfFramework += queryOfFramework
    listOfProject += queryOfProject
    listFramework = []
    listProject = []

    for i in range(0,len(listOfFramework)):
       listFramework.append(listOfFramework[i]['name'] + " " +listOfFramework[i]['version'])
    for i in range(0,len(listOfProject)):
       listProject.append(listOfProject[i]['name'])

    typeOfTheproject = forms.ChoiceField(choices=[(x, x) for x in listProject])  # <---
    wantedFramework = forms.MultipleChoiceField(choices=[(x, x) for x in listFramework])  # <---

SECOND VERSION CODE:

class ConfiguratorForm(forms.Form):
    queryOfProject = TypeOfProgram.objects.values_list('name')
    queryOfFramework = Framework.objects.values_list('name','version')
    listFramework = []
    listProject = []
    listFramework=[(q['name'], q['version'])for q in queryOfFramework]    # <---
    listProject =[(q['name'])for q in queryOfProject]    # <---

    print("list of")
    print(listFramework)
    print(listProject)
    typeOfTheproject = forms.ChoiceField(choices = listProject)
    wantedFramework = forms.MultipleChoiceField(choices = listFramework)


问:
Why I got out_of_range?
My function has to reverse the vector's values, but I got an out_of_range exception in one case. Please, explain to me what a difference between this to cases:</p>

```<code>/// working version of my function
void Reverse(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {
        int temp = v[i];
        v[i] = v[v.size() - (i + 1)]; /// look at round brackets
        v[v.size() - (i + 1)] = temp;
    }
}
/// wrong version
void Reverse2(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {

        int temp = v[i];
        v[i] = v[v.size() - i + 1];   /// this is wrong
        v[v.size() - i + 1] = temp;   /// same
    }
}
///
int main()
{
    vector<int> v = { 10, 22, 13, 144, 55, 167, 999};
    Reverse(v);
    for (auto c : v)
    {
        cout << c << " ";
    }
}
</code>```

答:
v.size() - i + 1 for when i = 0 is the same as v.size() - 0 + 1 or v.size() + 1 which is clearly an out of bounds reference to v.

Using the parenthesis will give you v.size() - 1, or the last element of the vector.

Title: Why I got out_of_range?

Body:
My function has to reverse the vector's values, but I got an out_of_range exception in one case. Please, explain to me what a difference between this to cases:

/// working version of my function
void Reverse(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {
        int temp = v[i];
        v[i] = v[v.size() - (i + 1)]; /// look at round brackets
        v[v.size() - (i + 1)] = temp;
    }
}
/// wrong version
void Reverse2(vector<int>& v)
{
    for (int i = 0; i < v.size() / 2; i++)
    {

        int temp = v[i];
        v[i] = v[v.size() - i + 1];   /// this is wrong
        v[v.size() - i + 1] = temp;   /// same
    }
}
///
int main()
{
    vector<int> v = { 10, 22, 13, 144, 55, 167, 999};
    Reverse(v);
    for (auto c : v)
    {
        cout << c << " ";
    }
}


问:
Pygame display does not update
I am making a game in pygame, but the display doesn't update. I am using the update() function and am clearing the screen at the beginning of the loop with fill(). Pygame also does not load very quickly; I have to hit "quit" on the pygame application once it shows in the running applications on my mac for the screen to appear. </p>

```<code>"Module Imports"
import pygame as pg
import shelve

"Import Classes"
from Settings import Settings
from Settings import Screen
from Settings import Save
from Random import Random
from Input import Input
from Input import Button
# Init Classes
Settings = Settings()
Screen = Screen()
Random = Random()
Save = Save()

on = True

pg.init()

event_const = pg.event.wait()

save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")

clock = pg.time.Clock()
MainDisplay = pg.display.set_mode((Screen.width, Screen.height))
pg.display.set_caption(Settings.title)
pg.display.init()

class Mouse:
    def __init__(self):
        self.left = False
        self.right = False

Mouse = Mouse()

def begin_game():
    players = []
    num_players = input("How Many Players (enter int): ")

    save_file["num_players_var"] = num_players

    for pl in range(num_players):
        players.append(raw_input("Enter Player Name: "))

    save_file["players_var"] = players

    print(players)

def intro():
    intro = True

    for event in pg.event.get():
        if event.get == pg.QUIT:
            intro = False
            on = False
        if event.get == pg.event.KEYDOWN:
            pass

# begin_game()

test_button = Button(0, 0, 200, 200, "Enter Text Here", MainDisplay)
buttons = []
buttons.append(test_button)

loops = 0

test_x = 10
test_y = 10

while on:
    MainDisplay.fill((0, 0, 0))
    for event in pg.event.get():
        if event.type == pg.QUIT:
            On = False
            pg.quit()
            exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                On = False
                pg.quit()
                exit()
            if event.key == pg.K_RIGHT:
                test_x += 10
                print("right")
        if event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
            else:
                Mouse.left = False
        if event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False

    for button in buttons:
        button.draw(pg.mouse.get_pos(), event_const)
        if button.clicked is True:
            print("True \n" * 100)

    pg.draw.line(MainDisplay, (255, 0, 0), (100, 100), (600, 600))
    pg.draw.rect(MainDisplay, (255, 0, 0), (test_x, test_y, 20, 20))

    pg.display.flip()
    pg.display.update()
    clock.tick(Settings.FPS)
    loops += 1
    print(str(loops))
</code>```

答:
I suspect the waiting for an event, or reading of the stdin with input() is causing a lockup issue. But in the presented code, the call to this is commented-out.  It's not possible to really know.

This version of the code, with a re-created Button class works ok, but obviously it doesn't have any of the referenced classes.

```<code>"Module Imports"
import pygame
#import shelve

"Import Classes"
#from Settings import Settings
#from Settings import Screen
#from Settings import Save
#from Random import Random
#from Input import Input
#from Input import Button
# Init Classes
#Settings = Settings()
#Screen = Screen()
#Random = Random()
#Save = Save()

WINDOW_WIDTH  = 600
WINDOW_HEIGHT = 600

class Mouse:
    def __init__(self):
        self.left = False
        self.right = False

class Button:
    def __init__( self, x, y, width, height, label, window ):
        self.rect    = pygame.Rect( x, y, width, height )
        self.clicked = False
        self.window  = window
        self.font    = pygame.font.Font( None, 20 )
        self.label   = self.font.render( label, True, ( 255, 255, 255 ) ) # large white text

    def draw( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            colour = ( 0, 200, 0 )  # green if mouse over
        else:
            colour = (0, 0, 200)    # blue otherwise
        pygame.draw.rect( self.window, colour, self.rect, 0 )  # filled rectangle
        # centred text
        label_rect = self.label.get_rect()
        x_offset = ( self.rect.width  - label_rect.width ) // 2
        y_offset = ( self.rect.height - label_rect.height ) // 2
        self.window.blit( self.label, ( x_offset, y_offset ) )

    def checkClick( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            self.clicked = True
        else:
            self.clicked = False

def begin_game():
    players = [ "Mork", "Mindy", "E.T." ]   # test data
    #players = []
    #num_players = input("How Many Players (enter int): ")
    #save_file["num_players_var"] = num_players
    #for pl in range(num_players):
    #    players.append(raw_input("Enter Player Name: "))
    #save_file["players_var"] = players
    print(players)

# Initialisation
pygame.init()
pygame.font.init()
#event_const = pygame.event.wait()
#save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")
clock = pygame.time.Clock()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption( "Settings.title" )
pygame.display.init()

Mouse = Mouse()
begin_game()
test_button = Button(0, 0, 200, 200, "Enter Text Here", window)
buttons = []
buttons.append(test_button)

loops = 0
test_x = 10
test_y = 10

on = True
while on:
    window.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            on = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                on = False
            elif event.key == pygame.K_RIGHT:
                test_x += 10
                print("right")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False
                for button in buttons:
                    button.checkClick( event.pos )  # buttons actuate on mouse-up

    for button in buttons:
        button.draw( pygame.mouse.get_pos() ) #, event_const)
        if button.clicked is True:
            print("True \n" * 5) # 100

    pygame.draw.line(window, (255, 0, 0), (100, 100), (600, 600))
    pygame.draw.rect(window, (255, 0, 0), (test_x, test_y, 20, 20))

    pygame.display.flip()
    #pygame.display.update()   # only need update() or flip()
    clock.tick( 60 ) #Settings.FPS)
    loops += 1
    #print(str(loops))   # Too noisy

# exiting
pygame.quit()
</code>```

Title: Pygame display does not update

Body:
I am making a game in pygame, but the display doesn't update. I am using the update() function and am clearing the screen at the beginning of the loop with fill(). Pygame also does not load very quickly; I have to hit "quit" on the pygame application once it shows in the running applications on my mac for the screen to appear.

"Module Imports"
import pygame as pg
import shelve

"Import Classes"
from Settings import Settings
from Settings import Screen
from Settings import Save
from Random import Random
from Input import Input
from Input import Button
# Init Classes
Settings = Settings()
Screen = Screen()
Random = Random()
Save = Save()

on = True

pg.init()

event_const = pg.event.wait()

save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")

clock = pg.time.Clock()
MainDisplay = pg.display.set_mode((Screen.width, Screen.height))
pg.display.set_caption(Settings.title)
pg.display.init()

class Mouse:
    def __init__(self):
        self.left = False
        self.right = False

Mouse = Mouse()

def begin_game():
    players = []
    num_players = input("How Many Players (enter int): ")

    save_file["num_players_var"] = num_players

    for pl in range(num_players):
        players.append(raw_input("Enter Player Name: "))

    save_file["players_var"] = players

    print(players)

def intro():
    intro = True

    for event in pg.event.get():
        if event.get == pg.QUIT:
            intro = False
            on = False
        if event.get == pg.event.KEYDOWN:
            pass

# begin_game()

test_button = Button(0, 0, 200, 200, "Enter Text Here", MainDisplay)
buttons = []
buttons.append(test_button)

loops = 0

test_x = 10
test_y = 10

while on:
    MainDisplay.fill((0, 0, 0))
    for event in pg.event.get():
        if event.type == pg.QUIT:
            On = False
            pg.quit()
            exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                On = False
                pg.quit()
                exit()
            if event.key == pg.K_RIGHT:
                test_x += 10
                print("right")
        if event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
            else:
                Mouse.left = False
        if event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False

    for button in buttons:
        button.draw(pg.mouse.get_pos(), event_const)
        if button.clicked is True:
            print("True \n" * 100)

    pg.draw.line(MainDisplay, (255, 0, 0), (100, 100), (600, 600))
    pg.draw.rect(MainDisplay, (255, 0, 0), (test_x, test_y, 20, 20))

    pg.display.flip()
    pg.display.update()
    clock.tick(Settings.FPS)
    loops += 1
    print(str(loops))

Body:
I suspect the waiting for an event, or reading of the stdin with input() is causing a lockup issue. But in the presented code, the call to this is commented-out.  It's not possible to really know.

This version of the code, with a re-created Button class works ok, but obviously it doesn't have any of the referenced classes.

"Module Imports"
import pygame
#import shelve

"Import Classes"
#from Settings import Settings
#from Settings import Screen
#from Settings import Save
#from Random import Random
#from Input import Input
#from Input import Button
# Init Classes
#Settings = Settings()
#Screen = Screen()
#Random = Random()
#Save = Save()

WINDOW_WIDTH  = 600
WINDOW_HEIGHT = 600

class Mouse:
    def __init__(self):
        self.left = False
        self.right = False

class Button:
    def __init__( self, x, y, width, height, label, window ):
        self.rect    = pygame.Rect( x, y, width, height )
        self.clicked = False
        self.window  = window
        self.font    = pygame.font.Font( None, 20 )
        self.label   = self.font.render( label, True, ( 255, 255, 255 ) ) # large white text

    def draw( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            colour = ( 0, 200, 0 )  # green if mouse over
        else:
            colour = (0, 0, 200)    # blue otherwise
        pygame.draw.rect( self.window, colour, self.rect, 0 )  # filled rectangle
        # centred text
        label_rect = self.label.get_rect()
        x_offset = ( self.rect.width  - label_rect.width ) // 2
        y_offset = ( self.rect.height - label_rect.height ) // 2
        self.window.blit( self.label, ( x_offset, y_offset ) )

    def checkClick( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            self.clicked = True
        else:
            self.clicked = False

def begin_game():
    players = [ "Mork", "Mindy", "E.T." ]   # test data
    #players = []
    #num_players = input("How Many Players (enter int): ")
    #save_file["num_players_var"] = num_players
    #for pl in range(num_players):
    #    players.append(raw_input("Enter Player Name: "))
    #save_file["players_var"] = players
    print(players)

# Initialisation
pygame.init()
pygame.font.init()
#event_const = pygame.event.wait()
#save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")
clock = pygame.time.Clock()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption( "Settings.title" )
pygame.display.init()

Mouse = Mouse()
begin_game()
test_button = Button(0, 0, 200, 200, "Enter Text Here", window)
buttons = []
buttons.append(test_button)

loops = 0
test_x = 10
test_y = 10

on = True
while on:
    window.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            on = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                on = False
            elif event.key == pygame.K_RIGHT:
                test_x += 10
                print("right")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False
                for button in buttons:
                    button.checkClick( event.pos )  # buttons actuate on mouse-up

    for button in buttons:
        button.draw( pygame.mouse.get_pos() ) #, event_const)
        if button.clicked is True:
            print("True \n" * 5) # 100

    pygame.draw.line(window, (255, 0, 0), (100, 100), (600, 600))
    pygame.draw.rect(window, (255, 0, 0), (test_x, test_y, 20, 20))

    pygame.display.flip()
    #pygame.display.update()   # only need update() or flip()
    clock.tick( 60 ) #Settings.FPS)
    loops += 1
    #print(str(loops))   # Too noisy

# exiting
pygame.quit()


问:
Is there any way to to send large file through API Gateway?
I'm working on the application that will receive files from users and then upload to Amazon S3. The application is accessed using API Gateway. The service API Gateway has limits for payload size for both WebSocket and REST APIs. Is there any way to access my service from the Internet through API Gateway?

答:
API gateway is not intended to be data transfer gateway, but lightweight API definition layer.

The most suitable approach is to generate temporary pre-signed upload URL and redirect (30X) requests there. API Gateway should define an endpoint, calling lambda function which generates pre-signed S3 URL and redirect post request there (after user's authentication of course).

Please refer an example of app with API Gateway and pre-signed S3 URLs to upload files

API documentation for generating pre-signed S3 URLs in Python, AWS CLI and even Go-lang


问:
jQuery html() function with javascript
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

```<code>$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});
</code>```

ajaxpage.php

```<code><html>
<body>
<div id="content">
   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</div>
</body>
</html>
</code>```

$(html).find('#content').html() returns

```<code>   //SOME HTML
</code>```

while I want

```<code>   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</code>```

答:
I have tried with filter but it only return the html part

```<code> $('#content').html($(html).filter('#content'));
</code>```

But when I tried with filter along with prevObject

i.e

```<code>$('#content').html($(html).filter('#content').prevObject);
</code>```

it returns the html part (visible in firebug) as well as the javascript(not visible in firebug).

ContentLicense: CC BY-SA 3.0

Title: jQuery html() function with javascript

Body:
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});

ajaxpage.php

   //SOME HTML

$(html).find('#content').html() returns

   //SOME HTML

while I want

   //SOME HTML

Body:
I have tried with filter but it only return the html part

 $('#content').html($(html).filter('#content'));

But when I tried with filter along with prevObject

i.e

$('#content').html($(html).filter('#content').prevObject);

it returns the html part (visible in firebug) as well as the javascript(not visible in firebug).


问:
Meaning of v-slot:activator="{ on }"
Looking at the Vuetify example code for v-toolbar, what is the purpose of v-slot:activator="{ on }"? For example:

<template v-slot:activator="{ on }">
  <v-toolbar-title v-on="on">
    All
    <v-icon dark>arrow_drop_down</v-icon>
  </v-toolbar-title>
</template>

```

As far as I can see, on is not a defined variable anywhere, so I don't see how this is working. When I try it in my project, Internet Explorer throws an error on the <template v-slot:activator="{ on }">, but if I remove it, the page renders.

答:
I think the original question is about understanding the "on" object.  It is best explained here:

https://github.com/vuetifyjs/vuetify/issues/6866

Essentially "on" is a prop passed in from the activator. What v-on="on" does is bind that on prop to the component. "on" itself is all of the event listeners passed from the activator.

Title: Meaning of v-slot:activator="{ on }"

Body:
Looking at the Vuetify example code for v-toolbar, what is the purpose of v-slot:activator="{ on }"? For example:

<template v-slot:activator="{ on }">
  <v-toolbar-title v-on="on">
    All
    <v-icon dark>arrow_drop_down</v-icon>
  </v-toolbar-title>
</template>

As far as I can see, on is not a defined variable anywhere, so I don't see how this is working. When I try it in my project, Internet Explorer throws an error on the <template v-slot:activator="{ on }">, but if I remove it, the page renders.


问:
c# stopwatch.startnew() always returns 0
I have this loop that I want to measure the speed of:

```<code>        private static string[] sequentialTest(string[] thisstringlist)
    {
        var watch = Stopwatch.StartNew();

        string[] returnList = new string[2150];
        for (int i = 0; i < thisstringlist.Length; ++i)
        {
            int thisI = i;
            returnList[i] = thisstringlist[i] + "pluuus this";
        }
        int thiss = 0;

        var elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine("execution time" + watch.ElapsedMilliseconds);

        return returnList;

    }
</code>```

Should be really simple, the stopwatch should just measure how long this operation takes, but i keeps returning 0

I have also tried inserting thread.sleep(), just to force the code to take some time, but that doesnt work either

答:
```<code> private static string[] sequentialTest(string[] thisstringlist)
    {
     Stopwatch stopwatch = new Stopwatch();
      stopwatch.Start();
      string[] returnList = new string[2150];
        for (int i = 0; i < thisstringlist.Length; ++i)
        {
            int thisI = i;
            returnList[i] = thisstringlist[i] + "pluuus this";
        }
        int thiss = 0;
       Console.WriteLine("execution time" + stopwatch.Elapsed.TotalMilliseconds);
      stopwatch.Stop();
   }
</code>```

Body:
I have this loop that I want to measure the speed of:

        private static string[] sequentialTest(string[] thisstringlist)
    {
        var watch = Stopwatch.StartNew();

        string[] returnList = new string[2150];
        for (int i = 0; i < thisstringlist.Length; ++i)
        {
            int thisI = i;
            returnList[i] = thisstringlist[i] + "pluuus this";
        }
        int thiss = 0;

        var elapsedMs = watch.ElapsedMilliseconds;
        Console.WriteLine("execution time" + watch.ElapsedMilliseconds);

        return returnList;

    }

Should be really simple, the stopwatch should just measure how long this operation takes, but i keeps returning 0

I have also tried inserting thread.sleep(), just to force the code to take some time, but that doesnt work either


问:
Test a substring with special character in a list
I have a list with some application landscape names and I have to look for an specific application with special characters in Jinja2

landscape_list: ["cmdb:app1 landscape", "cmdb:app2 (ex app3) landscape",
  "cmdb:app4 landscape"]

  app_to_look: "app2 (ex app3)"

I'm trying to use this code to test the list:

```<code>{{landscape_list | select('search',land_key) | list | count > 0}}
</code>```

But I'm always getting 0 when I tried to test "app2 (ex app3)".

I think this problem is related with special characters like ().

Is it possible to look into a list for that specific application in jinja2?

Thanks

答:
Q: "This problem is related to special characters like ()."

A: Yes. The parenthesis must be escaped in the regex. For example

```<code>    - set_fact:
        land_key: 'app2 \(ex app3\)'
    - debug:
        msg: "{{ landscape_list|select('search', land_key)|list }}"
    - debug:
        msg: "{{ landscape_list|select('search', land_key)|list|length }}"
    - debug:
        msg: One or more items match the searched pattern.
      when: landscape_list|select('search', land_key)|list|length > 0
</code>```

give

```<code>    "msg": [
        "cmdb:app2 (ex app3) landscape"
    ]

    "msg": "1"

    "msg": "One or more items match the searched pattern."
</code>```

Body:
I have a list with some application landscape names and I have to look for an specific application with special characters in Jinja2

landscape_list: ["cmdb:app1 landscape", "cmdb:app2 (ex app3) landscape",
  "cmdb:app4 landscape"]

  app_to_look: "app2 (ex app3)"

I'm trying to use this code to test the list:

{{landscape_list | select('search',land_key) | list | count > 0}}

But I'm always getting 0 when I tried to test "app2 (ex app3)".

I think this problem is related with special characters like ().

Is it possible to look into a list for that specific application in jinja2?

Thanks

Body:
Q: "This problem is related to special characters like ()."

A: Yes. The parenthesis must be escaped in the regex. For example

    - set_fact:
        land_key: 'app2 \(ex app3\)'
    - debug:
        msg: "{{ landscape_list|select('search', land_key)|list }}"
    - debug:
        msg: "{{ landscape_list|select('search', land_key)|list|length }}"
    - debug:
        msg: One or more items match the searched pattern.
      when: landscape_list|select('search', land_key)|list|length > 0

give

    "msg": [
        "cmdb:app2 (ex app3) landscape"
    ]

    "msg": "1"

    "msg": "One or more items match the searched pattern."


问:
Delete a table row with dynamic id that comes from DB using ajax
I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .

$('.dashboard-subscribe-form').submit(() => {
  event.preventDefault();
  const currentHiddBtn = $('.dash-subscribe-form-btn');
  console.log(currentHiddBtn.closest('tr'));

  const userCaution = confirm('Want to delete this quote?');
  if (userCaution) { //If admin insists to delete the row
    const deleteId = $('.dash-subscribe-form-btn').attr('value');
    $.ajax({
      type: "POST",
      url: "delete-subscribe.php",
      dataType: "json",
      data: {
        deleteId: deleteId
      },
      success: (data) => {
        if (data.code === '200') {
          console.log('It works!');
          currentHiddBtn.closest('tr').css('background', 'tomato');
          currentHiddBtn.closest('tr').fadeOut(1200, () => {

          });

        } else if (data.code === '404') {
          alert('An error occurred!Please try again.');
        }
      }
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tbody>
  <?php
       $count = 1;
       $sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
       $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
       $sqlCommandPrepare->execute();
       while ($result = $sqlCommandPrepare->fetch()) {
   ?>
   <tr id="row-<?php echo $result['id']; ?>">
      <td class="dashboard-records">
        <?php echo $count; ?>
      </td>
      <td class="dashboard-records">
        <?php echo $result['email']; ?>
      </td>
      <td>
        <form action="" method="post" class="dashboard-subscribe-form">
          <input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
          <button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
           </button>
        </form>
      </td>
    </tr>
    <?php
     $count++;
       }
     ?>
</tbody></code>```

delete-subscribe.php:

<?php
require_once('config.php');

$delete_row = $_POST['deleteId'];

if($delete_row){
    $sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
    $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
    $result = $sqlCommandPrepare->execute([

        $delete_row

    ]);

    /*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
       last line of code) */
    echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
    echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}
```

<hr>

<p>UPDATE2: now I'm using :</p>

``` $('#row-' + deleteId).css('background', 'tomato');
                    $('#row-' + deleteId).fadeOut(1200, () => {

                    });
```

but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?

答:
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.

The code causing this is:

const deleteId = $('.dash-subscribe-form-btn').attr('value');
```

<p>You want to be getting the target input from the <code>event</code> object passed from your <code>.submit()</code>.</p>

<p>I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.</p>

<pre class="lang-js prettyprint-override"><code>$('.dashboard-subscribe-form').submit((event) => {
  event.preventDefault()
  console.log(event.target.elements[0]["value"])
  $('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})
</code>```

It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]

You could then also use the value returned to remove the
 with the same  id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.

Body:
I have a table that it's content is comes from database.When I click on the delete button I want to delete that row with Ajax. Actually right now it's working but with a bug and that is all of the rows get deleted when I click on the button and then if I refresh , the row that I was deleted is gone and other rows are shown.But as I said it needs a refresh.Any solution would be appreciated .

$('.dashboard-subscribe-form').submit(() => {
  event.preventDefault();
  const currentHiddBtn = $('.dash-subscribe-form-btn');
  console.log(currentHiddBtn.closest('tr'));

  const userCaution = confirm('Want to delete this quote?');
  if (userCaution) { //If admin insists to delete the row
    const deleteId = $('.dash-subscribe-form-btn').attr('value');
    $.ajax({
      type: "POST",
      url: "delete-subscribe.php",
      dataType: "json",
      data: {
        deleteId: deleteId
      },
      success: (data) => {
        if (data.code === '200') {
          console.log('It works!');
          currentHiddBtn.closest('tr').css('background', 'tomato');
          currentHiddBtn.closest('tr').fadeOut(1200, () => {

          });

        } else if (data.code === '404') {
          alert('An error occurred!Please try again.');
        }
      }
    });
  }
});

  <?php
       $count = 1;
       $sqlCommand = "SELECT * FROM `kq0b3_subscribe`";
       $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
       $sqlCommandPrepare->execute();
       while ($result = $sqlCommandPrepare->fetch()) {
   ?>
   <tr id="row-<?php echo $result['id']; ?>">

        <?php echo $count; ?>

        <?php echo $result['email']; ?>

        <form action="" method="post" class="dashboard-subscribe-form">
          <input id="<?php echo $result['id']; ?>" type="hidden" class="dash-subscribe-form-btn" name="hidden-del" value='<?php echo $result[' id ']; ?>'/>
          <button type="submit" name="sub-del-btn" class="btn btn-danger del" value='<?php echo $result[' id ']; ?>'> Delete
           </button>
        </form>

    <?php
     $count++;
       }
     ?>

delete-subscribe.php:

<?php
require_once('config.php');

$delete_row = $_POST['deleteId'];

if($delete_row){
    $sqlCommand = "DELETE FROM `kq0b3_subscribe` WHERE `id` = ?";
    $sqlCommandPrepare = $pdoObject->prepare($sqlCommand);
    $result = $sqlCommandPrepare->execute([

        $delete_row

    ]);

    /*The json_encode() must be after all of our calculation codes and DB query codes and...(It must be the
       last line of code) */
    echo json_encode(['code' => '200'], JSON_THROW_ON_ERROR, 512);
}
else {
    echo json_encode(['code' => '404'], JSON_THROW_ON_ERROR, 512);
}

UPDATE2: now I'm using :

 $('#row-' + deleteId).css('background', 'tomato');
                    $('#row-' + deleteId).fadeOut(1200, () => {

                    });

but the new problem is : it doesn't matter which button I click, the forst row is deleted (when any button is clicked , in the console , the id of the first row-button is printed , not the actual id that I was clicked. ).How can I fix this one?

Body:
I think the main issue, in this case, is using CSS classes as a selector and it seems to be selecting the first instance no matter which item you are clicking.

The code causing this is:

const deleteId = $('.dash-subscribe-form-btn').attr('value');

You want to be getting the target input from the event object passed from your .submit().

I have created a jsfiddle with an example that could be adapted to your code but here is a quick preview of jQuery part.

$('.dashboard-subscribe-form').submit((event) => {
  event.preventDefault()
  console.log(event.target.elements[0]["value"])
  $('#result-from-click').html("Input Value: " + event.target.elements[0]["value"])
})

It is selecting the first element within the elements array which is the input. If you want the button you can use event.target.elements[1]

You could then also use the value returned to remove the <tr> with the same  id instead of finding the nearest. This could be done in the success part of your ajax call without doing a refresh.


问:
Different validation annotation rule for same Data Access Object
How to customize the validation annotation based on some criteria using javax validation with Hibernate validation implementation.

Sample code:

```<code>import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;

import org.springframework.stereotype.Component;

import com.kp.mechanic.workshop.validator.beans.GeoLocation;
import com.kp.mechanic.workshop.validator.beans.Practioner;
import com.kp.mechanic.workshop.validator.beans.PractionerAddress;

@Component("validator")
public class ValidatorService {

    private  Validator validator;
    private  ValidatorFactory factory;

    public void execute() {
        System.out.println(" Validation framework starts");
        try {

            //  < DAO call to get GEO Location is AUS >

            //Construct Geo Location:
            GeoLocation geoLocation= new GeoLocation();
            geoLocation.setStrtAddrLine1("walker street ");
            geoLocation.setOptionalAddrLine2("bonitoa road");
            geoLocation.setZipCD("SY");

             factory = Validation.buildDefaultValidatorFactory();
             validator = factory.getValidator();
             Set<ConstraintViolation<Object>> resultSet= validator.validate(geoLocation);

             for (ConstraintViolation<Object> object : resultSet) {
                   System.out.println(object.getPropertyPath() + ": " + object.getMessage());
               }

        }
        catch(Exception e) {
            System.out.println("Message "+e);
            e.printStackTrace();
        }

    }
}
</code>```

Refer the given below POJO using Lombok.

```<code>import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class GeoLocation {
//City name
        @NotNull(message="warn:Missing data")
        @Size(min =3 , max =50, message = "warn:Invalid length")
        @Pattern(regexp = "^a-zA-Z",message = "warn:Invalid characters found in text",flags=Pattern.Flag.CASE_INSENSITIVE)
        private String cityNM;

        //State Code
        @NotNull(message="warn:Missing data")
        @Size(min =2 , max =2, message = "warn:Invalid Length")
        @Pattern(regexp = "^[a-zA-Z]",message = "warn:Invalid characters found in text",flags=Pattern.Flag.CASE_INSENSITIVE)
        private String stateCD;

        //zip code
        @NotNull(message="warn:Missing data")
        @Size(min =5 , max =9, message = "warn:Invalid Length")
        @Pattern(regexp = "^[0-9]",message = "warn:Invalid characters found in text")
        private String zipCD;
}
</code>```

Using given above pom entries .

The above code is working fine for  the given below validation rules for  GEO Location is  "AUS".

```<code>> CityName   : not null , minimum 3 and maximum 50 characters, only alphabets.
> State Code : not null , maximum 2 , only alphabets.
> Zip  Code  : not null , minimum 5 and maximum 9, only digits.
</code>```

Where as for "IND" , i would like to change the given below validation rules as such.

```<code>> CityName   : not null , minimum 10 and maximum 15 characters, only alphabets
> State Code : not null , maximum 6, only alphabets.
> Zip  Code  : not null , maximum 10, only digits
</code>```

Can you  give any suggestion to change the validation rules based on the geo location type is IND?

This is a kind of Custom Annotation, is there any better approach to reuse the annotation without writing java logic in custom annotation class ?
Custom Annotation for cross fields

答:
I got reference from given below links.

stackover flow .

Programmatic constraint definition

```<code> HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
             ConstraintMapping constraintMapping = configuration.createConstraintMapping();
 if(geoLocation.getType().equals("AUS")) {
                 constraintMapping
                 .type(GeoLocation.class)
                 .property("cityName", ElementType.FIELD)
                 .constraint(new NotNullDef().message("cityName should not empty"))
                 .constraint(new SizeDef().min(3).message("Minimum 3 charater"))
                 .constraint(new SizeDef().max(50).message("Maximum 50 character"));
                 }else if(geoLocation.getType().equals("IND")) {
                     constraintMapping
                     .type(GeoLocation.class)
                     .property("cityName", ElementType.FIELD)
                     .constraint(new NotNullDef().message("cityName should not empty"))
                     .constraint(new SizeDef().min(10).message("Minimum 10 charater"))
                     .constraint(new SizeDef().max(15).message("Maximum 15 character"));

                 }

             validator=configuration.addMapping(constraintMapping).buildValidatorFactory().getValidator();
             resultSet= validator.validate(geoLocation);
             for (ConstraintViolation<Object> object : resultSet) {
               System.out.println(object.getPropertyPath() + ": " + object.getMessage());
           }
</code>```

Body:
How to customize the validation annotation based on some criteria using javax validation with Hibernate validation implementation.

Sample code:

import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;

import org.springframework.stereotype.Component;

import com.kp.mechanic.workshop.validator.beans.GeoLocation;
import com.kp.mechanic.workshop.validator.beans.Practioner;
import com.kp.mechanic.workshop.validator.beans.PractionerAddress;

@Component("validator")
public class ValidatorService {

    private  Validator validator;
    private  ValidatorFactory factory;

    public void execute() {
        System.out.println(" Validation framework starts");
        try {

            //  < DAO call to get GEO Location is AUS >

            //Construct Geo Location:
            GeoLocation geoLocation= new GeoLocation();
            geoLocation.setStrtAddrLine1("walker street ");
            geoLocation.setOptionalAddrLine2("bonitoa road");
            geoLocation.setZipCD("SY");

             factory = Validation.buildDefaultValidatorFactory();
             validator = factory.getValidator();
             Set<ConstraintViolation<Object>> resultSet= validator.validate(geoLocation);

             for (ConstraintViolation<Object> object : resultSet) {
                   System.out.println(object.getPropertyPath() + ": " + object.getMessage());
               }

        }
        catch(Exception e) {
            System.out.println("Message "+e);
            e.printStackTrace();
        }

    }
}

Refer the given below POJO using Lombok.

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class GeoLocation {
//City name
        @NotNull(message="warn:Missing data")
        @Size(min =3 , max =50, message = "warn:Invalid length")
        @Pattern(regexp = "^a-zA-Z",message = "warn:Invalid characters found in text",flags=Pattern.Flag.CASE_INSENSITIVE)
        private String cityNM;

        //State Code
        @NotNull(message="warn:Missing data")
        @Size(min =2 , max =2, message = "warn:Invalid Length")
        @Pattern(regexp = "^[a-zA-Z]",message = "warn:Invalid characters found in text",flags=Pattern.Flag.CASE_INSENSITIVE)
        private String stateCD;

        //zip code
        @NotNull(message="warn:Missing data")
        @Size(min =5 , max =9, message = "warn:Invalid Length")
        @Pattern(regexp = "^[0-9]",message = "warn:Invalid characters found in text")
        private String zipCD;
}

Using given above pom entries .

The above code is working fine for  the given below validation rules for  GEO Location is  "AUS".

> CityName   : not null , minimum 3 and maximum 50 characters, only alphabets.
> State Code : not null , maximum 2 , only alphabets.
> Zip  Code  : not null , minimum 5 and maximum 9, only digits.

Where as for "IND" , i would like to change the given below validation rules as such.

> CityName   : not null , minimum 10 and maximum 15 characters, only alphabets
> State Code : not null , maximum 6, only alphabets.
> Zip  Code  : not null , maximum 10, only digits

Can you  give any suggestion to change the validation rules based on the geo location type is IND?

This is a kind of Custom Annotation, is there any better approach to reuse the annotation without writing java logic in custom annotation class ?
Custom Annotation for cross fields

Body:
I got reference from given below links.

stackover flow .

Programmatic constraint definition

 HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
             ConstraintMapping constraintMapping = configuration.createConstraintMapping();
 if(geoLocation.getType().equals("AUS")) {
                 constraintMapping
                 .type(GeoLocation.class)
                 .property("cityName", ElementType.FIELD)
                 .constraint(new NotNullDef().message("cityName should not empty"))
                 .constraint(new SizeDef().min(3).message("Minimum 3 charater"))
                 .constraint(new SizeDef().max(50).message("Maximum 50 character"));
                 }else if(geoLocation.getType().equals("IND")) {
                     constraintMapping
                     .type(GeoLocation.class)
                     .property("cityName", ElementType.FIELD)
                     .constraint(new NotNullDef().message("cityName should not empty"))
                     .constraint(new SizeDef().min(10).message("Minimum 10 charater"))
                     .constraint(new SizeDef().max(15).message("Maximum 15 character"));

                 }

             validator=configuration.addMapping(constraintMapping).buildValidatorFactory().getValidator();
             resultSet= validator.validate(geoLocation);
             for (ConstraintViolation<Object> object : resultSet) {
               System.out.println(object.getPropertyPath() + ": " + object.getMessage());
           }


问:
Append Method Linked List... It keeps deleting the last input
```<code>public void append(int data) {
    Node newNode = new Node(data);

    if (head == null) {
        head = new Node(data);
        return;
    } else {
        Node last = head;
        while(last.nextNode != null) {
            last = last.nextNode;
        }
        last.nextNode = newNode;
    }
    return;
}

public void printList(){
    Node temp = head;
    while (temp != null && temp.nextNode != null){
        System.out.print(temp.data + " " );
        temp = temp.nextNode;
    }
    temp = temp.nextNode;
}
</code>```

Input: 4,5,6,9,9
Output: 4,5,6,9

This is the output I get it keeps deleting the last input.....
Changes made

答:
You forgot to print last node. You check not only if temp is not null, but also if it has next node after it - therefore you exit while loop before last node was actually printed.

Either change conditions or print last node right after while loop (I would suggest first option).

First option:

```<code>public void printList() {
    Node temp = head;
    while (temp != null) {
      System.out.print(temp.data + " ");
      temp = temp.nextNode;
    }
}
</code>```

Second option:

```<code>public void printList(){
    Node temp = head;
    while (temp != null && temp.nextNode != null){
        System.out.print(temp.data + " " );
        temp = temp.nextNode;
    }
    // print last node here
    System.out.print(temp.data);
    temp = temp.nextNode;
}
</code>```

Body:
public void append(int data) {
    Node newNode = new Node(data);

    if (head == null) {
        head = new Node(data);
        return;
    } else {
        Node last = head;
        while(last.nextNode != null) {
            last = last.nextNode;
        }
        last.nextNode = newNode;
    }
    return;
}

public void printList(){
    Node temp = head;
    while (temp != null && temp.nextNode != null){
        System.out.print(temp.data + " " );
        temp = temp.nextNode;
    }
    temp = temp.nextNode;
}

Input: 4,5,6,9,9
Output: 4,5,6,9

This is the output I get it keeps deleting the last input.....
Changes made

Body:
You forgot to print last node. You check not only if temp is not null, but also if it has next node after it - therefore you exit while loop before last node was actually printed.

Either change conditions or print last node right after while loop (I would suggest first option).

First option:

public void printList() {
    Node temp = head;
    while (temp != null) {
      System.out.print(temp.data + " ");
      temp = temp.nextNode;
    }
}

Second option:

public void printList(){
    Node temp = head;
    while (temp != null && temp.nextNode != null){
        System.out.print(temp.data + " " );
        temp = temp.nextNode;
    }
    // print last node here
    System.out.print(temp.data);
    temp = temp.nextNode;
}