问:
In what order does a minheap sort?
I've been reading various definitions on minHeap and maxHeap. I stumbled upon statements which say:

minHeap is used to sort in descending order.

maxHeap is used to sort in ascending order.

Statements taken from the "Note" in https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/ .
But when I implement minHeap using PriorityQueue<Integer> in Java with default comparator, and poll() it, I get the minimum element. Why is that?
Thanks to anybody who's trying to help :).

答:
min-heap and max-heap don't sort. You can use a min-heap or max-heap to sort, but in standard use, heaps aren't sorted. Instead, they arranged in what's called heap order. This arrangement makes it efficient to add items, and to remove the smallest (or largest) while keeping the data in the proper order.

For example, here's an illustration of a min-heap:

```<code>                1
            3       2
          4   7   6   5
</code>```

That follows the rule that no child is larger than its parent. The resulting array representation of that heap is [1,3,2,4,7,6,5]. Note that there are other valid heaps with those same numbers. For example, both of the below are valid, as well:

```<code>                1                          1
            2       5                  2       3
          4   3   6   7              4   5   6   7
</code>```

The corresponding array representations are [1,2,5,4,3,6,7] and [1,2,3,4,5,6,7].

Max-heap is similar, except the rule is that no child can be larger than its parent.

The Wikipedia article on binary heap explains this all very well.

Now, when you're talking about using heap sort, you build a heap and then repeatedly swap the root element with the last element in the array, reduce the count and then re-heapify. So you build the sorted array from back to front. If you use a min-heap, then the root (smallest value) will be at the end of the array.

So if you want to sort in descending order with heap sort, you use a min-heap.

Title: In what order does a minheap sort?

Body:
min-heap and max-heap don't sort. You can use a min-heap or max-heap to sort, but in standard use, heaps aren't sorted. Instead, they arranged in what's called heap order. This arrangement makes it efficient to add items, and to remove the smallest (or largest) while keeping the data in the proper order.

For example, here's an illustration of a min-heap:

                1
            3       2
          4   7   6   5

That follows the rule that no child is larger than its parent. The resulting array representation of that heap is [1,3,2,4,7,6,5]. Note that there are other valid heaps with those same numbers. For example, both of the below are valid, as well:

                1                          1
            2       5                  2       3
          4   3   6   7              4   5   6   7

The corresponding array representations are [1,2,5,4,3,6,7] and [1,2,3,4,5,6,7].

Max-heap is similar, except the rule is that no child can be larger than its parent.

The Wikipedia article on binary heap explains this all very well.

Now, when you're talking about using heap sort, you build a heap and then repeatedly swap the root element with the last element in the array, reduce the count and then re-heapify. So you build the sorted array from back to front. If you use a min-heap, then the root (smallest value) will be at the end of the array.

So if you want to sort in descending order with heap sort, you use a min-heap.


来源: stackexchange

问:
create all possible combinations with multiple variants from list
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

```<code>[12R,102A,250L]
[12R,102L,250L]
</code>```

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

ContentLicense: CC BY-SA 4.0

Body:
Ok so the problem is as follows:

let's say I have a list like this [12R,102A,102L,250L] what I would want is a list of all possible combinations, however for only one combination/number. so for the example above, the output I would like is:

[12R,102A,250L]
[12R,102L,250L]

my actual problem is a lot more complex with many more sites. Thanks for your help

edit: after reading some comments I guess this is slightly unclear. I have 3 unique numbers here, [12, 102, and 250] and for some numbers, I have different variations, for example [102A, 102L]. what I need is a way to combine the different positions[12,102,250] and all possible variations within. just like the lists, I presented above. they are the only valid solutions. [12R] is not. neither is [12R,102A,102L,250L]. so far I have done this with nested loops, but I have a LOT of variation within these numbers, so I can't really do that anymore

ill edit this again: ok so it seems as though there is still some confusion so I might extend the point I made before. what I am dealing with there is DNA. 12R means the 12th position in the sequence was changed to an R. so the solution     [12R,102A,250L] means that the amino acid on position 12 is R, 102 is A 250 is L.

this is why a solution like [102L, 102R, 250L] is not usable, because the same position can not be occupied by 2 different amino acids.

thank you

Body:
So it works with ["10A","100B","12C","100R"] (case 1) and ['12R','102A','102L','250L'] (case 2)

import itertools as it

liste = ['12R','102A','102L','250L']

comb = []
for e in it.combinations(range(4), 3):
    e1 = liste[e[0]][:-1]
    e2 = liste[e[1]][:-1]
    e3 = liste[e[2]][:-1]
    if e1 != e2 and e2 != e3 and e3 != e1:
        comb.append([e1+liste[e[0]][-1], e2+liste[e[1]][-1], e3+liste[e[2]][-1]])
print(list(comb))
# case 1 : [['10A', '100B', '12C'], ['10A', '12C', '100R']]
# case 2 : [['12R', '102A', '250L'], ['12R', '102L', '250L']]


问:
How can I change my React class to a function so that I can include Material UI classes?
After finally managing to set up Emailjs, I am now trying to use Material UI text fields (https://material-ui.com/components/text-fields/#text-field) for a better design.

Unfortunately I cannot manage to add Material UI classes to my code, since I a, not able to change the Class to a Functional Component with a state. Does anyone know how I can change the class to a function so that I can use Material UI designs for my Contact Form?

My EmailJS form (works perfectly fine , only changed my user and template ID before posting it here):

```<code>import React, { Component } from 'react'
import * as emailjs from 'emailjs-com'
import { Button, FormFeedback, Form, FormGroup, Label, Input } from 'reactstrap'

class ContactForm extends Component {
    state = {
        name: '',
        email: '',
        subject: '',
        message: '',
    }
    handleSubmit(e) {
        e.preventDefault()
        const { name, email, subject, message } = this.state
        let templateParams = {
            from_name: email,
            to_name: 'Altes Waschhaus',
            subject: subject,
            message_html: message,
        }
        emailjs.send(
            'gmail',
            'template_XXXXX',
            templateParams,
            'user_XXXXX'
        )
        this.resetForm()
    }
    resetForm() {
        this.setState({
            name: '',
            email: '',
            subject: '',
            message: '',
        })
    }
    handleChange = (param, e) => {
        this.setState({ [param]: e.target.value })
    }
    render() {
        return (
            <>
                    <h1 className="p-heading1">Get in Touch</h1>
                    <Form onSubmit={this.handleSubmit.bind(this)}>
                        <FormGroup controlId="formBasicEmail">
                            <Label className="text-muted">Email address</Label>
                            <Input
                                type="email"
                                name="email"
                                value={this.state.email}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'email')}
                                placeholder="Enter email"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicName">
                            <Label className="text-muted">Name</Label>
                            <Input
                                type="text"
                                name="name"
                                value={this.state.name}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'name')}
                                placeholder="Name"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicSubject">
                            <Label className="text-muted">Subject</Label>
                            <Input
                                type="text"
                                name="subject"
                                className="text-primary"
                                value={this.state.subject}
                                onChange={this.handleChange.bind(this, 'subject')}
                                placeholder="Subject"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicMessage">
                            <Label className="text-muted">Message</Label>
                            <Input
                                type="textarea"
                                name="message"
                                className="text-primary"
                                value={this.state.message}
                                onChange={this.handleChange.bind(this, 'message')}
                            />
                        </FormGroup>
                        <Button variant="primary" type="submit" value="Send">
                            Submit
                        </Button>
                    </Form>
            </>
        )
    }
}
export default ContactForm
</code>```

答:
You don't necessarily need to use only functional based components to use material ui.

You can still use class based components and make use of withStyles to use the classes.

Code Snippet

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
    //etc...
  },
};

class ContactForm extends Component {
    state = {
        name: '',
        email: '',
        subject: '',
        message: '',
    }
    ...
    render() {
        const { classes } = this.props; //<----- grab classes here in the props
        return (
            <>

Get in Touch

                    <Form onSubmit={this.handleSubmit.bind(this)}>
                        <FormGroup controlId="formBasicEmail">
                            Email address
                            <Input
                                type="email"
                                name="email"
                                value={this.state.email}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'email')}
                                placeholder="Enter email"
                            />
                        </FormGroup>
                        ....
            </>
        )
    }
}
export default withStyles(styles)(ContactForm) //<----- see here

