问:
C# Queries "Linq to XML" with complex filtering
Since I am new at Linq to XML, I practice using MS official document. I want the result Computer Keyboard from PurchaseOrderNumber="99504" and Item PartNumber="898-AZ" and ProductName. Can you give a guide for this?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ParsingXML_220211
{
    public class LINQtoXML
    {
        public LINQtoXML()
        {

        }

        public void ParsingXML(string path)
        {
            XElement root = XElement.Load(path);
            IEnumerable<XElement> purchaseOrders =
                from po in root.Elements("PurchaseOrder")
                where (from add in po.Elements("Address")
                       where (string)add.Attribute("Type") == "Billing" &&
                             (string)add.Element("City") == "Buffalo"
                       select add)
                    .Any()
                select po;
            foreach (XElement po in purchaseOrders)
            {
                var result = from item in po.Elements("Items")
                             where (string)item.Element("item").Attribute("PartNumber") == "898-AZ"
                             select item;
                Console.WriteLine( result.Elements("ProductName").ToString());
            }

        }
    }
}

</code>```

Main

```<code>using System;
using System.Diagnostics;
using System.Xml;

namespace ParsingXML_220211
{
    public class Program
    {
        //https://kibbomi.tistory.com/188
        static void Main(string[] args)
        {
            //Linq to XML
            LINQtoXML linQtoXml
                = new LINQtoXML();
            linQtoXml.ParsingXML("./../../../LinqToXML.xml");

        }
    }
}

</code>```

LinqToXML.xml

```<code>
<?xml version="1.0"?>
<PurchaseOrders>
  <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
    <Address Type="Shipping">
      <Name>Ellen Adams</Name>
      <Street>123 Maple Street</Street>
      <City>Mill Valley</City>
      <State>CA</State>
      <Zip>10999</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Tai Yee</Name>
      <Street>8 Oak Avenue</Street>
      <City>Old Town</City>
      <State>PA</State>
      <Zip>95819</Zip>
      <Country>USA</Country>
    </Address>
    <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
    <Items>
      <Item PartNumber="872-AA">
        <ProductName>Lawnmower</ProductName>
        <Quantity>1</Quantity>
        <USPrice>148.95</USPrice>
        <Comment>Confirm this is electric</Comment>
      </Item>
      <Item PartNumber="926-AA">
        <ProductName>Baby Monitor</ProductName>
        <Quantity>2</Quantity>
        <USPrice>39.98</USPrice>
        <ShipDate>1999-05-21</ShipDate>
      </Item>
    </Items>
  </PurchaseOrder>
  <PurchaseOrder PurchaseOrderNumber="99505" OrderDate="1999-10-22">
    <Address Type="Shipping">
      <Name>Cristian Osorio</Name>
      <Street>456 Main Street</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Cristian Osorio</Name>
      <Street>456 Main Street</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <DeliveryNotes>Please notify me before shipping.</DeliveryNotes>
    <Items>
      <Item PartNumber="456-NM">
        <ProductName>Power Supply</ProductName>
        <Quantity>1</Quantity>
        <USPrice>45.99</USPrice>
      </Item>
    </Items>
  </PurchaseOrder>
  <PurchaseOrder PurchaseOrderNumber="99504" OrderDate="1999-10-22">
    <Address Type="Shipping">
      <Name>Jessica Arnold</Name>
      <Street>4055 Madison Ave</Street>
      <City>Seattle</City>
      <State>WA</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Jessica Arnold</Name>
      <Street>4055 Madison Ave</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Items>
      <Item PartNumber="898-AZ">
        <ProductName>Computer Keyboard</ProductName>
        <Quantity>1</Quantity>
        <USPrice>29.99</USPrice>
      </Item>
      <Item PartNumber="898-AM">
        <ProductName>Wireless Mouse</ProductName>
        <Quantity>1</Quantity>
        <USPrice>14.99</USPrice>
      </Item>
    </Items>
  </PurchaseOrder>
</PurchaseOrders>
</code>```

答:
You have a typo here, it should be "Item"

```<code>where (string)item.Element("item").Attribute("PartNumber") == "898-AZ"
</code>```

If you just want the word "Computer Keyboard", add a foreach

```<code>var result = from item in po.Elements("Items")
                             where (string)item.Element("Item").Attribute("PartNumber") == "898-AZ"
                             select item.Element("Item");
                foreach (XElement item in result)
                {
                    Console.WriteLine((string)item.Element("ProductName"));
                }
</code>```

Body:
Since I am new at Linq to XML, I practice using MS official document. I want the result Computer Keyboard from PurchaseOrderNumber="99504" and Item PartNumber="898-AZ" and ProductName. Can you give a guide for this?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace ParsingXML_220211
{
    public class LINQtoXML
    {
        public LINQtoXML()
        {

        }

        public void ParsingXML(string path)
        {
            XElement root = XElement.Load(path);
            IEnumerable<XElement> purchaseOrders =
                from po in root.Elements("PurchaseOrder")
                where (from add in po.Elements("Address")
                       where (string)add.Attribute("Type") == "Billing" &&
                             (string)add.Element("City") == "Buffalo"
                       select add)
                    .Any()
                select po;
            foreach (XElement po in purchaseOrders)
            {
                var result = from item in po.Elements("Items")
                             where (string)item.Element("item").Attribute("PartNumber") == "898-AZ"
                             select item;
                Console.WriteLine( result.Elements("ProductName").ToString());
            }

        }
    }
}

Main

using System;
using System.Diagnostics;
using System.Xml;

namespace ParsingXML_220211
{
    public class Program
    {
        //https://kibbomi.tistory.com/188
        static void Main(string[] args)
        {
            //Linq to XML
            LINQtoXML linQtoXml
                = new LINQtoXML();
            linQtoXml.ParsingXML("./../../../LinqToXML.xml");

        }
    }
}

LinqToXML.xml

<?xml version="1.0"?>
<PurchaseOrders>
  <PurchaseOrder PurchaseOrderNumber="99503" OrderDate="1999-10-20">
    <Address Type="Shipping">
      <Name>Ellen Adams</Name>
      <Street>123 Maple Street</Street>
      <City>Mill Valley</City>
      <State>CA</State>
      <Zip>10999</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Tai Yee</Name>
      <Street>8 Oak Avenue</Street>
      <City>Old Town</City>
      <State>PA</State>
      <Zip>95819</Zip>
      <Country>USA</Country>
    </Address>
    <DeliveryNotes>Please leave packages in shed by driveway.</DeliveryNotes>
    <Items>
      <Item PartNumber="872-AA">
        <ProductName>Lawnmower</ProductName>
        <Quantity>1</Quantity>
        <USPrice>148.95</USPrice>
        <Comment>Confirm this is electric</Comment>
      </Item>
      <Item PartNumber="926-AA">
        <ProductName>Baby Monitor</ProductName>
        <Quantity>2</Quantity>
        <USPrice>39.98</USPrice>
        <ShipDate>1999-05-21</ShipDate>
      </Item>
    </Items>
  </PurchaseOrder>
  <PurchaseOrder PurchaseOrderNumber="99505" OrderDate="1999-10-22">
    <Address Type="Shipping">
      <Name>Cristian Osorio</Name>
      <Street>456 Main Street</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Cristian Osorio</Name>
      <Street>456 Main Street</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <DeliveryNotes>Please notify me before shipping.</DeliveryNotes>
    <Items>
      <Item PartNumber="456-NM">
        <ProductName>Power Supply</ProductName>
        <Quantity>1</Quantity>
        <USPrice>45.99</USPrice>
      </Item>
    </Items>
  </PurchaseOrder>
  <PurchaseOrder PurchaseOrderNumber="99504" OrderDate="1999-10-22">
    <Address Type="Shipping">
      <Name>Jessica Arnold</Name>
      <Street>4055 Madison Ave</Street>
      <City>Seattle</City>
      <State>WA</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Address Type="Billing">
      <Name>Jessica Arnold</Name>
      <Street>4055 Madison Ave</Street>
      <City>Buffalo</City>
      <State>NY</State>
      <Zip>98112</Zip>
      <Country>USA</Country>
    </Address>
    <Items>
      <Item PartNumber="898-AZ">
        <ProductName>Computer Keyboard</ProductName>
        <Quantity>1</Quantity>
        <USPrice>29.99</USPrice>
      </Item>
      <Item PartNumber="898-AM">
        <ProductName>Wireless Mouse</ProductName>
        <Quantity>1</Quantity>
        <USPrice>14.99</USPrice>
      </Item>
    </Items>
  </PurchaseOrder>
</PurchaseOrders>

Body:
You have a typo here, it should be "Item"

where (string)item.Element("item").Attribute("PartNumber") == "898-AZ"

If you just want the word "Computer Keyboard", add a foreach

var result = from item in po.Elements("Items")
                             where (string)item.Element("Item").Attribute("PartNumber") == "898-AZ"
                             select item.Element("Item");
                foreach (XElement item in result)
                {
                    Console.WriteLine((string)item.Element("ProductName"));
                }


来源: stackexchange

问:
Adding a legend + slope of trend line in ggplot()
Using ggplot and the following code I created the plot below:

```<code>df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(colour = "blue") +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, color="red") +
  xlab("Date") +
  ylab("Number of Visits")