```

Body:
After finally managing to set up Emailjs, I am now trying to use Material UI text fields (https://material-ui.com/components/text-fields/#text-field) for a better design.

Unfortunately I cannot manage to add Material UI classes to my code, since I a, not able to change the Class to a Functional Component with a state. Does anyone know how I can change the class to a function so that I can use Material UI designs for my Contact Form?

My EmailJS form (works perfectly fine , only changed my user and template ID before posting it here):

import React, { Component } from 'react'
import * as emailjs from 'emailjs-com'
import { Button, FormFeedback, Form, FormGroup, Label, Input } from 'reactstrap'

class ContactForm extends Component {
    state = {
        name: '',
        email: '',
        subject: '',
        message: '',
    }
    handleSubmit(e) {
        e.preventDefault()
        const { name, email, subject, message } = this.state
        let templateParams = {
            from_name: email,
            to_name: 'Altes Waschhaus',
            subject: subject,
            message_html: message,
        }
        emailjs.send(
            'gmail',
            'template_XXXXX',
            templateParams,
            'user_XXXXX'
        )
        this.resetForm()
    }
    resetForm() {
        this.setState({
            name: '',
            email: '',
            subject: '',
            message: '',
        })
    }
    handleChange = (param, e) => {
        this.setState({ [param]: e.target.value })
    }
    render() {
        return (
            <>

Get in Touch

                    <Form onSubmit={this.handleSubmit.bind(this)}>
                        <FormGroup controlId="formBasicEmail">
                            Email address
                            <Input
                                type="email"
                                name="email"
                                value={this.state.email}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'email')}
                                placeholder="Enter email"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicName">
                            Name
                            <Input
                                type="text"
                                name="name"
                                value={this.state.name}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'name')}
                                placeholder="Name"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicSubject">
                            Subject
                            <Input
                                type="text"
                                name="subject"
                                className="text-primary"
                                value={this.state.subject}
                                onChange={this.handleChange.bind(this, 'subject')}
                                placeholder="Subject"
                            />
                        </FormGroup>
                        <FormGroup controlId="formBasicMessage">
                            Message
                            <Input
                                type="textarea"
                                name="message"
                                className="text-primary"
                                value={this.state.message}
                                onChange={this.handleChange.bind(this, 'message')}
                            />
                        </FormGroup>
                        <Button variant="primary" type="submit" value="Send">
                            Submit
                        </Button>
                    </Form>
            </>
        )
    }
}
export default ContactForm

Body:
You don't necessarily need to use only functional based components to use material ui.

You can still use class based components and make use of withStyles to use the classes.

Code Snippet

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';

const styles = {
  root: {
    background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
    border: 0,
    borderRadius: 3,
    boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .3)',
    color: 'white',
    height: 48,
    padding: '0 30px',
    //etc...
  },
};

class ContactForm extends Component {
    state = {
        name: '',
        email: '',
        subject: '',
        message: '',
    }
    ...
    render() {
        const { classes } = this.props; //<----- grab classes here in the props
        return (
            <>
                    <h1 className="p-heading1">Get in Touch</h1>
                    <Form onSubmit={this.handleSubmit.bind(this)}>
                        <FormGroup controlId="formBasicEmail">
                            <Label className="text-muted">Email address</Label>
                            <Input
                                type="email"
                                name="email"
                                value={this.state.email}
                                className="text-primary"
                                onChange={this.handleChange.bind(this, 'email')}
                                placeholder="Enter email"
                            />
                        </FormGroup>
                        ....
            </>
        )
    }
}
export default withStyles(styles)(ContactForm) //<----- see here


问:
Swift - checking type of a generic class
I am having a Swift generic class as follows:

```<code>class List<T> {
    var value: T
    var next: List<T>?
    ...
}
</code>```

I would like to check for some object if it is an instance of this class, no matter what the type T is. For example, if I'm having:

```<code>let a = List<Int>(2, 3)
let b = List<Any>(5, List<String>("a", "b"))
let c = "something which is not a list"
</code>```

I would like the procedure (or the code snippet) to return true for a and b, and false for c.

Thanks in advance.

答:
List<T> is a generic type, and List<Int> and List<String> are concrete types, but List alone is not a type, it's just an identifier.

So, it's meaningless to say that 2 things are both a List. Furthermore, List<Int> and List<String>, for example, are as different from each other as some Foo and Bar.

If you want to reason about lists you'd need something common between these two, which is a protocol or a base class. However, because your list has a generic element type, there's almost nothing that is actually common between any two lists with different elements, aside from maybe functions like count or print.

So you could do something like this (as correctly suggested in another answer)

```<code>protocol AnyList {
   func count() -> Int
   func print() -> Void
   // but, var value: T wouldn't work
}

class List<T>: AnyList {
  ...
}
</code>```

But you can see that a common AnyList is of limited use compared to what a list does.

At the end, you need to ask yourself what you want to do next with any kind of "list", having concluded that something like List<Int> and List<String> are both lists, but knowing nothing about their concrete value types.

Body:
I am having a Swift generic class as follows:

class List<T> {
    var value: T
    var next: List<T>?
    ...
}

I would like to check for some object if it is an instance of this class, no matter what the type T is. For example, if I'm having:

let a = List<Int>(2, 3)
let b = List<Any>(5, List<String>("a", "b"))
let c = "something which is not a list"

I would like the procedure (or the code snippet) to return true for a and b, and false for c.

Thanks in advance.

Body:
List<T> is a generic type, and List<Int> and List<String> are concrete types, but List alone is not a type, it's just an identifier.

So, it's meaningless to say that 2 things are both a List. Furthermore, List<Int> and List<String>, for example, are as different from each other as some Foo and Bar.

If you want to reason about lists you'd need something common between these two, which is a protocol or a base class. However, because your list has a generic element type, there's almost nothing that is actually common between any two lists with different elements, aside from maybe functions like count or print.

So you could do something like this (as correctly suggested in another answer)

protocol AnyList {
   func count() -> Int
   func print() -> Void
   // but, var value: T wouldn't work
}

class List<T>: AnyList {
  ...
}

But you can see that a common AnyList is of limited use compared to what a list does.

At the end, you need to ask yourself what you want to do next with any kind of "list", having concluded that something like List<Int> and List<String> are both lists, but knowing nothing about their concrete value types.


问:
Flutter AnimatedContainer Can u Help Me?
When i tap menu icon i want to my main container swipe left and menu looks like android mobile-2

when i click my menu button nothing changed and i got this error Incorrect use of ParentDataWidget.

i cant figure out

Here my codes:

YanMenu widget just container with color

```<code>  @override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff3F48C1),
  // --------- Bottom Navigation Bar BAŞLANGIÇ ------------
  bottomNavigationBar: _buildBottomNavBar(),
  // --------- Bottom Navigation Bar BİTİŞ ------------
  body: Stack(
    children: <Widget>[
      YanMenu(),
      Container(
        alignment: Alignment.topCenter,
        color: Color(0xff3F48C1),
        padding: EdgeInsets.fromLTRB(10, 32, 10, 20),
        child:    !isDrawerOpen
                      ? IconButton(
                          icon: Icon(
                            Icons.menu,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 0;
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = false;
                            });
                          })
                      : IconButton(
                          icon: Icon(
                            OrdUpIcons.carpi,
                            color: Colors.white,
                            size: 20,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 230;
                              yOffSet = 150;
                              scaleFactor = 0.6;
                              isDrawerOpen = true;
                            });
                          })
                ],
              ),
            )
          ],
        ),
      ),
      Container(
        padding: EdgeInsets.only(top: 100),
        child: Flexible(
          child: AnimatedContainer(
            transform: Matrix4.translationValues(xOffSet, yOffSet, 0)
              ..scale(scaleFactor),
            duration: Duration(milliseconds: 250),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(45),
              ),
            ),
</code>```

答:
```<code>!isDrawerOpen
                      ? IconButton(
                          icon: Icon(
                            Icons.menu,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = -(genislik / 2);
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = true;
                              left = 20;
                              right = 30;
                              _borderRadius = BorderRadius.only(
                                topRight: Radius.circular(45),
                              );
                            });
                          })
                      : IconButton(
                          icon: Icon(
                            OrdUpIcons.carpi,
                            color: Colors.white,
                            size: 20,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 0;
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = false;
                              left=30;
                              right=20;
                              _borderRadius = BorderRadius.only(
                                topLeft: Radius.circular(45),
                              );
                            });
                          })
</code>```

I changed the container under YanMenu like this and my problem is solved

Body:
When i tap menu icon i want to my main container swipe left and menu looks like android mobile-2

when i click my menu button nothing changed and i got this error Incorrect use of ParentDataWidget.

i cant figure out

Here my codes:

YanMenu widget just container with color

  @override
Widget build(BuildContext context) {
return Scaffold(
  backgroundColor: Color(0xff3F48C1),
  // --------- Bottom Navigation Bar BAŞLANGIÇ ------------
  bottomNavigationBar: _buildBottomNavBar(),
  // --------- Bottom Navigation Bar BİTİŞ ------------
  body: Stack(
    children: <Widget>[
      YanMenu(),
      Container(
        alignment: Alignment.topCenter,
        color: Color(0xff3F48C1),
        padding: EdgeInsets.fromLTRB(10, 32, 10, 20),
        child:    !isDrawerOpen
                      ? IconButton(
                          icon: Icon(
                            Icons.menu,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 0;
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = false;
                            });
                          })
                      : IconButton(
                          icon: Icon(
                            OrdUpIcons.carpi,
                            color: Colors.white,
                            size: 20,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 230;
                              yOffSet = 150;
                              scaleFactor = 0.6;
                              isDrawerOpen = true;
                            });
                          })
                ],
              ),
            )
          ],
        ),
      ),
      Container(
        padding: EdgeInsets.only(top: 100),
        child: Flexible(
          child: AnimatedContainer(
            transform: Matrix4.translationValues(xOffSet, yOffSet, 0)
              ..scale(scaleFactor),
            duration: Duration(milliseconds: 250),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(45),
              ),
            ),

Body:
!isDrawerOpen
                      ? IconButton(
                          icon: Icon(
                            Icons.menu,
                            color: Colors.white,
                            size: 30,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = -(genislik / 2);
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = true;
                              left = 20;
                              right = 30;
                              _borderRadius = BorderRadius.only(
                                topRight: Radius.circular(45),
                              );
                            });
                          })
                      : IconButton(
                          icon: Icon(
                            OrdUpIcons.carpi,
                            color: Colors.white,
                            size: 20,
                          ),
                          onPressed: () {
                            setState(() {
                              xOffSet = 0;
                              yOffSet = 0;
                              scaleFactor = 1;
                              isDrawerOpen = false;
                              left=30;
                              right=20;
                              _borderRadius = BorderRadius.only(
                                topLeft: Radius.circular(45),
                              );
                            });
                          })

I changed the container under YanMenu like this and my problem is solved


问:
How to pass a valid CSRF token to AdonisJs using jQuery?
I am using datatable edit and delete button and performing CURD operation
but request can't get jquery ajax post id...

code
Controller: QuestionController

```<code>async findby({ request, response}) {
    response.send(request.input('id'));
  }