</code>```

However, I am wondering how to:

add a legend differentiating between the blue line (number of visits) and red line (line of best fit) and

annotate this chart with the equation of the red line in the form of y = mx + c

Thanks!

Edit: Sample data

df_have

```<code>   num_visits     date
1      19.825 2021.000
2      25.025 2021.083
3      27.950 2021.167
4      25.425 2021.250
5      29.575 2021.333
</code>```

答:
Update: One way could be using ggpmisc package:

```<code>library(tidyverse)
library(ggpmisc)

my.formula <- y ~ x
df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(aes(colour = "blue")) +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red")) +
  stat_poly_eq(formula = my.formula,
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE) +
  xlab("Date") +
  ylab("Number of Visits")+
  scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx + c'))
</code>```

First_answer:
You mean this kind of output?

```<code>df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(aes(colour = "blue")) +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red")) +
  xlab("Date") +
  ylab("Number of Visits")+
  scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx + c'))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using ggplot and the following code I created the plot below:

df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(colour = "blue") +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, color="red") +
  xlab("Date") +
  ylab("Number of Visits")

However, I am wondering how to:

add a legend differentiating between the blue line (number of visits) and red line (line of best fit) and

annotate this chart with the equation of the red line in the form of y = mx + c

Thanks!

Edit: Sample data

df_have

   num_visits     date
1      19.825 2021.000
2      25.025 2021.083
3      27.950 2021.167
4      25.425 2021.250
5      29.575 2021.333

Body:
Update: One way could be using ggpmisc package:

library(tidyverse)
library(ggpmisc)

my.formula <- y ~ x
df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(aes(colour = "blue")) +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red")) +
  stat_poly_eq(formula = my.formula,
               aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
               parse = TRUE) +
  xlab("Date") +
  ylab("Number of Visits")+
  scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx + c'))

First_answer:
You mean this kind of output?

df_have %>%
  ggplot(aes(date, num_visits)) +
  geom_line(aes(colour = "blue")) +
  ggtitle("Number of Customers Visiting Store by Month") +
  geom_smooth(method = "lm", fit = num_visits ~ date, se=F, aes(color="red")) +
  xlab("Date") +
  ylab("Number of Visits")+
  scale_color_manual(values = c('blue', 'red'), labels=c('num_visits', 'y = mx + c'))


答:
In case anyone's interested here's a recursive merge sort implementation. You'll need Python 3.8+</p>
```<code>def mergeSort(arr):
    if len(arr) > 1:
        mid = len(arr) >> 1
        mergeSort(left := arr[:mid])
        mergeSort(right := arr[mid:])

        i = j = k = 0

        ll, lr = len(left), len(right)

        while i < ll and j < lr:
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < ll:
            arr[k] = left[i]
            k += 1
            i += 1

        while j < lr:
            arr[k] = right[j]
            k += 1
            j += 1
</code>```

Title: Mergesort Implementation gone wrong

Body:
Output not as expected

import random

def mergeSort(a):

    width = 1
    n = len(a)

    while (width < n):

        l = 0
        while (l < n):
            r = min(l + (width * 2 - 1), n - 1)
            m = (l + r) // 2

            if (width > n // 2):
                m = r - ( n % width)
            merge(a, l, m, r)
            l += width * 2

        width *= 2
    return a

def merge(a, l, m, r):
    n1 = m - l + 1
    n2 = r - m
    L = [0] * n1
    R = [0] * n2
    for i in range(0, n1):
        L[i] = a[l + i]
    for i in range(0, n2):
        R[i] = a[m + i + 1]

    i = 0
    j = 0
    k = l
    while (i < n1) and (j < n2):
        if L[i] > R[j]:
            a[k] = R[j]
            j += 1
        else:
            a[k] = L[i]
            i += 1
        k += 1

    while i < n1:
        a[k] = L[i]
        i += 1
        k += 1

    while j < n2:
        a[k] = R[j]
        j += 1
        k += 1

def create_random_list(n):
    L = []
    for _ in range(n):
        L.append(random.randint(1,n))
    return L

a = create_random_list(100)
print("Given array is ")
print(a)

mergeSort(a)

print("Sorted array is ")
print(a)```

output

Given array is
[54, 17, 12, 61, 54, 13, 42, 82, 14, 65, 72, 11, 38, 76, 75, 56, 30, 1, 48, 52, 49, 88, 62, 94, 37, 98, 99, 79, 2, 77, 16, 67, 94, 14, 11, 24, 25, 20, 55, 92, 83, 85, 99, 50, 93, 49, 91, 73, 24, 84, 68, 21, 100, 4, 54, 65, 43, 74, 43, 60, 9, 27, 68, 15, 71, 39, 19, 69, 87, 56, 63, 56, 56, 70, 1, 51, 4, 87, 84, 7, 92, 30, 97, 74, 34, 45, 89, 33, 13, 41, 14, 92, 46, 8, 28, 72, 72, 37, 34, 64]

Sorted array is
[1, 1, 2, 4, 4, 7, 8, 9, 11, 11, 12, 13, 13, 14, 14, 14, 15, 16, 17, 19, 20, 21, 24, 24, 25, 27, 28, 30, 30, 33, 34, 37, 38, 39, 41, 42, 43, 43, 45, 46, 48, 49, 49, 50, 51, 52, 54, 54, 54, 55, 56, 56, 56, 56, 60, 61, 62, 63, 65, 65, 67, 68, 68, 69, 70, 71, 72, 72, 73, 74, 74, 75, 76, 77, 79, 82, 83, 84, 84, 85, 87, 87, 88, 89, 91, 92, 92, 92, 93, 94, 94, 97, 34, 37, 64, 72, 98, 99, 99, 100]

Body:
In case anyone's interested here's a recursive merge sort implementation. You'll need Python 3.8+

def mergeSort(arr):
    if len(arr) > 1:
        mid = len(arr) >> 1
        mergeSort(left := arr[:mid])
        mergeSort(right := arr[mid:])

        i = j = k = 0

        ll, lr = len(left), len(right)

        while i < ll and j < lr:
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < ll:
            arr[k] = left[i]
            k += 1
            i += 1

        while j < lr:
            arr[k] = right[j]
            k += 1
            j += 1


问:
Does the Go language have function/method overloading?
I'm porting a C library to Go. A C function (with varargs) is defined like this:

```<code>curl_easy_setopt(CURL *curl, CURLoption option, ...);
</code>```

So I created wrapper C functions:

```<code>curl_wrapper_easy_setopt_str(CURL *curl, CURLoption option, char* param);
curl_wrapper_easy_setopt_long(CURL *curl, CURLoption option, long param);
</code>```

If I define function in Go like this:

```<code>func (e *Easy)SetOption(option Option, param string) {
    e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(param)))
}

func (e *Easy)SetOption(option Option, param long) {
    e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(param)))
}
</code>```

The Go compiler complains:

```<code>*Easy·SetOption redeclared in this block
</code>```

So does Go support function (method) overloading, or does this error mean something else?

答:
Even though this question is really old, what I still want to say is that there is a way to acheive something close to overloading functions. Although it may not make the code so easy to read.

Say if you want to overload the funtion Test():

func Test(a int) {
    println(a);
}
func Test(a int, b string) {
    println(a);
    println(b);
}
```
<p>The code above will cause error. However if you redefine the first <code>Test()</code> to <code>Test1()</code> and the second to <code>Test2()</code>, and define a new function <code>Test()</code> using go's <code>...</code>, you would be able to call the function <code>Test()</code> the way it is overloaded.
code:</p>
<pre class="lang-golang prettyprint-override"><code>package main;

func Test1(a int) {
    println(a);
}
func Test2(a int, b string) {
    println(a);
    println(b);
}
func Test(a int, bs ...string) {
    if len(bs) == 0 {
        Test1(a);
    } else {
        Test2(a, bs[0]);
    }
}
func main() {
    Test(1);
    Test(1, "aaa");
}
</code>```

output:

```<code>1
1
aaa
</code>```

see more at: https://golangbyexample.com/function-method-overloading-golang/ (I'm not the author of this linked article but personally consider it useful)

ContentLicense: CC BY-SA 3.0

Body:
I'm porting a C library to Go. A C function (with varargs) is defined like this:

curl_easy_setopt(CURL *curl, CURLoption option, ...);

So I created wrapper C functions:

curl_wrapper_easy_setopt_str(CURL *curl, CURLoption option, char* param);
curl_wrapper_easy_setopt_long(CURL *curl, CURLoption option, long param);

If I define function in Go like this:

func (e *Easy)SetOption(option Option, param string) {
    e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(param)))
}

func (e *Easy)SetOption(option Option, param long) {
    e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(param)))
}

The Go compiler complains:

*Easy·SetOption redeclared in this block

So does Go support function (method) overloading, or does this error mean something else?

Body:
Even though this question is really old, what I still want to say is that there is a way to acheive something close to overloading functions. Although it may not make the code so easy to read.

Say if you want to overload the funtion Test():

func Test(a int) {
    println(a);
}
func Test(a int, b string) {
    println(a);
    println(b);
}

The code above will cause error. However if you redefine the first Test() to Test1() and the second to Test2(), and define a new function Test() using go's ..., you would be able to call the function Test() the way it is overloaded.
code:

package main;

func Test1(a int) {
    println(a);
}
func Test2(a int, b string) {
    println(a);
    println(b);
}
func Test(a int, bs ...string) {
    if len(bs) == 0 {
        Test1(a);
    } else {
        Test2(a, bs[0]);
    }
}
func main() {
    Test(1);
    Test(1, "aaa");
}

output:

1
1
aaa

see more at: https://golangbyexample.com/function-method-overloading-golang/ (I'm not the author of this linked article but personally consider it useful)


问:
Input field that only allows numbers but doesn't allow a single 0 in ReactJS
I need an input form that works with money. You can't type text, symbols, or anything besides numbers but you also shouldn't be able to put $0. It should be $1 and up. When I put /^[0-9\b]+$/ it only allows numbers but you can put $0. When I use /^[1-9\b]+$/ it doesn't let you put in a zero but if you type 1 and try to put a zero it won't let you. When I try /^[1-9\b]+/, it doesn't allow zero but now you can type text and characters. Is there a better way to do this?

const re = /^[0-9\b]+$/ is the current regex I'm using.

This is in ReactJS

答:
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financialGoal: ''
    }
  }

  handleChange(evt) {
    const financialGoal = (evt.target.validity.valid) ? evt.target.value : this.state.financialGoal;

    this.setState({ financialGoal });
  }

  render() {
    return (
      <input type="number" pattern="[0-9]*" min="1" step="any" onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
    )
  }
}

ReactDOM.render(<Example />, document.body);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

Body:
class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      financialGoal: ''
    }
  }

  handleChange(evt) {
    const financialGoal = (evt.target.validity.valid) ? evt.target.value : this.state.financialGoal;

    this.setState({ financialGoal });
  }

  render() {
    return (
      <input type="number" pattern="[0-9]*" min="1" step="any" onInput={this.handleChange.bind(this)} value={this.state.financialGoal} />
    )
  }
}

ReactDOM.render(<Example />, document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


问:
Algorithm to determine whether a point lies within a bounded area
How does one determine whether one or more points lie within an area whose boundary is given? For instance, in the following figure, three blue points lie within the area bounded in red, two red points lie within the area bounded in blue, and there are three points - two blue and one red - which do not lie within either of the indicated areas.

答:
Draw a line from the point. check if it crosses any of the region edges and what side of the line it is.

If it crosses them odd number of times on each side it is in the region.


问:
Python 3.7 BeautifullSoup soup.find error - find() takes no keyword arguments
I had the below HTML from URL:

```<code><h4>
   \r\n                            \r\n\r\n
   <a href="/l">
      \r\n    <!-- mp_trans_rt_start id="1" args="as" 1 -->\r\n    <span class="brandWrapTitle">\r\n        <span class="productdescriptionbrand">Mxxx</span>\r\n    </span>\r\n    <span class="nameWrapTitle">\r\n        <span class="productdescriptionname">Axxxname</span>\r\n    </span>\r\n    <!-- mp_trans_rt_end 1 -->\r\n
   </a>
   \r\n\r\n
</h4>
</code>```

And im trying to use python to find  class name:

```<code>  import urllib.request
from bs4 import BeautifulSoup
url = "https://link"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
urlwithagent = urllib.request.Request(url,headers={'User-Agent': user_agent})
response = urllib.request.urlopen(urlwithagent)
soup = response.read()
product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
print (product)
</code>```

Everythink works perfect until line :

```<code>product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
</code>```

Im getting error like:

```<code>find() takes no keyword arguments
</code>```

And I had no idea how to fix it - there is lot of info around but nothing works :/

答:
I thought this would be worth mentioning, if having problems with find method, checking type(soup) is a good way to find out if you're working with the correct bs4.BeautifulSoup object and not str.

One thing I'd like to point here, if using soup.prettify() to make the html readable. It is important to note that .prettify() converts the bs4.BeautifulSoup to str. So this should be used separately like:

```<code>soup = BeautifulSoup(response) # type(soup) --> bs4.BeautifulSoup
print(soup.prettify()) # print readable html
</code>```

And not like:

```<code>soup = BeautifulSoup(response).prettify() # type(soup) --> str
</code>```

One more thing that I read online regarding this issue was something like "Your version of beautiful soup might not support find." Hence, I ended up upgrading and degrading the version quite a few times before realising that it was a false statement made by someone amateur.

I had been struggling for about 45 minutes with just this before printing type(soup). I hope this saves someones else their time.

Body:
I had the below HTML from URL:

   \r\n                            \r\n\r\n

      \r\n    \r\n    \r\n        Mxxx\r\n    \r\n    \r\n        Axxxname\r\n    \r\n    \r\n

   \r\n\r\n

And im trying to use python to find  class name:

  import urllib.request
from bs4 import BeautifulSoup
url = "https://link"
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
urlwithagent = urllib.request.Request(url,headers={'User-Agent': user_agent})
response = urllib.request.urlopen(urlwithagent)
soup = response.read()
product = soup.find("h4", attrs ={"class=": "productdescriptionname"})
print (product)

Everythink works perfect until line :

product = soup.find("h4", attrs ={"class=": "productdescriptionname"})

Im getting error like:

find() takes no keyword arguments

And I had no idea how to fix it - there is lot of info around but nothing works :/

Body:
I thought this would be worth mentioning, if having problems with find method, checking type(soup) is a good way to find out if you're working with the correct bs4.BeautifulSoup object and not str.

One thing I'd like to point here, if using soup.prettify() to make the html readable. It is important to note that .prettify() converts the bs4.BeautifulSoup to str. So this should be used separately like:

soup = BeautifulSoup(response) # type(soup) --> bs4.BeautifulSoup
print(soup.prettify()) # print readable html

And not like:

soup = BeautifulSoup(response).prettify() # type(soup) --> str

One more thing that I read online regarding this issue was something like "Your version of beautiful soup might not support find." Hence, I ended up upgrading and degrading the version quite a few times before realising that it was a false statement made by someone amateur.

I had been struggling for about 45 minutes with just this before printing type(soup). I hope this saves someones else their time.


问:
String not recognised in intent.putExtra Unexpected tokens error
enter image description here

fun createBirthdayCard(view: View) {

```<code>     val name = nameInput.editableText.toString()

     val intent = Intent(this, BirthdayGreeting::class.java)
        intent.putExtra(name:"name", name)
     startActivity(intent)
 }