</code>```

Jquery AJAX Post Request Code

```<code>function QuestionEdit(id) {
  $.post(origin+'/dashboard/api/questions/findby', {id: id }, function(data){
      alert(data);
  });
}
</code>```

Errors:
HttpException
EBADCSRFTOKEN: Invalid CSRF token

help me how to solve and post ajax request and get Adonis Js request...

答:
You have to pass the token along with the request.

generate the token inside your view, you can put it on whatever you want, in the example below I'll store it as a data attribute:

```

<ol start="2">
<li>get it with jQuery and pass it in the post request:</li>
</ol>

```function QuestionEdit(id) {
  const token = $('.my-class').data('csrf-token');
  const params = {
    id: id,
    _csrf: token
  };

  $.post(origin + '/dashboard/api/questions/findby', params, function(data) {
    alert(data);
  });
}
```

Body:
I am using datatable edit and delete button and performing CURD operation
but request can't get jquery ajax post id...

code
Controller: QuestionController

async findby({ request, response}) {
    response.send(request.input('id'));
  }

Jquery AJAX Post Request Code

function QuestionEdit(id) {
  $.post(origin+'/dashboard/api/questions/findby', {id: id }, function(data){
      alert(data);
  });
}

Errors:
HttpException
EBADCSRFTOKEN: Invalid CSRF token

help me how to solve and post ajax request and get Adonis Js request...

Body:
You have to pass the token along with the request.

generate the token inside your view, you can put it on whatever you want, in the example below I'll store it as a data attribute:

<div class="my-class" data-csrf-token="{{ csrfToken }}"></div>

get it with jQuery and pass it in the post request:

function QuestionEdit(id) {
  const token = $('.my-class').data('csrf-token');
  const params = {
    id: id,
    _csrf: token
  };

  $.post(origin + '/dashboard/api/questions/findby', params, function(data) {
    alert(data);
  });
}


问:
Web API MediaRecorder: How do I force record at 60fps?

Summary

The API I speak about

The context

The problem: Actual result + Expected result

What I already have tried

Clues to help you to help me

Minimal and Testable Example: Prerequisites and Steps to follow + Sources

The API I speak about

https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder

The context

I have a video element that I load & play several times with different src. Between two different videos, a transition occures and each video appears with a fade in. When a video is playing, I draw it in a canvas with the transition and the fade in.

Everything I draw in the canvas is recorded using the Web API MediaRecorder. Then I download the WEBM file corresponding to this recording.

The problem

Actual result

The resulting WEBM  is jerky. When I drew in the canvas, the drawing was fluid. But the WEBM resulting from the recording of the canvas drawing is jerky.

Expected result

The WEBM resulting from the recording of the canvas drawing must be as fluid as the canvas drawing itself. If it's impossible to have exactly this result, then: the WEBM must be approximately as fluid as the canvas drawing itself in a way that we quite can't say it's jerky.

What I have already tried

First, I've tried to set a time slice of 1ms, of 16ms (corresponding to 60fps), of 100ms, then 1000, then 10000, etc. to the method start of the Media Recorder, but it didn't work.

Second, I've tried to call requestData every 16ms (in a simple JS timeoutlistener executed every 16ms), but it didn't work.

Clues to help you to help me

Perhaps I'm wrong but it would be possible that a material limit exist on my computer (I have a HP Spectre x360 that doesn't have graphic card, but just a little graphics chip), or a logical limit on my Chromium browser (I have Version 81.0.4044.138 on my Ubuntu 16.04 LTS).

If you can confirm this it would solve this question. If you can explain how to deal with this problem it would be very good (alternative solution to the Web API Media Recorder, or something else).

Minimal and Testable Example

Prerequisites and Steps to follow

Have at least 2 WEBM videos (which will be the input videos, remember: we want to output a new video that contains the canvas drawing, which itself contains these two input videos plus transitions and colors effects etc.)

Have a HTTP server and a file called "index.html" that you will open with Chromium v.81 e.g.. Copy/paste the following sources inside ; click on the "Start" button (you won't need to click on the "Stop" button) ; it will draw both videos on the canvas, with the transitions & colors effects, it will record the canvas drawing, and a "Download the final output video" will appear, allowing you to download the output video. You will see that it's jerky.

In the following sources, copy/paste the paths of your videos in the JS array called videos.

Sources

```<code><html>
<head>
    <title>Creating Final Video</title>
</head>

<body>
<button id="start">Start</button>
<button id="stop_recording">Stop recording</button>

<video id="video" width="320" height="240" controls>
    <source type="video/mp4">
</video>
<canvas id="canvas" width=3200 height=1608></canvas>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script>
var videos = [];  // Populated by Selenium
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var video = document.querySelector("video");

startRecording();
$('#start').click(function() {
    showSomeMedia(0, 0);
});

function showSomeMedia(videos_counter) {
    resetVideo();

    if(videos_counter == videos.length) {
            $('#stop_recording').click();
            return;
    } else {
            setVideoSrc(videos_counter);
            setVideoListener();
            videos_counter++;
    }

    video.addEventListener('ended', () => {
         showSomeMedia(videos_counter);
    }, false);
}

function resetVideo() {
    var clone = video.cloneNode(true);
    video.remove();
    video = clone;
}

function setVideoSrc(videos_counter) {
    video.setAttribute("src", videos[videos_counter]);
    video.load();
    video.play();
}

function setVideoListener() {
    var alpha = 0.1;
    video.addEventListener('playing', () => {
      function step() {
        if(alpha < 1) {
            ctx.globalAlpha = alpha;
        }

        ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
        requestAnimationFrame(step)

        if(alpha < 1) {
            alpha += 0.00001;
        }
      }
      requestAnimationFrame(step);
    }, false)
}

function startRecording() {
  const chunks = [];
  const stream = canvas.captureStream();
  const rec = new MediaRecorder(stream);
  rec.ondataavailable = e => chunks.push(e.data);

  $('#stop_recording').click(function() {
        rec.stop();
  });
  rec.onstop = e => exportVid(new Blob(chunks, {type: 'video/webm'}));

   window.setTimeout(function() {
            rec.requestData();
   }, 1);
  rec.start();
}

function exportVid(blob) {
  const vid = document.createElement('video');
  vid.src = URL.createObjectURL(blob);
  vid.controls = true;
  document.body.appendChild(vid);
  const a = document.createElement('a');
  a.download = 'my_final_output_video.webm';
  a.href = vid.src;
  a.textContent = 'Download the final output video';
  document.body.appendChild(a);
}
</script>

</body>

</html>
</code>```

答: The problem is solved by using my gaming laptop (RoG), wich has a good graphic card, able to record at higher frequency than my Spectre x360 development laptop. </p>

Body:
Summary

The API I speak about

The context

The problem: Actual result + Expected result

What I already have tried

Clues to help you to help me

Minimal and Testable Example: Prerequisites and Steps to follow + Sources

The API I speak about

https://developer.mozilla.org/en-US/docs/Web/API/MediaRecorder

The context

I have a video element that I load & play several times with different src. Between two different videos, a transition occures and each video appears with a fade in. When a video is playing, I draw it in a canvas with the transition and the fade in.

Everything I draw in the canvas is recorded using the Web API MediaRecorder. Then I download the WEBM file corresponding to this recording.

The problem

Actual result

The resulting WEBM  is jerky. When I drew in the canvas, the drawing was fluid. But the WEBM resulting from the recording of the canvas drawing is jerky.

Expected result

The WEBM resulting from the recording of the canvas drawing must be as fluid as the canvas drawing itself. If it's impossible to have exactly this result, then: the WEBM must be approximately as fluid as the canvas drawing itself in a way that we quite can't say it's jerky.

What I have already tried

First, I've tried to set a time slice of 1ms, of 16ms (corresponding to 60fps), of 100ms, then 1000, then 10000, etc. to the method start of the Media Recorder, but it didn't work.

Second, I've tried to call requestData every 16ms (in a simple JS timeoutlistener executed every 16ms), but it didn't work.

Clues to help you to help me

Perhaps I'm wrong but it would be possible that a material limit exist on my computer (I have a HP Spectre x360 that doesn't have graphic card, but just a little graphics chip), or a logical limit on my Chromium browser (I have Version 81.0.4044.138 on my Ubuntu 16.04 LTS).