</code>```

}

答:
remove name: you don't need to mention it . just write like this</p>
```<code>   intent.putExtra("name", name)
</code>```

Body:
enter image description here

fun createBirthdayCard(view: View) {

     val name = nameInput.editableText.toString()

     val intent = Intent(this, BirthdayGreeting::class.java)
        intent.putExtra(name:"name", name)
     startActivity(intent)
 }

}

Body:
remove name: you don't need to mention it . just write like this

   intent.putExtra("name", name)


问:
Forum Post To Url
I have this project where I have to post data to the url given following specific parameters. I am getting errors and my code is just messy in general. One thing that got me stumped is how I can convert specific values in the JSON object to int. For example the parameter "tickets" requests a integer. Any help would be great.

```<code><form class="form" id="form" name="form"  action="https://api.leadprosper.io/ingest" method="post" enctype="multipart/form-data" >
            <div id="wizard">
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="FirstName">First Name</label>
                        <input type="hidden" type="number" id="lp_campaign_id" name="lp_campaign_id" value="5848" required>
                        <input type="hidden" type="number" id="lp_supplier_id" name="lp_supplier_id" value="5848" required>
                        <input type="hidden" id="lp_campaign_id" name="lp_key" value="131bvmpb2" required>
                        <input type="text" id="FirstName" name="FirstName" required>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="LastName">Last Name</label>
                        <input type="text" id="LastName" name="LastName" required>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Email">Email</label>
                        <input pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" type="email" id="Email" name="Email"  required>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Phone">phone</label>
                        <input type="phone"  type="text" pattern="^[789]\d{9,9}$" min="1" max="10" id="Phone" Name="Phone" required>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="VehicleYear">Vehicle Year</label>
                        <input pattern="[0-9]{1,15}" type="number" id="VehicleYear" name="VehicleYear" required>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="PurchaseDateMonth">Purchase Date Month</label>
                        <input pattern="[a-zA-z]{1,15}" type="text" id="PurchaseDateMonth" name="PurchaseDateMonth" required placeholder="September">
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="PurchaseDateYear">Purchaes Date Year</label>
                        <input pattern="[0-9]{1,15}" type="number" id="PurchaseDateYear" name="PurchaseDateYear" placeholder="2022" required>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="FinancedLeased">Finance Leased</label>
                        <select type="text" id="FinancedLeased" name="FinancedLeased" placeholder="">
                            <option value="finance">finance</option>
                            <option value="leased">leased</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Goal">Goal</label>
                        <input pattern="[a-zA-Z]{1,15}" type="text" id="Goal" name="Goal" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="DailyDistance">Daily Distance</label>
                        <input pattern="[0-9]{1,15}" type="text" id="DailyDistance" name="DailyDistance" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="YearlyDistance">Yearly Distance</label>
                        <input pattern="[0-9]{1,15}" type="text" id="YearlyDistance" name="YearlyDistance" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="CompCoverage">Company Coverage</label>
                        <select type="text" id="CompCoverage" name="CompCoverage" placeholder="">
                            <option value="yes">yes</option>
                            <option value="no">no</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="CollisionCoverage">Collision Converage</label>
                        <select type="text" id="CollisionCoverage" name="CollisionCoverage" placeholder="">
                            <option value="yes">yes</option>
                            <option value="no">no</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="MaritalStatus">Marital Status</label>
                        <select type="text" id="MaritalStatus" name="MaritalStatus" placeholder="">
                            <option value="single">single</option>
                            <option value="married/common law">married/common law</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label id="dob"for="DOB">Date of Birth</label>
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="datetime" id="DOB" name="DOB" placeholder="yyyy-mm-dd">
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Occupation">Occupation</label>
                        <input patter="[a-zA-Z]{1,15}" type="text" id="Occupation" name="Occupation" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">

                    <div class="form-row">
                        <label for="genGenderder">gender</label>
                        <select type="text" id="Gender"  name="genGenderder" placeholder="">
                            <option value="male">male</option>
                            <option value="female">female</option>
                            <option value='other'>other</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="LicenseClass">Licence Class</label>
                        <select type="text" id="LicenseClass" name="LicenseClass" placeholder="">
                            <option value="class 5">class 5</option>
                            <option value="class 5-1">class 5-1</option>
                            <option value="class 5-2">class 5-2</option>
                            <option value="other">other</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-4">

                    <div class="form-row">
                        <label for="DriverAge">Driver Age</label>
                        <input pattern="[0-9]{1,15}" type="text" id="DriverAge" name="DriverAge" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="InsuranceCancellation">Insurance Cancellation</label>
                        <select type="text" id="InsuranceCancellation" name="InsuranceCancellation" placeholder="">
                            <option value="no">no</option>
                            <option value="yes">yes</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">

                    <div class="form-row">
                        <label for="Suspensions">Suspensions</label>
                        <select type="text" id="Suspensions" name="Suspensions"  placeholder="">
                            <option value="no">no</option>
                            <option value="yes-once">yes once</option>
                            <option value="yes-more">yes more than once
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Claims">claim</label>
                        <select type="text" id="Claims" name="Claims" placeholder="">
                            <option value="no">no</option>
                            <option value="yes">yes</option>
                        </select>
                        <div class="error"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">

                    <div class="form-row">
                        <label for="Tickets">Tickets</label>
                        <input pattern="[0-9]{1,10}" type="text" id="Tickets" name="Tickets" placeholder="">
                        <div class="error"></div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="StartDate">Start Date</label>
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="datetime" id="StartDate" name="StartDate" placeholder="yyyy-mm-dd">
                        <div class="error"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">

                <div class="col-md-4">
                    <div class="form-row">
                        <label for="licenceSince">Licence Since</label>
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="text" id="licenceSince"  name="licenceSince"  placeholder="yyyy-mm-dd">
                        <div class="error"></div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="City">City</label>
                        <input type="text" id="City" name="City" required>
                        <div class="error"></div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-row">
                            <label for="state">State</label>
                            <input pattern="[a-zA-z]{2}" type="text" id="State" name="State" required>
                            <div class="error"></div>
                        </div>
                    </div>
            <div class="row">
                <div class="col-md-4">
                    <div class="form-row">
                        <label for="Postal">Postal</label>
                        <input type="text" pattern="[A-za-z0-9]{5}"  id="Postal" name="Postal" required>
                        <div class="error"></div>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="sumbit">
                    <button type="submit" >Submit</button>
                </div>
            </div>
            </div>
        </form>
</code>```

Javascript

```<code><script>
const Form = document.querySelectorAll('form');

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

    const formData = new FormData(this);
    const searchParams = new URLSearchParams();

    for(const pair of formData){
        searchParams.append(pair[0],pair[1]);
        console.log(pair[0],pair[1]);
    }
    console.log(formData);
    const response =  fetch('https://api.leadprosper.io/ingest', {

        method: 'POST',
        body: searchParams,
        headers:{
            'Content-Type': 'application/json;'
        }
    }).then(function (reponse){
       return reponse.json();

    }).then(function(text){
        console.log(text);
    }).catch(function (error){
        console.error(error);
    })

})
</script>
</code>```

Payload with the paramaters I need to follow.

```<code>{
    "lp_campaign_id": "5848",
    "lp_supplier_id": "5848",
    "lp_key": "131bvmpb2",
    "FirstName": "Amelia",
    "LastName": "Nakia",
    "Email": "jbaumbach@example.com",
    "Phone": "3866311306",
    "VehicleYear": 4,
    "PurchaseDateMonth": "Groves",
    "PurchaseDateYear": 1,
    "FinancedLeased": "gray",
    "Goal": "Thursday",
    "DailyDistance": 7,
    "YearlyDistance": 5,
    "CompCoverage": "no",
    "CollisionCoverage": "yes",
    "MaritalStatus": "fuchsia",
    "DOB": "2022-02-03",
    "Occupation": "South",
    "Gender": "male",
    "LicenseClass": "lime",
    "DriverAge": 6,
    "LicensedSince": 2,
    "LicenseLength": "Springs",
    "InsuranceCancellation": "no",
    "Suspensions": "no",
    "Claims": "West",
    "Tickets": 7,
    "StartDate": "2022-02-07",
    "City": "Lake Bailee",
    "State": "AL",
    "Postal": "68820"
}
</code>```

答:
First of all, if you want to get only numbers from input, convert your html code to this:

```<code>                    <div class="form-row">
                        <label for="Tickets">Tickets</label>
                        <input pattern="[0-9]{1,10}" type="text" id="Tickets" name="Tickets" placeholder="">
                        <div class="error"></div>
                    </div>
</code>```

then when you want to get value as an integer type, you should put it in parseInt();
Like this:

```<code>var data = parseInt(document.getElementById('tickets')) // data is an integer
</code>```

if you want to change value from a JSON object you can simply change the value by reading it like this:

```<code>data = {
  tickets : 5
}

// to change the number in tickets

data.tickets = 12
</code>```

Title: Forum Post To Url

Body:
I have this project where I have to post data to the url given following specific parameters. I am getting errors and my code is just messy in general. One thing that got me stumped is how I can convert specific values in the JSON object to int. For example the parameter "tickets" requests a integer. Any help would be great.

<form class="form" id="form" name="form"  action="https://api.leadprosper.io/ingest" method="post" enctype="multipart/form-data" >

                        First Name
                        <input type="hidden" type="number" id="lp_campaign_id" name="lp_campaign_id" value="5848" required>
                        <input type="hidden" type="number" id="lp_supplier_id" name="lp_supplier_id" value="5848" required>
                        <input type="hidden" id="lp_campaign_id" name="lp_key" value="131bvmpb2" required>
                        <input type="text" id="FirstName" name="FirstName" required>

                        Last Name
                        <input type="text" id="LastName" name="LastName" required>

                        Email
                        <input pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" type="email" id="Email" name="Email"  required>

                        phone
                        <input type="phone"  type="text" pattern="^[789]\d{9,9}$" min="1" max="10" id="Phone" Name="Phone" required>

                        Vehicle Year
                        <input pattern="[0-9]{1,15}" type="number" id="VehicleYear" name="VehicleYear" required>

                        Purchase Date Month
                        <input pattern="[a-zA-z]{1,15}" type="text" id="PurchaseDateMonth" name="PurchaseDateMonth" required placeholder="September">

                        Purchaes Date Year
                        <input pattern="[0-9]{1,15}" type="number" id="PurchaseDateYear" name="PurchaseDateYear" placeholder="2022" required>

                        Finance Leased
                        <select type="text" id="FinancedLeased" name="FinancedLeased" placeholder="">
                            <option value="finance">finance</option>
                            <option value="leased">leased</option>
                        </select>

                        Goal
                        <input pattern="[a-zA-Z]{1,15}" type="text" id="Goal" name="Goal" placeholder="">

                        Daily Distance
                        <input pattern="[0-9]{1,15}" type="text" id="DailyDistance" name="DailyDistance" placeholder="">

                        Yearly Distance
                        <input pattern="[0-9]{1,15}" type="text" id="YearlyDistance" name="YearlyDistance" placeholder="">

                        Company Coverage
                        <select type="text" id="CompCoverage" name="CompCoverage" placeholder="">
                            <option value="yes">yes</option>
                            <option value="no">no</option>
                        </select>

                        Collision Converage
                        <select type="text" id="CollisionCoverage" name="CollisionCoverage" placeholder="">
                            <option value="yes">yes</option>
                            <option value="no">no</option>
                        </select>

                        Marital Status
                        <select type="text" id="MaritalStatus" name="MaritalStatus" placeholder="">
                            <option value="single">single</option>
                            <option value="married/common law">married/common law</option>
                        </select>

                        Date of Birth
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="datetime" id="DOB" name="DOB" placeholder="yyyy-mm-dd">

                        Occupation
                        <input patter="[a-zA-Z]{1,15}" type="text" id="Occupation" name="Occupation" placeholder="">

                        gender
                        <select type="text" id="Gender"  name="genGenderder" placeholder="">
                            <option value="male">male</option>
                            <option value="female">female</option>
                            <option value='other'>other</option>
                        </select>

                        Licence Class
                        <select type="text" id="LicenseClass" name="LicenseClass" placeholder="">
                            <option value="class 5">class 5</option>
                            <option value="class 5-1">class 5-1</option>
                            <option value="class 5-2">class 5-2</option>
                            <option value="other">other</option>
                        </select>

                        Driver Age
                        <input pattern="[0-9]{1,15}" type="text" id="DriverAge" name="DriverAge" placeholder="">

                        Insurance Cancellation
                        <select type="text" id="InsuranceCancellation" name="InsuranceCancellation" placeholder="">
                            <option value="no">no</option>
                            <option value="yes">yes</option>
                        </select>

                        Suspensions
                        <select type="text" id="Suspensions" name="Suspensions"  placeholder="">
                            <option value="no">no</option>
                            <option value="yes-once">yes once</option>
                            <option value="yes-more">yes more than once
                        </select>

                        claim
                        <select type="text" id="Claims" name="Claims" placeholder="">
                            <option value="no">no</option>
                            <option value="yes">yes</option>
                        </select>

                        Tickets
                        <input pattern="[0-9]{1,10}" type="text" id="Tickets" name="Tickets" placeholder="">

                        Start Date
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="datetime" id="StartDate" name="StartDate" placeholder="yyyy-mm-dd">

                        Licence Since
                        <input pattern="?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31" type="text" id="licenceSince"  name="licenceSince"  placeholder="yyyy-mm-dd">

                        City
                        <input type="text" id="City" name="City" required>

                            State
                            <input pattern="[a-zA-z]{2}" type="text" id="State" name="State" required>

                        Postal
                        <input type="text" pattern="[A-za-z0-9]{5}"  id="Postal" name="Postal" required>

                    <button type="submit" >Submit</button>

        </form>

Javascript

Payload with the paramaters I need to follow.

{
    "lp_campaign_id": "5848",
    "lp_supplier_id": "5848",
    "lp_key": "131bvmpb2",
    "FirstName": "Amelia",
    "LastName": "Nakia",
    "Email": "jbaumbach@example.com",
    "Phone": "3866311306",
    "VehicleYear": 4,
    "PurchaseDateMonth": "Groves",
    "PurchaseDateYear": 1,
    "FinancedLeased": "gray",
    "Goal": "Thursday",
    "DailyDistance": 7,
    "YearlyDistance": 5,
    "CompCoverage": "no",
    "CollisionCoverage": "yes",
    "MaritalStatus": "fuchsia",
    "DOB": "2022-02-03",
    "Occupation": "South",
    "Gender": "male",
    "LicenseClass": "lime",
    "DriverAge": 6,
    "LicensedSince": 2,
    "LicenseLength": "Springs",
    "InsuranceCancellation": "no",
    "Suspensions": "no",
    "Claims": "West",
    "Tickets": 7,
    "StartDate": "2022-02-07",
    "City": "Lake Bailee",
    "State": "AL",
    "Postal": "68820"
}

Body:
First of all, if you want to get only numbers from input, convert your html code to this:

                    <div class="form-row">
                        <label for="Tickets">Tickets</label>
                        <input pattern="[0-9]{1,10}" type="text" id="Tickets" name="Tickets" placeholder="">
                        <div class="error"></div>
                    </div>

then when you want to get value as an integer type, you should put it in parseInt();
Like this:

var data = parseInt(document.getElementById('tickets')) // data is an integer

if you want to change value from a JSON object you can simply change the value by reading it like this:

data = {
  tickets : 5
}

// to change the number in tickets

data.tickets = 12


问:
Convert unix timestamp in known timezone to datetime
I have a data download that supplies timestamps in unix form. They don't have any timezone awareness - they're simply a number - but they're localised to US/Pacific. I want to end up with them in Europe/London time. Don't ask me why it's set up like this.... I wouldn't have done it myself but not in my power to change!

I have tried

```<code>    import datetime as dt, pandas as pd
    df['time'] = pd.to_datetime(df['timestamp'], unit = 's')
    df['London time'] = df['time'].dt.tz_localize('US/Pacific').dt.tz_convert('Europe/London')