If you can confirm this it would solve this question. If you can explain how to deal with this problem it would be very good (alternative solution to the Web API Media Recorder, or something else).

Minimal and Testable Example

Prerequisites and Steps to follow

Have at least 2 WEBM videos (which will be the input videos, remember: we want to output a new video that contains the canvas drawing, which itself contains these two input videos plus transitions and colors effects etc.)

Have a HTTP server and a file called "index.html" that you will open with Chromium v.81 e.g.. Copy/paste the following sources inside ; click on the "Start" button (you won't need to click on the "Stop" button) ; it will draw both videos on the canvas, with the transitions & colors effects, it will record the canvas drawing, and a "Download the final output video" will appear, allowing you to download the output video. You will see that it's jerky.

In the following sources, copy/paste the paths of your videos in the JS array called videos.

Sources

    <title>Creating Final Video</title>

<button id="start">Start</button>
<button id="stop_recording">Stop recording</button>

<video id="video" width="320" height="240" controls>
    <source type="video/mp4">
</video>
<canvas id="canvas" width=3200 height=1608></canvas>


问:
FATAL EXCEPTION; SQLiteException: no such column:
updateName() is working fine, but updateID() throwing error

I'm not able to find a solution

Can you please check my code to find what's wrong?

DataBaseHandler.kt

```<code>val DB_NAME = "DBDEMO2"
val DB_VERSION = 1

val TABLE_NAME = "table_DEMO2"
val COL_EMP_ID = "empId"
val COL_EMP_NAME = "empName"

data class User(var id: Int, var name: String)

val list = mutableListOf<String>(
    "John", "Robert", "William", "Charles", "Mary", "Elizabeth", "Maria", "Anne", "Margaret",
    "David","James","Richard","Johann","George","Paul","Susan", "Ruth", "Anna","Alice","Dorothy")

val CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME+"("+ COL_EMP_ID+" INTEGER, "+COL_EMP_NAME+" TEXT NOT NULL" + ")"

class DataBaseHandler(context: Context) : SQLiteOpenHelper(context, DB_NAME,null, DB_VERSION){

    var  db: SQLiteDatabase = writableDatabase
    fun insertData(){
        val cv = ContentValues()
        var id = 1001
        var index = 0
        for (id in 1001..1020){
            cv.put(COL_EMP_ID,id)
            cv.put(COL_EMP_NAME, list[index])
            db.insert(TABLE_NAME,null,cv)
            index++
        }

    }

    fun modifyName(empID : Int, newName : String){
        val cv = ContentValues()
        cv.put(COL_EMP_NAME,newName)
        db.update(TABLE_NAME,cv, COL_EMP_ID+" = "+empID,null)
    }

    fun modifyID(name : String, newEmpID : Int){
        val cv = ContentValues()
        cv.put(COL_EMP_ID,newEmpID)
        db.update(TABLE_NAME,cv, COL_EMP_NAME+" = "+name,null)
    }

    fun deleteAllData(){
        db.delete(TABLE_NAME,null,null)
    }

    fun displayData() : List<User>{

        val list = mutableListOf<User>()
        val cursor = db.query(TABLE_NAME, arrayOf(COL_EMP_ID, COL_EMP_NAME),null,null,null,null,null,null)
        if (cursor!=null && cursor.count >0 ) {
            while (cursor.moveToNext()) {
                val data = User(cursor.getInt(0), cursor.getString(1))
                list.add(data)
            }
        }
        cursor.close()
        return list
    }

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(CREATE_TABLE)
        Log.i("TAG", "OnCreateTable")
    }

    override fun onOpen(db: SQLiteDatabase?) {
        super.onOpen(db)
        Log.i("TAG", "OnOpenTable")
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }
}
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity(), View.OnClickListener {

lateinit var dbhandler: DataBaseHandler
lateinit var list: List<User>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    BtnUpdateName.setOnClickListener(this)
    BtnUpdateID.setOnClickListener(this)
    buttonDispData.setOnClickListener(this)
    buttonDeleteAll.setOnClickListener(this)
    buttonInsertData.setOnClickListener(this)

    refreshList()
}

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.BtnUpdateName -> updateName()
        R.id.BtnUpdateID -> updateID()
        R.id.buttonDispData -> refreshList()
        R.id.buttonDeleteAll -> deleteAll()
        R.id.buttonInsertData -> dbhandler.insertData()
    }
}

fun updateName() {
    val id = Integer.parseInt(EditTextEmpID.getText().toString())
    val newEmpName = EditTextNewEmpName.getText().toString()
    dbhandler.modifyName(id, newEmpName)
    refreshList()
}

fun updateID() {
    val name = EditTextEmpName.getText().toString()
    val newEmpID = Integer.parseInt(EditTextNewEmpID.getText().toString())
    dbhandler.modifyID(name, newEmpID)
    refreshList()
}

  fun deleteAll() {

      val dbHandlerDel = DataBaseHandler(this)
      dbHandlerDel.deleteAllData()
      refreshList()
  }

fun refreshList() {
    textDisplayResult.text = getResult()
}

fun getResult(): String {
    val dbHandlerResult = DataBaseHandler(this@MainActivity)
    list = dbHandlerResult.displayData()
    val str = StringBuffer("")
    if (list != null && list.size > 0) {
        for (element in list) {
            str.append(element.id.toString() + ", " + element.name + "\n")
        }
        return str.toString()
    } else
        return "No Items"
}
</code>```

}

updateName() is working fine, but updateID() throwing error

2020-05-31 18:51:33.656 6423-6423/com.db.dbdemo2 E/AndroidRuntime:
  FATAL EXCEPTION: main
      Process: com.db.dbdemo2, PID: 6423
      android.database.sqlite.SQLiteException: no such column: Mary (code 1): , while compiling: UPDATE table_DEMO2 SET empId=? WHERE
  empName = Mary
          at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
          at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
          at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
          at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
          at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
          at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
          at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1577)
          at

android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1525)
              at com.db.dbdemo2.DataBaseHandler.modifyID(DataBaseHandler.kt:52)
              at com.db.dbdemo2.MainActivity.updateID(MainActivity.kt:75)
              at com.db.dbdemo2.MainActivity.onClick(MainActivity.kt:58)
              at android.view.View.performClick(View.java:5637)
              at android.view.View$PerformClick.run(View.java:22429)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at android.os.Looper.loop(Looper.java:154)
              at android.app.ActivityThread.main(ActivityThread.java:6119)
              at java.lang.reflect.Method.invoke(Native Method)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

答:
Please try by changing your modifyID() method as below

```<code>fun modifyID(name : String, newEmpID : Int){
        val cv = ContentValues()
        cv.put(COL_EMP_ID,newEmpID)
        val args = arrayOf<String>(name)
        db.update(TABLE_NAME, values, COL_EMP_NAME + "=?", args)
    }
</code>```

Body:
updateName() is working fine, but updateID() throwing error

I'm not able to find a solution

Can you please check my code to find what's wrong?

DataBaseHandler.kt

val DB_NAME = "DBDEMO2"
val DB_VERSION = 1

val TABLE_NAME = "table_DEMO2"
val COL_EMP_ID = "empId"
val COL_EMP_NAME = "empName"

data class User(var id: Int, var name: String)

val list = mutableListOf<String>(
    "John", "Robert", "William", "Charles", "Mary", "Elizabeth", "Maria", "Anne", "Margaret",
    "David","James","Richard","Johann","George","Paul","Susan", "Ruth", "Anna","Alice","Dorothy")

val CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME+"("+ COL_EMP_ID+" INTEGER, "+COL_EMP_NAME+" TEXT NOT NULL" + ")"

class DataBaseHandler(context: Context) : SQLiteOpenHelper(context, DB_NAME,null, DB_VERSION){

    var  db: SQLiteDatabase = writableDatabase
    fun insertData(){
        val cv = ContentValues()
        var id = 1001
        var index = 0
        for (id in 1001..1020){
            cv.put(COL_EMP_ID,id)
            cv.put(COL_EMP_NAME, list[index])
            db.insert(TABLE_NAME,null,cv)
            index++
        }

    }

    fun modifyName(empID : Int, newName : String){
        val cv = ContentValues()
        cv.put(COL_EMP_NAME,newName)
        db.update(TABLE_NAME,cv, COL_EMP_ID+" = "+empID,null)
    }

    fun modifyID(name : String, newEmpID : Int){
        val cv = ContentValues()
        cv.put(COL_EMP_ID,newEmpID)
        db.update(TABLE_NAME,cv, COL_EMP_NAME+" = "+name,null)
    }

    fun deleteAllData(){
        db.delete(TABLE_NAME,null,null)
    }