</code>```

and this works absolutely fine 99% of the time. The issue is with the DST transition where it throws an ambiguous error. Is there any way of dealing with this given that the unix time is ultimately just counting seconds and shouldn't be inherently ambiguous?

I would prefer a pandas solution, but can always use apply if need be. I had thought to use

```<code>    dt.datetime.fromtimestamp(timestamp, pytz.timezone('US/Pacific'))
</code>```

as the initial conversion from unix but this gives me the Pacific equivalent of the timestamp if it were localised on my machine.

This is a sample of the data set which throws the error.

```<code>    import pandas as pd
    test_times = [1636246173, 1636248552, 1636248678, 1636251161, 1636251689]
    df = pd.DataFrame(test_times, columns = ['timestamp'])

</code>```

答:
just you this snippet, added ambiguous=True to tz_localize

```<code>import datetime as dt, pandas as pd
df['time'] = pd.to_datetime(df['timestamp'], unit = 's')
df['London time'] = df['time'].dt.tz_localize('US/Pacific', ambiguous=True).dt.tz_convert('Europe/London')
</code>```

The error message says that it cannot infer Daylight Saving Time. Now, as probably everybody knows, the change from Daylight Saving Time to normal time occurs at the end of October at 2:00 am/3:00 am, and in fact, a quick look at the calendar tells us that DST change in 2017 was on October, 29th.

Body:
I have a data download that supplies timestamps in unix form. They don't have any timezone awareness - they're simply a number - but they're localised to US/Pacific. I want to end up with them in Europe/London time. Don't ask me why it's set up like this.... I wouldn't have done it myself but not in my power to change!

I have tried

    import datetime as dt, pandas as pd
    df['time'] = pd.to_datetime(df['timestamp'], unit = 's')
    df['London time'] = df['time'].dt.tz_localize('US/Pacific').dt.tz_convert('Europe/London')

and this works absolutely fine 99% of the time. The issue is with the DST transition where it throws an ambiguous error. Is there any way of dealing with this given that the unix time is ultimately just counting seconds and shouldn't be inherently ambiguous?

I would prefer a pandas solution, but can always use apply if need be. I had thought to use

    dt.datetime.fromtimestamp(timestamp, pytz.timezone('US/Pacific'))

as the initial conversion from unix but this gives me the Pacific equivalent of the timestamp if it were localised on my machine.

This is a sample of the data set which throws the error.

    import pandas as pd
    test_times = [1636246173, 1636248552, 1636248678, 1636251161, 1636251689]
    df = pd.DataFrame(test_times, columns = ['timestamp'])

Body:
just you this snippet, added ambiguous=True to tz_localize

import datetime as dt, pandas as pd
df['time'] = pd.to_datetime(df['timestamp'], unit = 's')
df['London time'] = df['time'].dt.tz_localize('US/Pacific', ambiguous=True).dt.tz_convert('Europe/London')

The error message says that it cannot infer Daylight Saving Time. Now, as probably everybody knows, the change from Daylight Saving Time to normal time occurs at the end of October at 2:00 am/3:00 am, and in fact, a quick look at the calendar tells us that DST change in 2017 was on October, 29th.


问:
Is it possible to move MacOS TMPDIR to another drive?
Some programs write to the macOS TMPDIR that is on the booth volume, but unfortunately, some write huge files on it (for scratch disk, Lightroom for example) and this depletes the available space, but more importantly the remaining HD space on the boot volumes (especially nowadays with Apple's soldered SSDs) the remaining pace is not enough for the scratch disk and it fails. I experience it a lot with Lightroom doing Panorama,s temp files can be hundred of Gigagbytes. Unfortunately, you can't set the scratch disk location, contrary to photoshop. It writes to the TMPDIR.

So I would like to move that TMPDIR  to another external SSD.
I tried the symbolic link but unfortunately, I don't have the permission to overwrite or rename the current temporary folder.

Maybe there's a way to change the way the TMPDIR is create so it does it on another drive than the boot drive, or maybe I could get the permission to modify the current one.

Given the fact that lots of program used that location that is often too small, it would be a major boon to get a method to put that TMPDIR on another drive.

答:
I managed to do it, by disabling SIP and then create a symbolic link to another drive as a replacement of the TMPDIR folder.

Original TMPDIR was T : /var/folders/jc/myw_64vd1vb2zsn9wps4_xnh0000gp/T

More exactly I created a symbolic to my other drive folder in the folder myw_64vd1vb2zsn9wps4_xnh0000gp and named it A.

Then I renamed the T Folder to G and then the symbolink link A to T. You've to be quick as the OS recreates T quickly.

Of course, Lightroom must be quit before doing that. But it works.

It works, but of course, you've to disable SIP which is a pain. Also, after that photoshop doesn't work anymore, other programs mays fail also.

Now, the real solution would be to tell mac os to create the temp folder to and external drive. But that's another topic. I feel it has to to with the mktemp command, If we could ask it to use and external drive it would be the perfect solution.

So the solution was to disable SIP, and then you can move the TMPDIR with a symbolic link.


问:
No tables generated using code-first in .NET Core
I am using VS 2016, SQL Server 2016, .NET Core, code-first, when I try to update the database, no table is generated.

Context:

```<code>public DataContext()
{
}

public DataContext(DbContextOptions<DataContext> options)
            : base(options)
{
}