    fun displayData() : List<User>{

        val list = mutableListOf<User>()
        val cursor = db.query(TABLE_NAME, arrayOf(COL_EMP_ID, COL_EMP_NAME),null,null,null,null,null,null)
        if (cursor!=null && cursor.count >0 ) {
            while (cursor.moveToNext()) {
                val data = User(cursor.getInt(0), cursor.getString(1))
                list.add(data)
            }
        }
        cursor.close()
        return list
    }

    override fun onCreate(db: SQLiteDatabase?) {
        db?.execSQL(CREATE_TABLE)
        Log.i("TAG", "OnCreateTable")
    }

    override fun onOpen(db: SQLiteDatabase?) {
        super.onOpen(db)
        Log.i("TAG", "OnOpenTable")
    }

    override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {

    }
}

MainActivity.kt

class MainActivity : AppCompatActivity(), View.OnClickListener {

lateinit var dbhandler: DataBaseHandler
lateinit var list: List<User>

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    BtnUpdateName.setOnClickListener(this)
    BtnUpdateID.setOnClickListener(this)
    buttonDispData.setOnClickListener(this)
    buttonDeleteAll.setOnClickListener(this)
    buttonInsertData.setOnClickListener(this)

    refreshList()
}

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.BtnUpdateName -> updateName()
        R.id.BtnUpdateID -> updateID()
        R.id.buttonDispData -> refreshList()
        R.id.buttonDeleteAll -> deleteAll()
        R.id.buttonInsertData -> dbhandler.insertData()
    }
}

fun updateName() {
    val id = Integer.parseInt(EditTextEmpID.getText().toString())
    val newEmpName = EditTextNewEmpName.getText().toString()
    dbhandler.modifyName(id, newEmpName)
    refreshList()
}

fun updateID() {
    val name = EditTextEmpName.getText().toString()
    val newEmpID = Integer.parseInt(EditTextNewEmpID.getText().toString())
    dbhandler.modifyID(name, newEmpID)
    refreshList()
}

  fun deleteAll() {

      val dbHandlerDel = DataBaseHandler(this)
      dbHandlerDel.deleteAllData()
      refreshList()
  }

fun refreshList() {
    textDisplayResult.text = getResult()
}

fun getResult(): String {
    val dbHandlerResult = DataBaseHandler(this@MainActivity)
    list = dbHandlerResult.displayData()
    val str = StringBuffer("")
    if (list != null && list.size > 0) {
        for (element in list) {
            str.append(element.id.toString() + ", " + element.name + "\n")
        }
        return str.toString()
    } else
        return "No Items"
}

}

updateName() is working fine, but updateID() throwing error

2020-05-31 18:51:33.656 6423-6423/com.db.dbdemo2 E/AndroidRuntime:
  FATAL EXCEPTION: main
      Process: com.db.dbdemo2, PID: 6423
      android.database.sqlite.SQLiteException: no such column: Mary (code 1): , while compiling: UPDATE table_DEMO2 SET empId=? WHERE
  empName = Mary
          at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native
  Method)
          at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
          at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
          at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
          at android.database.sqlite.SQLiteProgram.(SQLiteProgram.java:58)
          at android.database.sqlite.SQLiteStatement.(SQLiteStatement.java:31)
          at android.database.sqlite.SQLiteDatabase.updateWithOnConflict(SQLiteDatabase.java:1577)
          at

android.database.sqlite.SQLiteDatabase.update(SQLiteDatabase.java:1525)
              at com.db.dbdemo2.DataBaseHandler.modifyID(DataBaseHandler.kt:52)
              at com.db.dbdemo2.MainActivity.updateID(MainActivity.kt:75)
              at com.db.dbdemo2.MainActivity.onClick(MainActivity.kt:58)
              at android.view.View.performClick(View.java:5637)
              at android.view.View$PerformClick.run(View.java:22429)
              at android.os.Handler.handleCallback(Handler.java:751)
              at android.os.Handler.dispatchMessage(Handler.java:95)
              at android.os.Looper.loop(Looper.java:154)
              at android.app.ActivityThread.main(ActivityThread.java:6119)
              at java.lang.reflect.Method.invoke(Native Method)
              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
Please try by changing your modifyID() method as below

fun modifyID(name : String, newEmpID : Int){
        val cv = ContentValues()
        cv.put(COL_EMP_ID,newEmpID)
        val args = arrayOf<String>(name)
        db.update(TABLE_NAME, values, COL_EMP_NAME + "=?", args)
    }


问:
Should I store data as a variable in javascript or in a text file?
I am creating a webpage, and I want it to display a random text. Suppose I have around 1000 sentences (for example), and I want to select a random sentence from the list.

Which would be a better way: to store all these sentences in a javascript array or to store them in a text file, and then use javascript to read a line from the file?

Essentially, how does this impact the performance? And the 1000 lines are just for example, I want to know how the general approach should be for increasing variable size.

The desired result is that the webpage should load fast, and should not be computationally heavy on the client side.

Note that the page is static and the sentences are immutable and won't change over the course of time.

答:
Question:

What approach is the best among these 2 options?

Option 1: 1000 sentences inside javascript array variable

Vs.

Option 2: 1000 sentences served in a separate text file (json format assumed)'

Answer:

The 3 major aspects that impact the performance of a web app are:

Number of network calls between browser and server

Amount of data downloaded from server

Amount of memory consumed by Javascript running on browser

Performance can be enhanced by minimizing and balancing the above aspects.

Loading 1000 sentences into one array variable will reduce the number of network calls.
Therefore, it is a very good option to improve performance,
as long as the following conditions are true:

Total size of the 1000 sentences is small (only up to several KB)

There is no security risk in showing full data to user (if all data is kept in variable, then the user can see all sentences by opening developer console).

If the sentences are big in size, or if the requirement is to hide the remaining 999 sentences from user, then the idea of keeping those in a separate json file on server and serving only one of the sentences based on random value is a better option.


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

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

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

HTML Code:

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

JavaScript Code:

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

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

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

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

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

PHP Code:

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

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

Thanks for your help in advance..

答:
Using the fetch api for simplicity and brevity - an example piece of code that will make a POST request to the server ( in this instance the same page but change location.href for the correct endpoint / url ) and use the callback to perform the DOM manipulation.

The PHP at the top here is to emulate YOUR database insert - you would be advised however to use a prepared statement rather than embedding user content directly in the SQL as this leaves you vulnerable to SQL Injection.

```<code><?php

    # include scripts
    require 'db.php';

    /*
        The PHP endpoint that handles the database insert.
        For the purposes of this example it is on the same
        page as the HTML form but can as easily be a different
        script.
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        /*
            Only process this piece if there is a POST request with
            a particular parameter present in the request. Note that
            it makes more sense to test that the parameter that will
            be used in any database operations is present as opposed
            to the `submit` button which is commonly used for such a
            test but serves no purpose beyond this point so is redundant.
        */
        if( isset( $_POST['name'] ) ){
            /*
                As this is an AJAX request we are only interested in
                content generated in this piece of code. Anything that
                was generated before or after should be discarded.
            */
            ob_flush();

            /*
                Create a "Prepared Statement" to allow the user
                supplied data to be handled in a safe manner. Note
                that you should not use `mysqli_real_escape_string`
            */
            $sql='insert into `test` ( `xxname` ) values ( ? )';
            $stmt=$db->prepare( $sql );

            /*
                The return value from the `prepare` method is a Boolean
                so you are able to use that value to "Fork" the program
                logic.
            */
            if( $stmt ){
                /*
                    The prepared statement has been created by the server
                    so now you can assign values to the placeholders. This
                    is done using `bind_param`

                    Different types of variable can be bound using a different
                    `type` argument
                        >   i   - integers
                        >   s   - strings
                        >   d   - double
                        >   b   - boolean
                */
                $stmt->bind_param( 's', $_POST['name'] );
                /*
                    With the variable bound to the placeholder
                    you can now commit the data to the db
                */
                $result=$stmt->execute();
                $rows=$stmt->affected_rows;
                /*
                    The return value from `execute` is a boolean.
                    It will be false if, for some reason, the db
                    failed to process the request.

                    To determine if the request succeeded you can use
                    a combination of $result & $rows if you wish and
                    inform the user with an appropriate response.
                */
                $response = $result && $rows==1 ? 'Whoohoo! Record added - ya dancer!' : 'ERROR: Could not insert record';
                exit( $response );
            }else{
                /*
                    If you get here it often suggests a syntax error in
                    the sql. You could use $stmt->error to aid analysis
                    but not in production code.
                */
                exit('bogus');
            }
        }

        /* To prevent the whole page appearing in the AJAX response */
        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Submit Form data and hide form</title>
    </head>
    <body>

        <!-- slightly streamlined version of original HTML markup. -->
        <div style='display:none;'>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
                numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
                commodi voluptatum!
            </p>
        </div>
        <div>
            <form method='post'>
                <input type='text' name='name' />
                <input type='submit' />
            </form>
        </div>

        <script>
            /*
                Bind an event handler to the submit ( or regular ) button to fire
                an AJAX request to the PHP server.

                Binding a FORM with the `submit` event requires a different approach
                to that shown in the question. The callback function or event handler
                needs to return a boolean and the form will only be submitted if the
                function evaluates to true. Hence better binding to the button as we
                do not want to send the form in the traditional sense - we need to
                fashion our own request without reloading the page.
            */
            document.querySelector('form > input[type="submit"]').addEventListener('click', function(e){
                // Prevent the form being submitted.
                e.preventDefault();

                /*
                    using parent and sibling selectors we can identify
                    the required DOM elements that will be used in the
                    show/hide operations.
                */
                let container=this.parentNode.parentNode;
                let div=container.previousElementSibling;

                /*
                    The `Fetch` api was developed to provide greater
                    flexibility than the more commonly used `XMLHttpRequest`
                    which has become the workhorse of many web applications.

                    To explain it fully you should study the documentation on
                    MDN - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
                    Google - https://developers.google.com/web/updates/2015/03/introduction-to-fetch

                    Another little gem is the `FormData` object used here.
                    MDN - https://developer.mozilla.org/en-US/docs/Web/API/FormData

                    The fetch call sends the request in this case to the same page ( location.href )
                    and has various configuration options set - method and body being of interest.

                    The `body` of the request is the `FormData` object which can be populated
                    automagically by supplying a reference to the FORM as the argument or manually
                    by calling the `append` method.

                    rtfm
                */
                fetch( location.href, { method:'post',body:( new FormData( document.querySelector('form') ) ) } )
                    .then( response=>{ return response.text() } )
                    .then( text=>{
                        /* The server response can be read / used here */
                        console.info( text );

                        /* perform the show and hide operations... */
                        container.style.display='none';
                        div.style.display='block';
                    })
                    .catch( err=>{ alert(err) })

            });

        </script>
    </body>
</html>
</code>```

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

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

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

HTML Code:

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

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

JavaScript Code:

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

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

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

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

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

PHP Code:

include("db.php");

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

Thanks for your help in advance..

Body:
Using the fetch api for simplicity and brevity - an example piece of code that will make a POST request to the server ( in this instance the same page but change location.href for the correct endpoint / url ) and use the callback to perform the DOM manipulation.

The PHP at the top here is to emulate YOUR database insert - you would be advised however to use a prepared statement rather than embedding user content directly in the SQL as this leaves you vulnerable to SQL Injection.

<?php

    # include scripts
    require 'db.php';

    /*
        The PHP endpoint that handles the database insert.
        For the purposes of this example it is on the same
        page as the HTML form but can as easily be a different
        script.
    */
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        /*
            Only process this piece if there is a POST request with
            a particular parameter present in the request. Note that
            it makes more sense to test that the parameter that will
            be used in any database operations is present as opposed
            to the `submit` button which is commonly used for such a
            test but serves no purpose beyond this point so is redundant.
        */
        if( isset( $_POST['name'] ) ){
            /*
                As this is an AJAX request we are only interested in
                content generated in this piece of code. Anything that
                was generated before or after should be discarded.
            */
            ob_flush();

            /*
                Create a "Prepared Statement" to allow the user
                supplied data to be handled in a safe manner. Note
                that you should not use `mysqli_real_escape_string`
            */
            $sql='insert into `test` ( `xxname` ) values ( ? )';
            $stmt=$db->prepare( $sql );

            /*
                The return value from the `prepare` method is a Boolean
                so you are able to use that value to "Fork" the program
                logic.
            */
            if( $stmt ){
                /*
                    The prepared statement has been created by the server
                    so now you can assign values to the placeholders. This
                    is done using `bind_param`

                    Different types of variable can be bound using a different
                    `type` argument
                        >   i   - integers
                        >   s   - strings
                        >   d   - double
                        >   b   - boolean
                */
                $stmt->bind_param( 's', $_POST['name'] );
                /*
                    With the variable bound to the placeholder
                    you can now commit the data to the db
                */
                $result=$stmt->execute();
                $rows=$stmt->affected_rows;
                /*
                    The return value from `execute` is a boolean.
                    It will be false if, for some reason, the db
                    failed to process the request.

                    To determine if the request succeeded you can use
                    a combination of $result & $rows if you wish and
                    inform the user with an appropriate response.
                */
                $response = $result && $rows==1 ? 'Whoohoo! Record added - ya dancer!' : 'ERROR: Could not insert record';
                exit( $response );
            }else{
                /*
                    If you get here it often suggests a syntax error in
                    the sql. You could use $stmt->error to aid analysis
                    but not in production code.
                */
                exit('bogus');
            }
        }

        /* To prevent the whole page appearing in the AJAX response */
        exit();
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Submit Form data and hide form</title>
    </head>
    <body>

        <!-- slightly streamlined version of original HTML markup. -->
        <div style='display:none;'>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate culpa reprehenderit animi,
                numquam distinctio repellendus debitis fugit unde consequatur eum magni illo minima amet quidem omnis veniam
                commodi voluptatum!
            </p>
        </div>
        <div>
            <form method='post'>
                <input type='text' name='name' />
                <input type='submit' />
            </form>
        </div>

        <script>
            /*
                Bind an event handler to the submit ( or regular ) button to fire
                an AJAX request to the PHP server.

                Binding a FORM with the `submit` event requires a different approach
                to that shown in the question. The callback function or event handler
                needs to return a boolean and the form will only be submitted if the
                function evaluates to true. Hence better binding to the button as we
                do not want to send the form in the traditional sense - we need to
                fashion our own request without reloading the page.
            */
            document.querySelector('form > input[type="submit"]').addEventListener('click', function(e){
                // Prevent the form being submitted.
                e.preventDefault();

                /*
                    using parent and sibling selectors we can identify
                    the required DOM elements that will be used in the
                    show/hide operations.
                */
                let container=this.parentNode.parentNode;
                let div=container.previousElementSibling;

                /*
                    The `Fetch` api was developed to provide greater
                    flexibility than the more commonly used `XMLHttpRequest`
                    which has become the workhorse of many web applications.

                    To explain it fully you should study the documentation on
                    MDN - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
                    Google - https://developers.google.com/web/updates/2015/03/introduction-to-fetch

                    Another little gem is the `FormData` object used here.
                    MDN - https://developer.mozilla.org/en-US/docs/Web/API/FormData

                    The fetch call sends the request in this case to the same page ( location.href )
                    and has various configuration options set - method and body being of interest.

                    The `body` of the request is the `FormData` object which can be populated
                    automagically by supplying a reference to the FORM as the argument or manually
                    by calling the `append` method.

                    rtfm
                */
                fetch( location.href, { method:'post',body:( new FormData( document.querySelector('form') ) ) } )
                    .then( response=>{ return response.text() } )
                    .then( text=>{
                        /* The server response can be read / used here */
                        console.info( text );

                        /* perform the show and hide operations... */
                        container.style.display='none';
                        div.style.display='block';
                    })
                    .catch( err=>{ alert(err) })

            });

        </script>
    </body>
</html>


问:
AWS access key is showing up in browser url when accessing the s3 content from heroku
I have deployed my django app to heroku and using Amazon s3 bucket to store the static files and I see there is no issues in getting data from s3 buckets to heroku. But, when I'm testing to see the content storage location i'm getting the url path in addition with the AccesskeyID

https://myapp.s3.amazonaws.com/img/front_cover.JPG?AWSAccessKeyId=AKIAXPKPZLYKLRB7DR4N&Signature=JzTU0DpmbGSBRpYHwV8Dvt0p1QQ%3D&Expires=1590936351

So I'm concerned showing up access id in the browser URl, do we have an option to disable this in heroku or django settings or in AWS

答:
This is a presigned URL and the AWSAccessKeyId is actually part of its structure.

Both this and Signature need to match for this to be displayed to the end user.

If security is a concern just generate IAM user which is minimum permissions. Remember the secret key should be kept secret though, this is the equivalent of a password. An access key however, is actually retrievable through anyone in your AWS account, closer to a username.


问:
How to Save reactjs state object in LocalStorage?
I want to save the state of movies in localstorage. I am stuck and have no idea on how to implement this. I tried to add localStorage.setItem('movies', JSON.stringify(this.state.movies)) in the addMovie method in the App component but this did not work. I have listed my App component and my CreateMovieForm component below.

This website stores movies in a list.
The way this website works is that it has a movies state in the app component. All the components do is manipulate this movies state. It does not matter if they delete or add a movie. The state always gets updated and the list of movies gets re-rendered.