public virtual DbSet<Relative> Relatives { get; set; }
public virtual DbSet<User> Users { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=DESKTOP-ARVMMP2\\SQLEXPRESS;Database=PraxedesDb;Trusted_Connection=True");
    }
 }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

     modelBuilder.Entity<Relative>(entity =>
            {
                entity.ToTable("Relatives");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.RelativeNames).HasColumnName("RelativeNames");
                entity.Property(e => e.RelativeLastNames).HasColumnName("RelativeLastNames");
                entity.Property(e => e.RelativeGender).HasColumnName("RelativeGender");
                entity.Property(e => e.RelativeDocumentNumber).HasColumnName("RelativeDocumentNumber");
                entity.Property(e => e.InLaw).HasColumnName("InLaw");
                entity.Property(e => e.RelativeAge).HasColumnName("RelativeAge");

                entity.Property(e => e.UserId).HasColumnName("UserId");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.Relatives)
                    .HasForeignKey(d => d.UserId)
                    .HasConstraintName("UserId");
            });

    modelBuilder.Entity<User>(entity =>
            {
                entity.ToTable("Users");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.UserNames).HasColumnName("UserNames");
                entity.Property(e => e.UserLastNames).HasColumnName("UserLastNames");
                entity.Property(e => e.UserPlatformName).HasColumnName("UserPlatformName");
                entity.Property(e => e.UserPassword).HasColumnName("UserPassword");
                entity.Property(e => e.UserGender).HasColumnName("UserGender");
                entity.Property(e => e.UserDocumentNumber).HasColumnName("UserDocumentNumber");
            });

    OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
</code>```

The models:

```<code>        public User()
        {
            Relatives = new HashSet<Relative>();
        }

        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string UserNames { get; set; }
        public string UserLastNames { get; set; }
        public string UserPlatformName { get; set; }
        public string UserPassword { get; set; }
        public string UserGender { get; set; }
        public int UserDocumentNumber { get; set; }

        public virtual ICollection<Relative> Relatives { get; set; }

    public class Relative
    {
        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string RelativeNames { get; set; }
        public string RelativeLastNames { get; set; }
        public string RelativeGender { get; set; }
        public int RelativeDocumentNumber { get; set; }
        public string InLaw { get; set; }
        public int RelativeAge { get; set; }

        public int? UserId { get; set; }
        public virtual User User { get; set; }
    }
</code>```

Startup:

```<code>public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // for reference loop handling
    services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

    // for mySettingModel
    services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));

    // for Cors Allow
    services.AddCors();

    services.AddControllers();
    // services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "PraxedesBackend", Version = "v1" });
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // for Cors Allow
    app.UseCors(options => options.WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
            );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PraxedesBackend v1"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
}
</code>```

A user has many relatives, that is the relationship between the two models.

Is there a problem on the DataContext? or maybe the models? Can you please help me?

I tried with:

```<code> modelBuilder.Entity<Relative>()
            .HasOne<User>(s => s.User)
            .WithMany(g => g.Relatives)
            .HasForeignKey(s => s.UserId);
</code>```

With no result either.

I did the migration and the update-database commands

答:
it's not enough create the classes and the dbcontext to create the database and the tables.
You have to run two commands:

```<code>dotnet ef migrations add "create db and tables"
</code>```
```<code>dotnet ef database update
</code>```

Every time you change your models you have to run these 2 commands to reflect the changes to the database...

Body:
I am using VS 2016, SQL Server 2016, .NET Core, code-first, when I try to update the database, no table is generated.

Context:

public DataContext()
{
}

public DataContext(DbContextOptions<DataContext> options)
            : base(options)
{
}

public virtual DbSet<Relative> Relatives { get; set; }
public virtual DbSet<User> Users { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    if (!optionsBuilder.IsConfigured)
    {
        optionsBuilder.UseSqlServer("Server=DESKTOP-ARVMMP2\\SQLEXPRESS;Database=PraxedesDb;Trusted_Connection=True");
    }
 }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS");

     modelBuilder.Entity<Relative>(entity =>
            {
                entity.ToTable("Relatives");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.RelativeNames).HasColumnName("RelativeNames");
                entity.Property(e => e.RelativeLastNames).HasColumnName("RelativeLastNames");
                entity.Property(e => e.RelativeGender).HasColumnName("RelativeGender");
                entity.Property(e => e.RelativeDocumentNumber).HasColumnName("RelativeDocumentNumber");
                entity.Property(e => e.InLaw).HasColumnName("InLaw");
                entity.Property(e => e.RelativeAge).HasColumnName("RelativeAge");

                entity.Property(e => e.UserId).HasColumnName("UserId");

                entity.HasOne(d => d.User)
                    .WithMany(p => p.Relatives)
                    .HasForeignKey(d => d.UserId)
                    .HasConstraintName("UserId");
            });

    modelBuilder.Entity<User>(entity =>
            {
                entity.ToTable("Users");

                entity.Property(e => e.Id)
                    .ValueGeneratedNever()
                    .HasColumnName("Id");

                entity.Property(e => e.DateOfBirth).HasColumnType("DateOfBirth");
                entity.Property(e => e.UserNames).HasColumnName("UserNames");
                entity.Property(e => e.UserLastNames).HasColumnName("UserLastNames");
                entity.Property(e => e.UserPlatformName).HasColumnName("UserPlatformName");
                entity.Property(e => e.UserPassword).HasColumnName("UserPassword");
                entity.Property(e => e.UserGender).HasColumnName("UserGender");
                entity.Property(e => e.UserDocumentNumber).HasColumnName("UserDocumentNumber");
            });

    OnModelCreatingPartial(modelBuilder);
}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

The models:

        public User()
        {
            Relatives = new HashSet<Relative>();
        }

        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string UserNames { get; set; }
        public string UserLastNames { get; set; }
        public string UserPlatformName { get; set; }
        public string UserPassword { get; set; }
        public string UserGender { get; set; }
        public int UserDocumentNumber { get; set; }

        public virtual ICollection<Relative> Relatives { get; set; }

    public class Relative
    {
        public int Id { get; set; }
        public DateTime? DateOfBirth { get; set; }
        public string RelativeNames { get; set; }
        public string RelativeLastNames { get; set; }
        public string RelativeGender { get; set; }
        public int RelativeDocumentNumber { get; set; }
        public string InLaw { get; set; }
        public int RelativeAge { get; set; }

        public int? UserId { get; set; }
        public virtual User User { get; set; }
    }

Startup:

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    // for reference loop handling
    services.AddControllers().AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            });

    // for mySettingModel
    services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));

    // for Cors Allow
    services.AddCors();

    services.AddControllers();
    // services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
    services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "PraxedesBackend", Version = "v1" });
            });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // for Cors Allow
    app.UseCors(options => options.WithOrigins("http://localhost:4200")
                .AllowAnyMethod()
                .AllowAnyHeader()
            );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "PraxedesBackend v1"));
    }

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
}

A user has many relatives, that is the relationship between the two models.

Is there a problem on the DataContext? or maybe the models? Can you please help me?

I tried with:

 modelBuilder.Entity<Relative>()
            .HasOne<User>(s => s.User)
            .WithMany(g => g.Relatives)
            .HasForeignKey(s => s.UserId);

With no result either.

I did the migration and the update-database commands

Body:
it's not enough create the classes and the dbcontext to create the database and the tables.
You have to run two commands:

dotnet ef migrations add "create db and tables"

dotnet ef database update

Every time you change your models you have to run these 2 commands to reflect the changes to the database...


问:
How to combine 2 tables in query SQL and convert to JSON
I have these tables

albums (id integer, name text, year text)

songs (id integer, title text, year text, performer text, genre text, album_id text)

This is my query

```<code>SELECT *
FROM albums
JOIN songs ON albums.id = songs.album_id
WHERE albums.id = id
</code>```

And this is the result of that query:

```<code>"albums": [
            {
                "id": "Coldplay-5KkCY8_uEaTBQqO7",
                "name": "Viva la vida",
                "year": 2008,
                "title": "Fix you",
                "performer": "Coldplay",
                "genre": "Pop",
                "album_id": "album-2008-mwlgbkMXbSqt5hlo"
            },
            {
                "id": "Coldplay-5a-QCy2W2jFTfoTR",
                "name": "Viva la vida",
                "year": 2008,
                "title": "Yellow",
                "performer": "Coldplay",
                "genre": "Pop",
                "album_id": "album-2008-mwlgbkMXbSqt5hlo"
            }
        ]