```<code>class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      movies: []
    }
  }

  addMovie(movie) {
    this.setState({
      movies: this.state.movies.concat(movie)
    })
    console.log(this.state.movies);
  }

  createDeltedList(newMovies){
    this.setState({
      movies: newMovies
    })
  }

  sortMovies(){
    let movies = this.state.movies;
    movies.sort(function(a, b) {
      return b.grade - a.grade;
    })
    this.setState({movies: movies})
  }

  sortMoviesAlpha(){
    let movies = this.state.movies;
    movies.sort(function(a, b) {
      if (a.title > b.title){
        return 1
      }
      if (a.title < b.title){
        return -1
      }
      return 0
    })
    this.setState({movies: movies})
  }

  render(){
    return (
      <div className='container'>
        <AppTitle attr='display-4' title='Min film lista ' />
        <LeadText attr='lead' text='Lägg till film:' />
        <AddLine />
        <CreateMovieForm addMovie={this.addMovie.bind(this)} attr='form-group' from='form-control' btnSave='Spara film'/>
        <SortGradeButton sortMovies={this.sortMovies.bind(this)} text='Sort by Grade'/>
        <SortAlphaButton sortMoviesAlpha={this.sortMoviesAlpha.bind(this)} text='Sort Alphabetically' />
        <MovieList genNewList={this.createDeltedList.bind(this)} movies={this.state.movies} />
      </div>
    );
  }

}

export default App;
</code>```

```<code>class CreateMovieForm extends React.Component{
  constructor(props){
    super(props);
    this.state = {title: '', grade: '1'};

    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleGradeChange = this.handleGradeChange.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }
  handleTitleChange(event) {
    this.setState({title: event.target.value});
  }

  handleGradeChange(event){
    this.setState({grade: event.target.value});
  }

  handleSave(event){
    event.preventDefault();
    let movie = {
      title: this.state.title,
      grade: this.state.grade
    }
    this.props.addMovie(movie)
  }
  render(){
    return (
      <form onSubmit={this.handleSave}>
        <div className={this.props.attr}>
          <label htmlFor='movieTitle'>Titel:</label>
          <input type='text' className={this.props.from} placeholder='Titel här...' title={this.state.title} onChange={this.handleTitleChange}/>
        </div>
        <div className={this.props.attr}>
          <label htmlFor='grade'>Betyg:</label>
          <select id='grade' className={this.props.from} grade={this.state.grade} onChange={this.handleGradeChange}>
              <option>Välj betyg här...</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
          </select>
        </div>
        <button className='btn btn-info'>{this.props.btnSave} </button>
      </form>
    );
  }
}
</code>```

答:
You can acccess the window.localStorage method

By setting data to the localStorage localStorage.setItem('key', value );

And also getting  localStorage.getItem('key', value);

You can also save an array by passing data

// let’s say am saving an array of books with objects values
localStorage.setItem('books',JSON.stringify(books));

let books = localStorage.getItem('books');
books = JSON.parse(books);
I hope this helps

Body:
I want to save the state of movies in localstorage. I am stuck and have no idea on how to implement this. I tried to add localStorage.setItem('movies', JSON.stringify(this.state.movies)) in the addMovie method in the App component but this did not work. I have listed my App component and my CreateMovieForm component below.

This website stores movies in a list.
The way this website works is that it has a movies state in the app component. All the components do is manipulate this movies state. It does not matter if they delete or add a movie. The state always gets updated and the list of movies gets re-rendered.

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      movies: []
    }
  }

  addMovie(movie) {
    this.setState({
      movies: this.state.movies.concat(movie)
    })
    console.log(this.state.movies);
  }

  createDeltedList(newMovies){
    this.setState({
      movies: newMovies
    })
  }

  sortMovies(){
    let movies = this.state.movies;
    movies.sort(function(a, b) {
      return b.grade - a.grade;
    })
    this.setState({movies: movies})
  }

  sortMoviesAlpha(){
    let movies = this.state.movies;
    movies.sort(function(a, b) {
      if (a.title > b.title){
        return 1
      }
      if (a.title < b.title){
        return -1
      }
      return 0
    })
    this.setState({movies: movies})
  }

  render(){
    return (

        <AppTitle attr='display-4' title='Min film lista ' />
        <LeadText attr='lead' text='Lägg till film:' />
        <AddLine />
        <CreateMovieForm addMovie={this.addMovie.bind(this)} attr='form-group' from='form-control' btnSave='Spara film'/>
        <SortGradeButton sortMovies={this.sortMovies.bind(this)} text='Sort by Grade'/>
        <SortAlphaButton sortMoviesAlpha={this.sortMoviesAlpha.bind(this)} text='Sort Alphabetically' />
        <MovieList genNewList={this.createDeltedList.bind(this)} movies={this.state.movies} />

    );
  }

}

export default App;

class CreateMovieForm extends React.Component{
  constructor(props){
    super(props);
    this.state = {title: '', grade: '1'};

    this.handleTitleChange = this.handleTitleChange.bind(this);
    this.handleGradeChange = this.handleGradeChange.bind(this);
    this.handleSave = this.handleSave.bind(this);
  }
  handleTitleChange(event) {
    this.setState({title: event.target.value});
  }

  handleGradeChange(event){
    this.setState({grade: event.target.value});
  }

  handleSave(event){
    event.preventDefault();
    let movie = {
      title: this.state.title,
      grade: this.state.grade
    }
    this.props.addMovie(movie)
  }
  render(){
    return (
      <form onSubmit={this.handleSave}>

          Titel:
          <input type='text' className={this.props.from} placeholder='Titel här...' title={this.state.title} onChange={this.handleTitleChange}/>

          Betyg:
          <select id='grade' className={this.props.from} grade={this.state.grade} onChange={this.handleGradeChange}>
              <option>Välj betyg här...</option>
              <option>1</option>
              <option>2</option>
              <option>3</option>
              <option>4</option>
              <option>5</option>
          </select>

        <button className='btn btn-info'>{this.props.btnSave} </button>
      </form>
    );
  }
}


问:
how to bind two or more events with on_text_validate
I want that on pressing enter in a TextInput widget it should do two things-

change the screen (i am using screen manager)

and search for the keyword

I do know that with on_text_validate we can perform either of the tasks by-

1.root.manager.current='namesomething'

2.root.function_which_has_search_algorithm()

is there anyway with which i can do both the things(changing_the_screen,calling_the_search_function) using on_text_validate or do i have to use some other technique?

here a sample code:

```<code>import kivy
kivy.require("1.10.0")

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.lang import Builder

Builder.load_file('screenswitch.kv')

class MainScreen(Screen):
    def SelectWord(self):
        ''' some search
                   code'''

class OtherScreen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(OtherScreen(name='other'))

class ScreenSwitchApp(App):
    def build(self):
        return sm

obj = ScreenSwitchApp()
obj.run()
</code>```

heres my kivy code:

```<code><MainScreen>:
    BoxLayout:
        TextInput:
            text: "Search your word here"
            color: 1,1,1,1
            id: search_input
            width: 200
            size_hint: None, .20
            pos_hint: {"center_x": .5, "center_y": 0.5}
            multiline: False
            on_text_validate: root.SelectWord() # i want this to change screen also

<OtherScreen>:
    BoxLayout:
        Button:
            text: 'back to main screen'
            on_press: root.manager.current='main'
</code>```

答:
```<code>        TextInput:
                id:qty_inp
                size_hint_x:.1
                multiline:False
                on_text_validate:root.update_price()
                on_text_validate:root.update_purchase
</code>```

Like the above code you can add one more on_text_validate: root.method()

ContentLicense: CC BY-SA 3.0

Body:
I want that on pressing enter in a TextInput widget it should do two things-

change the screen (i am using screen manager)

and search for the keyword

I do know that with on_text_validate we can perform either of the tasks by-

1.root.manager.current='namesomething'

2.root.function_which_has_search_algorithm()

is there anyway with which i can do both the things(changing_the_screen,calling_the_search_function) using on_text_validate or do i have to use some other technique?

here a sample code:

import kivy
kivy.require("1.10.0")

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.lang import Builder

Builder.load_file('screenswitch.kv')

class MainScreen(Screen):
    def SelectWord(self):
        ''' some search
                   code'''

class OtherScreen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(MainScreen(name='main'))
sm.add_widget(OtherScreen(name='other'))

class ScreenSwitchApp(App):
    def build(self):
        return sm

obj = ScreenSwitchApp()
obj.run()

heres my kivy code:

<MainScreen>:
    BoxLayout:
        TextInput:
            text: "Search your word here"
            color: 1,1,1,1
            id: search_input
            width: 200
            size_hint: None, .20
            pos_hint: {"center_x": .5, "center_y": 0.5}
            multiline: False
            on_text_validate: root.SelectWord() # i want this to change screen also

<OtherScreen>:
    BoxLayout:
        Button:
            text: 'back to main screen'
            on_press: root.manager.current='main'

Body:
        TextInput:
                id:qty_inp
                size_hint_x:.1
                multiline:False
                on_text_validate:root.update_price()
                on_text_validate:root.update_purchase

Like the above code you can add one more on_text_validate: root.method()


问:
How to get date timestamp of a symlink or directory using ansible?
Is there a way we can extract modification date/time of a symlink or directory using Ansible.
For example on my remote host in directory /opt/tomcat/apps I have this symlink myapp -> /opt/tomcat/releases/Release1.20.0-01/myapp/webapp/.

I know ls -lrt gives you the date and time but is there a way to get it using Ansible playbook?

lrwxrwxrwx  1 tomcat tomcat   48 May 15 13:26 myapp -> /opt/tomcat/releases/Release1.20.0-01/myapp/webapp/

I want to extract the date and time from this and store it in a variable in Ansible. Please let me know if someone can advice.

答:
You can use stat module to get the details of file or directory and then fetch relevant information like atime, ctime, time etc.

Here is a sample:

```<code>- name: get file statistics
  stat:
    path: /path/to/link
  register: status

- debug:
    msg: "{{ status.stat.mtime }}"
</code>```

Since atime, ctime, mtime properties return float you may like to convert them to date or string. To do that, you may create a small filter like this.

Body:
You can use stat module to get the details of file or directory and then fetch relevant information like atime, ctime, time etc.

Here is a sample:

- name: get file statistics
  stat:
    path: /path/to/link
  register: status

- debug:
    msg: "{{ status.stat.mtime }}"

Since atime, ctime, mtime properties return float you may like to convert them to date or string. To do that, you may create a small filter like this.


问:
Unable to create/access database
I have been using MongoDB without issues in Python but I am in need to build a client in go now.
I have looked at the documentation and the examples work fine.

But when I try to use my own code, the code execute without errors, but when I inspect the database (via CLI) I see no database, no collection and no data.

I am sure I am doing something wrong, but I am unable to find it in this little testing code.

```<code>func main() {

    if client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")); err == nil {
        ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
        defer client.Disconnect(ctx)
        if err = client.Connect(ctx); err == nil {
            os.Exit(0)
        }

        KeysCol := client.Database("yfroot").Collection("KeysCol")

        mac, e1 := crypto.GenerateRandomBytes(16)
        key, e2 := crypto.GenerateRandomBytes(16)
        if e1 != nil || e2 != nil {
            fmt.Println("failed crypto generate")
            os.Exit(0)
        }
        testKey := dataformats.DeviceKey{
            Mac: string(mac),
            Key: key,
        }

        // ctx, _ = context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
        _, err := KeysCol.InsertOne(ctx, testKey)
        if err != nil {
            fmt.Println(err)
            os.Exit(0)
        }

    } else {
        fmt.Println(err)
    }
}
</code>```

答:
Look at this part:

```<code>if err = client.Connect(ctx); err == nil {
  os.Exit(0)
}
</code>```

If you are able to connect, that us (err is nil), you are exiting.

You probably meant to do:

```<code>if err = client.Connect(ctx); err != nil {
  fmt.Println(err)
  os.Exit(0)
}
</code>```

Title: Unable to create/access database

Body:
I have been using MongoDB without issues in Python but I am in need to build a client in go now.
I have looked at the documentation and the examples work fine.

But when I try to use my own code, the code execute without errors, but when I inspect the database (via CLI) I see no database, no collection and no data.

I am sure I am doing something wrong, but I am unable to find it in this little testing code.

func main() {

    if client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017")); err == nil {
        ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
        defer client.Disconnect(ctx)
        if err = client.Connect(ctx); err == nil {
            os.Exit(0)
        }

        KeysCol := client.Database("yfroot").Collection("KeysCol")

        mac, e1 := crypto.GenerateRandomBytes(16)
        key, e2 := crypto.GenerateRandomBytes(16)
        if e1 != nil || e2 != nil {
            fmt.Println("failed crypto generate")
            os.Exit(0)
        }
        testKey := dataformats.DeviceKey{
            Mac: string(mac),
            Key: key,
        }

        // ctx, _ = context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
        _, err := KeysCol.InsertOne(ctx, testKey)
        if err != nil {
            fmt.Println(err)
            os.Exit(0)
        }

    } else {
        fmt.Println(err)
    }
}

Body:
Look at this part:

if err = client.Connect(ctx); err == nil {
  os.Exit(0)
}

If you are able to connect, that us (err is nil), you are exiting.

You probably meant to do:

if err = client.Connect(ctx); err != nil {
  fmt.Println(err)
  os.Exit(0)
}


问:
NLTK - AttributeError: module 'nltk' has no attribute 'data'
I used nltk in my code for a few days, but now, when I try to import nltk, I get the error:

```<code>File "C:\Users\Nada\Anaconda\lib\site-packages\nltk\corpus\reader\plaintext.py", line 42, in PlaintextCorpusReader
sent_tokenizer=nltk.data.LazyLoader(

AttributeError: module 'nltk' has no attribute 'data'
</code>```

I installed weka package yesterday but it didn't work, I don't know in this has anything to do with that...

I tried to update it, but the error keeps showing up.

答: i get the same issue, restarting the kernel fixed my issue</p>

Body:
I used nltk in my code for a few days, but now, when I try to import nltk, I get the error:

File "C:\Users\Nada\Anaconda\lib\site-packages\nltk\corpus\reader\plaintext.py", line 42, in PlaintextCorpusReader
sent_tokenizer=nltk.data.LazyLoader(

AttributeError: module 'nltk' has no attribute 'data'

I installed weka package yesterday but it didn't work, I don't know in this has anything to do with that...

I tried to update it, but the error keeps showing up.


问:
Is there a way to add different Id's to multiple elements with Javascript?
Let's say I have

```<code><iframe> id="iframeid"
<div> </div>
<div> </div>
<div> </div>
<div> </div>
</iframe>
</code>```

Is there a way to add unique Id's to the divs using javascript?
For example

```<code><iframe> id="iframeid"
<div>id="divid1"</div>
<div>id="divid2" </div>
<div>id="divid3" </div>
<div>id="divid4" </div>
</iframe>
</code>```

答:
You can return all the div elements with document.getElementsByTagName. This return a NodeList (of div in this case) that you can access with bracket notation (or item method, it's the same) that return the Element Node. You can set its attribute id with .id=value or setAttribute(id,value). In my example I set the div elements with id=id0    id=id1  and so on.

```<code>      let myDivs = document.getElementsByTagName("div");
      for(let i=0 ; i<myDivs.length ;i++)
         myDivs[i].id = `id${i}`;
</code>```

Furthermore note that document.getElementsByTagName("div") returns all the div in the page,  if you want only the div of an element, for instance an iframe element with id=myiframe you can do:

```<code>document.getElementById("myiframe").getElementsByTagName("div");
</code>```

Also note that this method detects all the div in the subtree, it is not limited to direct children

Body:
Let's say I have

 id="iframeid"

Is there a way to add unique Id's to the divs using javascript?
For example

 id="iframeid"

id="divid1"

id="divid2"

id="divid3"

id="divid4"

Body:
You can return all the div elements with document.getElementsByTagName. This return a NodeList (of div in this case) that you can access with bracket notation (or item method, it's the same) that return the Element Node. You can set its attribute id with .id=value or setAttribute(id,value). In my example I set the div elements with id=id0    id=id1  and so on.

      let myDivs = document.getElementsByTagName("div");
      for(let i=0 ; i<myDivs.length ;i++)
         myDivs[i].id = `id${i}`;

Furthermore note that document.getElementsByTagName("div") returns all the div in the page,  if you want only the div of an element, for instance an iframe element with id=myiframe you can do:

document.getElementById("myiframe").getElementsByTagName("div");

Also note that this method detects all the div in the subtree, it is not limited to direct children


问:
Xamarin : Application not installed issue
When I install my application in debugging mode on my Android mobile device, it seems to be installed.

However, after signing the application and publishing it, it's not installed on my phone. (Release mode)

It says: Application not installed.
I tried a few things but cannot resolve this problem. I also tested with another Keystore but it still cannot be installed.

I verified Xamarin Studio options but everything is OK, does anyone have an idea?

答:
I know I am late in party. But I believe it could help someone to resolve his issue.

Sometimes the issue is unsupported Architecture.

You can resolve it by

Android Project>Properties>Android Options> Advance>Supported Architecture.

Here you can check the supported architecture according to your device and the issue would be resolved. (I believe app should support maximum of architectures so check them all).

Hope it would help.


问:
Is it possible to deploy a NodeJs app in Vercel?
I'm trying to deploy an API (made in Node) at Vercel (https://vercel.com, before Now) from the CLI. But when I deploy the app, I open the site and the result is just the files in the path directory, and not the app running. This is my server.js

```<code>    {
  "name": "subtitles-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "pre-deploy": "node deleteLastDeploy.js",
    "deploy": "npm run pre-deploy && now --public && now alias",
    "test": "echo \"Error: no test specified\" && exit 1"
  }
  "engines": {
    "node": ">=6.9"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    //list of dependencies
  }
}
</code>```

To see the full API: https://github.com/bitflix-official/subtitles-api

答: You should look at https://github.com/Chuloo/now-express repository for their serverless boilerplate code</p>

Body:
I'm trying to deploy an API (made in Node) at Vercel (https://vercel.com, before Now) from the CLI. But when I deploy the app, I open the site and the result is just the files in the path directory, and not the app running. This is my server.js

    {
  "name": "subtitles-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node server.js",
    "pre-deploy": "node deleteLastDeploy.js",
    "deploy": "npm run pre-deploy && now --public && now alias",
    "test": "echo \"Error: no test specified\" && exit 1"
  }
  "engines": {
    "node": ">=6.9"
  },
  "keywords": [],
  "author": "",
  "license": "MIT",
  "dependencies": {
    //list of dependencies
  }
}

To see the full API: https://github.com/bitflix-official/subtitles-api