</code>```

As you can see, the albums is there twice for the same item.

I want my result for the albums to be like this:

```<code>"albums": [
            {
                "id": "album-2008-mwlgbkMXbSqt5hlo",
                "name": "Viva la vida",
                "year": 2008,
                "songs": [
                   {
                     "id": "Coldplay-5KkCY8_uEaTBQqO7"
                     "title": "Fix you",
                     "year": 2008,
                     "performer": "Coldplay",
                     "genre": "Pop",
                     "album_id": "album-2008-mwlgbkMXbSqt5hlo"
                   },
                   {
                     "id": "Coldplay-5a-QCy2W2jFTfoTR"
                     "title": "Yellow",
                     "year": 2008,
                     "performer": "Coldplay",
                     "genre": "Pop",
                     "album_id": "album-2008-mwlgbkMXbSqt5hlo"
                   }
                 ]
            }
        ]
</code>```

How can I get this result?

答:
You can use json_agg function and create sub-json data

SELECT
  albums.id,
  albums.name,
  albums.year,
  json_agg(songs.*) as songs
FROM
  albums JOIN songs ON albums.id = songs.album_id
WHERE
  albums.id = id
GROUP BY 1, 2, 3
```

Body:
I have these tables

albums (id integer, name text, year text)

songs (id integer, title text, year text, performer text, genre text, album_id text)

This is my query

SELECT *
FROM albums
JOIN songs ON albums.id = songs.album_id
WHERE albums.id = id

And this is the result of that query:

"albums": [
            {
                "id": "Coldplay-5KkCY8_uEaTBQqO7",
                "name": "Viva la vida",
                "year": 2008,
                "title": "Fix you",
                "performer": "Coldplay",
                "genre": "Pop",
                "album_id": "album-2008-mwlgbkMXbSqt5hlo"
            },
            {
                "id": "Coldplay-5a-QCy2W2jFTfoTR",
                "name": "Viva la vida",
                "year": 2008,
                "title": "Yellow",
                "performer": "Coldplay",
                "genre": "Pop",
                "album_id": "album-2008-mwlgbkMXbSqt5hlo"
            }
        ]

As you can see, the albums is there twice for the same item.

I want my result for the albums to be like this:

"albums": [
            {
                "id": "album-2008-mwlgbkMXbSqt5hlo",
                "name": "Viva la vida",
                "year": 2008,
                "songs": [
                   {
                     "id": "Coldplay-5KkCY8_uEaTBQqO7"
                     "title": "Fix you",
                     "year": 2008,
                     "performer": "Coldplay",
                     "genre": "Pop",
                     "album_id": "album-2008-mwlgbkMXbSqt5hlo"
                   },
                   {
                     "id": "Coldplay-5a-QCy2W2jFTfoTR"
                     "title": "Yellow",
                     "year": 2008,
                     "performer": "Coldplay",
                     "genre": "Pop",
                     "album_id": "album-2008-mwlgbkMXbSqt5hlo"
                   }
                 ]
            }
        ]

How can I get this result?


问:
JAVA Package won't import even though it was declared
I'm trying to compile a program but it always displays an error that my package cannot be found but its properly declared (i think)

The exact error im getting

Here's the beginning part of the code of the program im packaging:

```<code>package domain;
public class Person {
  private String name;
  private int empNO;
  private int age;
</code>```

and here's the beginning of the program Im importing it into:

```<code>package test;
import domain.*;

public class TestPerson {
     public static void main (String args[]) {
</code>```

this is essentially the directory of the project:

答: Try import com.companyName.department.domain. I think its because you didn't specify the whole path of the package you were trying to import.

Body:
I'm trying to compile a program but it always displays an error that my package cannot be found but its properly declared (i think)

The exact error im getting

Here's the beginning part of the code of the program im packaging:

package domain;
public class Person {
  private String name;
  private int empNO;
  private int age;

and here's the beginning of the program Im importing it into:

package test;
import domain.*;

public class TestPerson {
     public static void main (String args[]) {

this is essentially the directory of the project:


问:
html2canvas not working at all
Here is the code which isn't working. Basically I'm allowing the user to edit some text in the div and then display its screenshot. Can someone please tell why is it not working?

<!doctype html>

  <link type="text/css" rel="stylesheet" href="main.css" />
  <title>Poster</title>

IT IS TOTALLY AWESOME

    <textarea id="user_input" placeholder="Your text here.." rows="2" cols="30" ></textarea>

      FONT-SIZE :
      <button id="decrease_size">-</button>
      <button id="increase_size">+</button>

    <input id="submit" type="submit" value="SUBMIT" />

```

答:
```Just use this code

<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelector('button').addEventListener('click', function() {
  html2canvas(document.querySelector('.specific'), {
    onrendered: function(canvas) {
      // document.body.appendChild(canvas);
      return Canvas2Image.saveAsPNG(canvas);
    }
  });
});</code>```

.btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
}
.btn-default {
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}
h1 {
  font-size: 36px;
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: inherit;
}
h1 small {
  font-size: 65%;
  font-weight: 400;
  line-height: 1;
  color: #777;
  display: block;
  padding-top: 15px;
}
.specific {
  background-color: #fff;
}
p a {
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://superal.github.io/canvas2image/canvas2image.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div class="specific">
  <h1>Click to Take a Screenshot & Download it! <small>using html2canvas.js + canvas2image.js</small></h1>
  <p>This is a simple demo.</p>
  <p>Use html2canvas.js to take a screenshot of a specific div and then use canvas2image.js to download the screenshot as an image locally to your filesystem.</p>
  <button type="button" class="btn btn-default">Take a Screenshot!</button>
  <p>References: html2canvas.jscanvas2image.js
  </p>
</div></code>```

```

Title: html2canvas not working at all

Body:
Just use this code

document.querySelector('button').addEventListener('click', function() {
  html2canvas(document.querySelector('.specific'), {
    onrendered: function(canvas) {
      // document.body.appendChild(canvas);
      return Canvas2Image.saveAsPNG(canvas);
    }
  });
});

.btn {
  display: inline-block;
  padding: 6px 12px;
  margin-bottom: 0;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.42857143;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  background-image: none;
  border: 1px solid transparent;
  border-radius: 4px;
}
.btn-default {
  color: #333;
  background-color: #fff;
  border-color: #ccc;
}
h1 {
  font-size: 36px;
  font-family: inherit;
  font-weight: 500;
  line-height: 1.1;
  color: inherit;
}
h1 small {
  font-size: 65%;
  font-weight: 400;
  line-height: 1;
  color: #777;
  display: block;
  padding-top: 15px;
}
.specific {
  background-color: #fff;
}
p a {
  padding: 5px;
}

<script src="https://superal.github.io/canvas2image/canvas2image.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<div class="specific">
  <h1>Click to Take a Screenshot & Download it! <small>using html2canvas.js + canvas2image.js</small></h1>
  <p>This is a simple demo.</p>
  <p>Use html2canvas.js to take a screenshot of a specific div and then use canvas2image.js to download the screenshot as an image locally to your filesystem.</p>
  <button type="button" class="btn btn-default">Take a Screenshot!</button>
  <p>References: <a href="http://html2canvas.hertzen.com/">html2canvas.js</a><a href="https://github.com/SuperAL/canvas2image">canvas2image.js</a>
  </p>
</div>