问:
Mysql Join AND SUM
Please look to this picture

http://i.stack.imgur.com/A2RB2.jpg

i want to get

sum of money in table come

sum of money in table leave

inner join  emp using id

Thats my query

```<code>SELECT uid,SUM(money) FROM come
INNER JOIN emp ON(come.uid = emp.id)
WHERE emp.statue=1
GROUP BY come.uid
UNION
SELECT uid,SUM(money) FROM `leave`
INNER JOIN emp ON ( leave.uid = emp.id )
GROUP BY leave.uid
</code>```

and the result was this image

http://i.stack.imgur.com/xZtO3.jpg

答:
here we go:</p>

```<code>SELECT q1.uid,SUM(q1.l),SUM(q1.c) FROM
(
SELECT uid,0 as l,SUM(money) as c FROM come
INNER JOIN emp ON (come.uid = emp.id)
WHERE emp.statue=1 GROUP BY come.uid
UNION ALL
SELECT uid,SUM(money) as l,0 as c FROM leave
INNER JOIN emp ON ( leave.uid = emp.id ) GROUP BY leave.uid
) q1
GROUP BY uid
</code>```

Title: Mysql Join AND SUM

Body:
Please look to this picture

http://i.stack.imgur.com/A2RB2.jpg

i want to get

sum of money in table come

sum of money in table leave

inner join  emp using id

Thats my query

SELECT uid,SUM(money) FROM come
INNER JOIN emp ON(come.uid = emp.id)
WHERE emp.statue=1
GROUP BY come.uid
UNION
SELECT uid,SUM(money) FROM `leave`
INNER JOIN emp ON ( leave.uid = emp.id )
GROUP BY leave.uid

and the result was this image

http://i.stack.imgur.com/xZtO3.jpg

Body:
here we go:

SELECT q1.uid,SUM(q1.l),SUM(q1.c) FROM
(
SELECT uid,0 as l,SUM(money) as c FROM come
INNER JOIN emp ON (come.uid = emp.id)
WHERE emp.statue=1 GROUP BY come.uid
UNION ALL
SELECT uid,SUM(money) as l,0 as c FROM leave
INNER JOIN emp ON ( leave.uid = emp.id ) GROUP BY leave.uid
) q1
GROUP BY uid


来源: stackexchange

问:
Can't scrape tile; Python dictionary returns 'None'
I am trying to scrape a job title from Indeed.com.

Here is my code:

```<code>import scrapy

class JobsNySpider(scrapy.Spider):
    name = 'jobs_ny'
    allowed_domains = ['www.indeed.com']
    start_urls = ['https://www.indeed.com/jobs?q=analyst&l=New%20York,%20NY&vjk=b588911bd50d7ab1']

    def parse(self, response):
       jobs = response.xpath("//td[@class='resultContent']")
       for job in jobs:
           yield {
            'title': job.xpath(".//h2[@class='jobTitle']/span/text()").get()
           }

       next_page=response.urljoin(response.xpath("//ul[@class='pagination-list']/li[position() = last()]/a/@href").get())

       if next_page:
           yield scrapy.Request(url=next_page, callback=self.parse)
</code>```

For some reason, Python dictionary returns {'title': None}.
I disabled JavaScript to make sure I am scraping HTML markup.

答:
Your xpath selector for the title is incorrect because you are using the selector @class='jobTitle' yet the h2 element has multiple classes on it so your selector will not find a matching element. Try using the contains function as shown below.

yield {
   'title': job.xpath(".//h2[contains(@class,'jobTitle')]/span/text()").get()
}
```
<p>Alternatively, ensure you capture all the classes on the element if you want to select using <code>@class=...</code>. This might be unstable since some classes might change from time to time. See below sample</p>
<pre class="lang-py prettyprint-override"><code>yield {
   'title': job.xpath(".//h2[@class='jobTitle jobTitle-color-purple']/span/text()").get()
}
</code>```

I recommend using the contains function with the class name that is common on all the elements you want to select.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to scrape a job title from Indeed.com.

Here is my code:

import scrapy

class JobsNySpider(scrapy.Spider):
    name = 'jobs_ny'
    allowed_domains = ['www.indeed.com']
    start_urls = ['https://www.indeed.com/jobs?q=analyst&l=New%20York,%20NY&vjk=b588911bd50d7ab1']

    def parse(self, response):
       jobs = response.xpath("//td[@class='resultContent']")
       for job in jobs:
           yield {
            'title': job.xpath(".//h2[@class='jobTitle']/span/text()").get()
           }

       next_page=response.urljoin(response.xpath("//ul[@class='pagination-list']/li[position() = last()]/a/@href").get())

       if next_page:
           yield scrapy.Request(url=next_page, callback=self.parse)

For some reason, Python dictionary returns {'title': None}.
I disabled JavaScript to make sure I am scraping HTML markup.

Body:
Your xpath selector for the title is incorrect because you are using the selector @class='jobTitle' yet the h2 element has multiple classes on it so your selector will not find a matching element. Try using the contains function as shown below.

yield {
   'title': job.xpath(".//h2[contains(@class,'jobTitle')]/span/text()").get()
}

Alternatively, ensure you capture all the classes on the element if you want to select using @class=.... This might be unstable since some classes might change from time to time. See below sample

yield {
   'title': job.xpath(".//h2[@class='jobTitle jobTitle-color-purple']/span/text()").get()
}

I recommend using the contains function with the class name that is common on all the elements you want to select.


问:
Linking 2 tkinter GUI with a main file
I'm trying to link 2 tkinter file in a main file, I'm relatively quite new for python
When i try to run my main file my tkinter window does not pop out.
if i run individually it will run page2 instead of page 1
what is wrong inside here ?

Here is my main file

```<code>import page1w,page2w
from tkinter import *

def main():
    page1_window=page1w
    page2_window=page2w
</code>```

Here is my page 1 tkinter file

```<code>from tkinter import *
import page2w
root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1:")
l2=Label(root, text="Label2:")
l3=Label(root,text="Label 3")

#Input from above
e1=Entry(root)
e2=Entry(root)
e3=Entry(root)

#submit button
s1=Button(root,text='Submit',command=page2w)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
e1.grid(row=0,column=1,pady=2)
e2.grid(row=1,column=1,pady=2)
e3.grid(row=2,column=1,pady=2)
s1.grid(row=3,column=3,pady=2)

mainloop()
</code>```

here is my page 2 file

```<code>from tkinter import *

root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1 ")
l2=Label(root, text="Label2 ")
l3=Label(root,text="Label3")

#Pass & Fail Button
l1b=Button(root,text="PASS")
l2b=Button(root,text="PASS")
l3b=Button(root,text="PASS")
l1bf=Button(root,text="FAIL")
l2bf=Button(root,text="FAIL")
l3bf=Button(root,text="FAIL")

#Next button
s1=Button(root,text='Next',)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
l1b.grid(row=0,column=4,sticky=E)
l2b.grid(row=1,column=4,sticky=E)
l3b.grid(row=2,column=4,sticky=E)
l1bf.grid(row=0,column=5,sticky=E)
l2bf.grid(row=1,column=5,sticky=E)
l3bf.grid(row=2,column=5,sticky=E)
s1.grid(row=3,column=3,pady=2)

mainloop()
</code>```

i'm using python3.xx
what is a suitable way to link all tkinter gui & run in sequence order
say : page1w then page2 etc,etc

答:
Your functions are running when you import them. You can test this by running

```<code>import page1w,page2w
from tkinter import *

# def main():
#     page1_window=page1w
#     page2_window=page2w
</code>```

as your main script. This is because you should be defining your code as functions or a class in the scripts you are importing. This gives:

page1w:

```<code>from tkinter import *
import page2w

def page1w(root):
    root.geometry("500x500")
    root.title("Some title")

    #Label
    l1=Label(root, text="Label1:")
    l2=Label(root, text="Label2:")
    l3=Label(root,text="Label 3")

    #Input from above
    e1=Entry(root)
    e2=Entry(root)
    e3=Entry(root)

    #submit button
    s1=Button(root,text='Submit',command=page2w)

    #Arrangement of label & input
    l1.grid(row=0,column=0,sticky=W,pady=2)
    l2.grid(row=1,column=0,sticky = W,pady=2)
    l3.grid(row=2,column=0,sticky=W , pady=2)
    e1.grid(row=0,column=1,pady=2)
    e2.grid(row=1,column=1,pady=2)
    e3.grid(row=2,column=1,pady=2)
    s1.grid(row=3,column=3,pady=2)

if __name__=="__main__":
    root=Tk()
    page1w(root)
    mainloop()
</code>```

page2w:

```<code>from tkinter import *

def page2w(root):
    root.geometry("500x500")
    root.title("Some title")

    #Label
    l1=Label(root, text="Label1 ")
    l2=Label(root, text="Label2 ")
    l3=Label(root,text="Label3")

    #Pass & Fail Button
    l1b=Button(root,text="PASS")
    l2b=Button(root,text="PASS")
    l3b=Button(root,text="PASS")
    l1bf=Button(root,text="FAIL")
    l2bf=Button(root,text="FAIL")
    l3bf=Button(root,text="FAIL")

    #Next button
    s1=Button(root,text='Next',)

    #Arrangement of label & input
    l1.grid(row=0,column=0,sticky=W,pady=2)
    l2.grid(row=1,column=0,sticky = W,pady=2)
    l3.grid(row=2,column=0,sticky=W , pady=2)
    l1b.grid(row=0,column=4,sticky=E)
    l2b.grid(row=1,column=4,sticky=E)
    l3b.grid(row=2,column=4,sticky=E)
    l1bf.grid(row=0,column=5,sticky=E)
    l2bf.grid(row=1,column=5,sticky=E)
    l3bf.grid(row=2,column=5,sticky=E)
    s1.grid(row=3,column=3,pady=2)

if __name__=="__main__":
    root=Tk()
    page2w(root)
    mainloop()
</code>```

However, your main file still won't run properly. This is because you need to create an instance of Tk() and pass it to both functions

```<code>from page1w import *
from page2w import *
from tkinter import *

def main(root):
    page1_window=page1w(root)
    page2_window=page2w(root)

root = Tk()
main(root)
root.mainloop()
</code>```

This will run both of your windows, but they will be on the same window, which (I think) is not your intention. We can get around this by creating a Toplevel() instance. You should not create a second Tk(); while it might work, it actually creates two tcl interpreters in the background and means that the two windows can't interact with each other.

```<code>from page1w import *
from page2w import *
from tkinter import *

def main(first_window, second_window):
    page1_window=page1w(first_window)
    page2_window=page2w(second_window)

root = Tk()
second_window = Toplevel(root)
main(root, second_window)
root.mainloop()
</code>```

Your code will now be running each of your imported files in a seperate window. Hopefully this is enough to help you for now, but I recommend following along some tutorials on tkinter

Title: Linking 2 tkinter GUI with a main file

Body:
I'm trying to link 2 tkinter file in a main file, I'm relatively quite new for python
When i try to run my main file my tkinter window does not pop out.
if i run individually it will run page2 instead of page 1
what is wrong inside here ?

Here is my main file

import page1w,page2w
from tkinter import *

def main():
    page1_window=page1w
    page2_window=page2w

Here is my page 1 tkinter file

from tkinter import *
import page2w
root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1:")
l2=Label(root, text="Label2:")
l3=Label(root,text="Label 3")

#Input from above
e1=Entry(root)
e2=Entry(root)
e3=Entry(root)

#submit button
s1=Button(root,text='Submit',command=page2w)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
e1.grid(row=0,column=1,pady=2)
e2.grid(row=1,column=1,pady=2)
e3.grid(row=2,column=1,pady=2)
s1.grid(row=3,column=3,pady=2)

mainloop()

here is my page 2 file

from tkinter import *

root=Tk()

root.geometry("500x500")
root.title("Some title")

#Label
l1=Label(root, text="Label1 ")
l2=Label(root, text="Label2 ")
l3=Label(root,text="Label3")

#Pass & Fail Button
l1b=Button(root,text="PASS")
l2b=Button(root,text="PASS")
l3b=Button(root,text="PASS")
l1bf=Button(root,text="FAIL")
l2bf=Button(root,text="FAIL")
l3bf=Button(root,text="FAIL")

#Next button
s1=Button(root,text='Next',)

#Arrangement of label & input
l1.grid(row=0,column=0,sticky=W,pady=2)
l2.grid(row=1,column=0,sticky = W,pady=2)
l3.grid(row=2,column=0,sticky=W , pady=2)
l1b.grid(row=0,column=4,sticky=E)
l2b.grid(row=1,column=4,sticky=E)
l3b.grid(row=2,column=4,sticky=E)
l1bf.grid(row=0,column=5,sticky=E)
l2bf.grid(row=1,column=5,sticky=E)
l3bf.grid(row=2,column=5,sticky=E)
s1.grid(row=3,column=3,pady=2)

mainloop()

i'm using python3.xx
what is a suitable way to link all tkinter gui & run in sequence order
say : page1w then page2 etc,etc

Body:
Your functions are running when you import them. You can test this by running

import page1w,page2w
from tkinter import *

# def main():
#     page1_window=page1w
#     page2_window=page2w

as your main script. This is because you should be defining your code as functions or a class in the scripts you are importing. This gives:

page1w:

from tkinter import *
import page2w

def page1w(root):
    root.geometry("500x500")
    root.title("Some title")

    #Label
    l1=Label(root, text="Label1:")
    l2=Label(root, text="Label2:")
    l3=Label(root,text="Label 3")

    #Input from above
    e1=Entry(root)
    e2=Entry(root)
    e3=Entry(root)

    #submit button
    s1=Button(root,text='Submit',command=page2w)

    #Arrangement of label & input
    l1.grid(row=0,column=0,sticky=W,pady=2)
    l2.grid(row=1,column=0,sticky = W,pady=2)
    l3.grid(row=2,column=0,sticky=W , pady=2)
    e1.grid(row=0,column=1,pady=2)
    e2.grid(row=1,column=1,pady=2)
    e3.grid(row=2,column=1,pady=2)
    s1.grid(row=3,column=3,pady=2)

if __name__=="__main__":
    root=Tk()
    page1w(root)
    mainloop()

page2w:

from tkinter import *

def page2w(root):
    root.geometry("500x500")
    root.title("Some title")

    #Label
    l1=Label(root, text="Label1 ")
    l2=Label(root, text="Label2 ")
    l3=Label(root,text="Label3")

    #Pass & Fail Button
    l1b=Button(root,text="PASS")
    l2b=Button(root,text="PASS")
    l3b=Button(root,text="PASS")
    l1bf=Button(root,text="FAIL")
    l2bf=Button(root,text="FAIL")
    l3bf=Button(root,text="FAIL")

    #Next button
    s1=Button(root,text='Next',)

    #Arrangement of label & input
    l1.grid(row=0,column=0,sticky=W,pady=2)
    l2.grid(row=1,column=0,sticky = W,pady=2)
    l3.grid(row=2,column=0,sticky=W , pady=2)
    l1b.grid(row=0,column=4,sticky=E)
    l2b.grid(row=1,column=4,sticky=E)
    l3b.grid(row=2,column=4,sticky=E)
    l1bf.grid(row=0,column=5,sticky=E)
    l2bf.grid(row=1,column=5,sticky=E)
    l3bf.grid(row=2,column=5,sticky=E)
    s1.grid(row=3,column=3,pady=2)

if __name__=="__main__":
    root=Tk()
    page2w(root)
    mainloop()

However, your main file still won't run properly. This is because you need to create an instance of Tk() and pass it to both functions

from page1w import *
from page2w import *
from tkinter import *

def main(root):
    page1_window=page1w(root)
    page2_window=page2w(root)

root = Tk()
main(root)
root.mainloop()

This will run both of your windows, but they will be on the same window, which (I think) is not your intention. We can get around this by creating a Toplevel() instance. You should not create a second Tk(); while it might work, it actually creates two tcl interpreters in the background and means that the two windows can't interact with each other.

from page1w import *
from page2w import *
from tkinter import *

def main(first_window, second_window):
    page1_window=page1w(first_window)
    page2_window=page2w(second_window)

root = Tk()
second_window = Toplevel(root)
main(root, second_window)
root.mainloop()

Your code will now be running each of your imported files in a seperate window. Hopefully this is enough to help you for now, but I recommend following along some tutorials on tkinter


问:
Is there a faster way to extract lines from a file?
I have a set of files that I need to search through and extract certain lines.  Right now, I'm using a for loop but this is proving costly in terms of time.  Is there a faster way than the below?

```<code>import re

for file in files:
        localfile = open(file, 'r')
        for line in localfile:
                if re.search("Common English Words", line):
                      words = line.split("|")[0]
                      # Append words to file words.txt
                      open("words.txt","a+").write(words + "\n")
</code>```

答:
Well for one thing, you are creating a new file descriptor every time that you write to the words.txt file.
I ran some tests and found that python garbage collection does in fact close open file descriptors when they become inaccessible (at least in my test case).
However, creating a file descriptor every time that you want to append to a file is going to be costly. For future reference, it is considered good practice to use with as blocks for opening files.

TLDR:
One improvement you could make is to open the file you are writing to just once.
Here is what that would look like:

```<code>import re

with open("words.txt","a+") as words_file:
    for file in files:
            localfile = open(file, 'r')
                for line in localfile:
                        if re.search("Common English Words", line):
                              words = line.split("|")[0]
                              # Append words to file words.txt
                              words_file.write(words + "\n")
</code>```

Like I said, using with as statements when opening files is considered best practice. We can fully implement this best practice like so:

```<code>import re

with open("words.txt","a+") as words_file:
    for file in files:
            with open(file, 'r') as localfile:
                for line in localfile:
                        if re.search("Common English Words", line):
                              words = line.split("|")[0]
                              # Append words to file words.txt
                              words_file.write(words + "\n")
</code>```

Body:
I have a set of files that I need to search through and extract certain lines.  Right now, I'm using a for loop but this is proving costly in terms of time.  Is there a faster way than the below?

import re

for file in files:
        localfile = open(file, 'r')
        for line in localfile:
                if re.search("Common English Words", line):
                      words = line.split("|")[0]
                      # Append words to file words.txt
                      open("words.txt","a+").write(words + "\n")

Body:
Well for one thing, you are creating a new file descriptor every time that you write to the words.txt file.
I ran some tests and found that python garbage collection does in fact close open file descriptors when they become inaccessible (at least in my test case).
However, creating a file descriptor every time that you want to append to a file is going to be costly. For future reference, it is considered good practice to use with as blocks for opening files.

TLDR:
One improvement you could make is to open the file you are writing to just once.
Here is what that would look like:

import re

with open("words.txt","a+") as words_file:
    for file in files:
            localfile = open(file, 'r')
                for line in localfile:
                        if re.search("Common English Words", line):
                              words = line.split("|")[0]
                              # Append words to file words.txt
                              words_file.write(words + "\n")

Like I said, using with as statements when opening files is considered best practice. We can fully implement this best practice like so:

import re

with open("words.txt","a+") as words_file:
    for file in files:
            with open(file, 'r') as localfile:
                for line in localfile:
                        if re.search("Common English Words", line):
                              words = line.split("|")[0]
                              # Append words to file words.txt
                              words_file.write(words + "\n")


问:
Use Custom DNS resolver for any request in NodeJS
I'm looking to find a way to use a custom DNS resolver for a nodejs request using node-fetch. I think there is a star of explaining here : Node override request IP resolution but I can't manage to make it work for any request. My goal is to use an alternative DNS resolver, such as cloudflare (1.1.1.1) or Google public DNS (8.8.8.8) instead the OS / ISP default DNS resolution.

import http from "http";
import https from "https";
import fetch from "node-fetch";

const staticLookup = (ip: string, v?: number) => (hostname: string, _: null, cb: Function) => {
  cb(null, ip, v || 4);
};

const staticDnsAgent = (scheme: "http" | "https", ip: string) => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup(ip), rejectUnauthorized: false });
};

// Both request are not working
fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https", "1.1.1.1")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http", "8.8.8.8")
})

```

I'm struggling a bit to find a way to make this example work, I'm pretty sure I have to use the nodejs DNS module and set a custom server.

答:
Thanks to Martheen who answered in my first post I was able to achieve the result here :</p>
```<code>import http from "http";
import https from "https";
import dns from "dns/promises";
import fetch from "node-fetch";

// Cloud flare dns
dns.setServers([
  "1.1.1.1",
  "[2606:4700:4700::1111]",
]);

const staticLookup = () => async (hostname: string, _: null, cb: Function) => {
  const ips = await dns.resolve(hostname);

  if (ips.length === 0) {
    throw new Error(`Unable to resolve ${hostname}`);
  }

  cb(null, ips[0], 4);
};

const staticDnsAgent = (scheme: "http" | "https") => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup() });
};

fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http")
})

</code>```

Body:
I'm looking to find a way to use a custom DNS resolver for a nodejs request using node-fetch. I think there is a star of explaining here : Node override request IP resolution but I can't manage to make it work for any request. My goal is to use an alternative DNS resolver, such as cloudflare (1.1.1.1) or Google public DNS (8.8.8.8) instead the OS / ISP default DNS resolution.

import http from "http";
import https from "https";
import fetch from "node-fetch";

const staticLookup = (ip: string, v?: number) => (hostname: string, _: null, cb: Function) => {
  cb(null, ip, v || 4);
};

const staticDnsAgent = (scheme: "http" | "https", ip: string) => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup(ip), rejectUnauthorized: false });
};

// Both request are not working
fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https", "1.1.1.1")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http", "8.8.8.8")
})

I'm struggling a bit to find a way to make this example work, I'm pretty sure I have to use the nodejs DNS module and set a custom server.

Body:
Thanks to Martheen who answered in my first post I was able to achieve the result here :

import http from "http";
import https from "https";
import dns from "dns/promises";
import fetch from "node-fetch";

// Cloud flare dns
dns.setServers([
  "1.1.1.1",
  "[2606:4700:4700::1111]",
]);

const staticLookup = () => async (hostname: string, _: null, cb: Function) => {
  const ips = await dns.resolve(hostname);

  if (ips.length === 0) {
    throw new Error(`Unable to resolve ${hostname}`);
  }

  cb(null, ips[0], 4);
};

const staticDnsAgent = (scheme: "http" | "https") => {
  const httpModule = scheme === "http" ? http : https;
  return new httpModule.Agent({ lookup: staticLookup() });
};

fetch(`https://api.github.com/search/issues?q=Hello%20World`, {
  agent: staticDnsAgent("https")
})

fetch(`http://jsonplaceholder.typicode.com/todos`, {
  agent: staticDnsAgent("http")
})


问:
firebase database - adding the current server-side timestamp as a key
using firebase functions (NODE) I would like to create a timestamp base node to save my data using timestamp as key name:

EX:

```<code>WATERLEVEL
    16934723478:1
    16934723482:2
    16934723483:50
</code>```

I'm trying to using this code without success.

```<code>    const timest = admin.database.ServerValue.TIMESTAMP ;

    let waterData = {};
    waterData[timest] = req.body.WATERLEVEL;

    rtdb.child("SENSOR").child(req.body.SERIAL).child("LEVEL").update(waterData);
</code>```

Can somebody drive me to the right approach ?  could a variable been used as key ?

答:
The admin.database.ServerValue.TIMESTAMP variable is not actually a timestamp, but an instruction to the database to write the current timestamp. There is no way in the Firebase Realtime Database to write this value into a key; it can only be used in values.

If you want to write the current server-side timestamp from Cloud Functions as a key, use:

```<code>const timest = Date.now();
</code>```

Body:
using firebase functions (NODE) I would like to create a timestamp base node to save my data using timestamp as key name:

EX:

WATERLEVEL
    16934723478:1
    16934723482:2
    16934723483:50

I'm trying to using this code without success.

    const timest = admin.database.ServerValue.TIMESTAMP ;

    let waterData = {};
    waterData[timest] = req.body.WATERLEVEL;

    rtdb.child("SENSOR").child(req.body.SERIAL).child("LEVEL").update(waterData);

Can somebody drive me to the right approach ?  could a variable been used as key ?

Body:
The admin.database.ServerValue.TIMESTAMP variable is not actually a timestamp, but an instruction to the database to write the current timestamp. There is no way in the Firebase Realtime Database to write this value into a key; it can only be used in values.

If you want to write the current server-side timestamp from Cloud Functions as a key, use:

const timest = Date.now();


问:
Trying to add a JavaFX shape from another class and create it in my main class. The Class cannot be converted to node
I'm very new to Java. I've been using it for the last two months. The end goal of my code is to try and create a shape and add it to the window without having to set all the properties of the shape in the main "view" class.

When I attempt to add my work in progress Castle class, Intellij is telling me I need to provide a node instead. Below I will provide the class where I'm setting the properties of the shape and the main class where I get halted trying to add it to my window.

```<code>public class Castle {
    private int width = 1280; // width of the window
    private int height = 720; // height of the window
    private double x, y, size;
    private int denizens;
    private Color color;
    private String name;
    private Random rn = new Random();

    // constructor
    Castle() {
        x = 50;
        y = 50;
        size = 10;
        color = Color.GRAY;
        name = "Anthony's Castle";
        denizens = rn.nextInt();
    }
    // GraphicsContext method
    protected void draw(GraphicsContext gc) {
        Rectangle rec = new Rectangle(x, y);
        rec.setX(100);
        rec.setY(100);
        rec.setWidth(100);
        rec.setHeight(100);
        rec.setFill(Color.RED);
    }
    // get methods
    public int getDenizens() {
        return denizens;
    }
    public double getSize() {
        return size;
    }
}
</code>```
```<code>public class TwoDomains extends Application {
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 1280, 720, Color.BEIGE);

        Castle castle = new Castle();

        root.getChildren().add(castle);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Village");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}
</code>```

答:
Maybe you want:</p>
```<code>public class Castle extends Group {
    private int width = 1280; // width of the window - does EACH castle need a separate copy of this info?
    private int height = 720; // height of the window
    private double x, y, size;
    private int denizens;
    private Color color;
    private String name;
    private Random rn = new Random();  // This probably should be static, or somewhere else.

    // constructor
    Castle() {
        x = 50;
        y = 50;
        size = 10;
        color = Color.GRAY;
        name = "Anthony's Castle";
        denizens = rn.nextInt();
        makeShape();
    }

    protected void makeShape() {
        Rectangle rec = new Rectangle(x, y);
        rec.setX(100);
        rec.setY(100);
        rec.setWidth(100);
        rec.setHeight(100);
        rec.setFill(Color.RED);
        getChildren().add(rec);
    }
    // get methods
    public int getDenizens() {
        return denizens;
    }
    public double getSize() {
        return size;
    }
}
</code>```

Body:
I'm very new to Java. I've been using it for the last two months. The end goal of my code is to try and create a shape and add it to the window without having to set all the properties of the shape in the main "view" class.

When I attempt to add my work in progress Castle class, Intellij is telling me I need to provide a node instead. Below I will provide the class where I'm setting the properties of the shape and the main class where I get halted trying to add it to my window.

public class Castle {
    private int width = 1280; // width of the window
    private int height = 720; // height of the window
    private double x, y, size;
    private int denizens;
    private Color color;
    private String name;
    private Random rn = new Random();

    // constructor
    Castle() {
        x = 50;
        y = 50;
        size = 10;
        color = Color.GRAY;
        name = "Anthony's Castle";
        denizens = rn.nextInt();
    }
    // GraphicsContext method
    protected void draw(GraphicsContext gc) {
        Rectangle rec = new Rectangle(x, y);
        rec.setX(100);
        rec.setY(100);
        rec.setWidth(100);
        rec.setHeight(100);
        rec.setFill(Color.RED);
    }
    // get methods
    public int getDenizens() {
        return denizens;
    }
    public double getSize() {
        return size;
    }
}

public class TwoDomains extends Application {
    public void start(Stage primaryStage) {
        Group root = new Group();
        Scene scene = new Scene(root, 1280, 720, Color.BEIGE);

        Castle castle = new Castle();

        root.getChildren().add(castle);
        primaryStage.setScene(scene);
        primaryStage.setTitle("Village");
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Body:
Maybe you want:

public class Castle extends Group {
    private int width = 1280; // width of the window - does EACH castle need a separate copy of this info?
    private int height = 720; // height of the window
    private double x, y, size;
    private int denizens;
    private Color color;
    private String name;
    private Random rn = new Random();  // This probably should be static, or somewhere else.

    // constructor
    Castle() {
        x = 50;
        y = 50;
        size = 10;
        color = Color.GRAY;
        name = "Anthony's Castle";
        denizens = rn.nextInt();
        makeShape();
    }

    protected void makeShape() {
        Rectangle rec = new Rectangle(x, y);
        rec.setX(100);
        rec.setY(100);
        rec.setWidth(100);
        rec.setHeight(100);
        rec.setFill(Color.RED);
        getChildren().add(rec);
    }
    // get methods
    public int getDenizens() {
        return denizens;
    }
    public double getSize() {
        return size;
    }
}


问:
Mock function call inside other function
How to mock a function call inside another function in JavaScript?

Code example:

returnNumber.js

```<code>export default function returnNumber() {
  return 5;
}
</code>```

myFunction.js

```<code>import returnNumber from "./returnNumber";

export default function myFunction(input) {
  return input + returnNumber();
}
</code>```

I would like to test it by doing something like this, but none if the code examples I saw seem to be working in my case

myFunction.test.js

```<code>import myFunction from "./myFunction";

test("myFunction should equal 6", async () => {
  returnNumber = () => {
    return 1
  }

  expect(myFunction(5)).toEqual(6);
});
</code>```

Considering the example above; can I test myFunction while overriding returnNumber's return value without changing the code of returnNumber.js / myFunction.js?

答:
i think you usually use jest to mock the return value of the function like so:

```<code>import myFunctionService from './myFunctionService';

test('myFunction', async () => {
jest.spyOn(myFunctionService, 'returnNumber').mockReturnValue(1);
const result = myFunction(5);

expect(result).toBe(6);
}
</code>```

class should be something like this:

```<code>export default class myFunctionService {
    constructor() {}

    myFunction(input) {
      return input + returnNumber();
    }
}
</code>```

Body:
How to mock a function call inside another function in JavaScript?

Code example:

returnNumber.js

export default function returnNumber() {
  return 5;
}

myFunction.js

import returnNumber from "./returnNumber";

export default function myFunction(input) {
  return input + returnNumber();
}

I would like to test it by doing something like this, but none if the code examples I saw seem to be working in my case

myFunction.test.js

import myFunction from "./myFunction";

test("myFunction should equal 6", async () => {
  returnNumber = () => {
    return 1
  }

  expect(myFunction(5)).toEqual(6);
});

Considering the example above; can I test myFunction while overriding returnNumber's return value without changing the code of returnNumber.js / myFunction.js?

Body:
i think you usually use jest to mock the return value of the function like so:

import myFunctionService from './myFunctionService';

test('myFunction', async () => {
jest.spyOn(myFunctionService, 'returnNumber').mockReturnValue(1);
const result = myFunction(5);

expect(result).toBe(6);
}

class should be something like this:

export default class myFunctionService {
    constructor() {}

    myFunction(input) {
      return input + returnNumber();
    }
}


问:
cannot find symbol DaggerAppComponent, Cause: java.lang.ExceptionInInitializerError
I was trying to build my Dagger2 based Android project in Android studio Arctic fox 2020.3.1 with Mac M1 and I got the error,

error: cannot find symbol
import xxxx.com.xxxx.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent

which also was showing

Cause: java.lang.ExceptionInInitializerError

The same project was working in another machine(not mac).

Also I am unable to see the compiler error toggle button in android studio build output.

Please help me to resolve this.

complete build output,

Executing tasks: [:app:assembleDebug] in project /projects/Android/prototype

Task :app:preBuild UP-TO-DATE
Task :app:preDebugBuild UP-TO-DATE
Task :app:compileDebugAidl NO-SOURCE
Task :app:compileDebugRenderscript NO-SOURCE
Task :app:dataBindingMergeDependencyArtifactsDebug UP-TO-DATE
Task :app:dataBindingMergeGenClassesDebug UP-TO-DATE
Task :app:generateDebugResValues UP-TO-DATE
Task :app:generateDebugResources UP-TO-DATE
Task :app:injectCrashlyticsMappingFileIdDebug UP-TO-DATE
Task :app:processDebugGoogleServices UP-TO-DATE
Task :app:mergeDebugResources UP-TO-DATE
Task :app:dataBindingGenBaseClassesDebug UP-TO-DATE
Task :app:dataBindingTriggerDebug UP-TO-DATE
Task :app:generateDebugBuildConfig UP-TO-DATE
Task :app:javaPreCompileDebug UP-TO-DATE
Task :app:checkDebugAarMetadata UP-TO-DATE
Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
Task :app:extractDeepLinksDebug UP-TO-DATE
Task :app:processDebugMainManifest UP-TO-DATE
Task :app:processDebugManifest UP-TO-DATE
Task :app:processDebugManifestForPackage UP-TO-DATE
Task :app:processDebugResources UP-TO-DATE

Task :app:compileDebugJavaWithJavac FAILED
The following annotation processors are not incremental: dagger-android-processor-2.16.jar (com.google.dagger:dagger-android-processor:2.16), dagger-compiler-2.16.jar (com.google.dagger:dagger-compiler:2.16).
Make sure all annotation processors are incremental to improve your build speed.
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/provision/PairingActivity.java:22: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/provision/ProvisionActivity.java:41: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/splash/SplashActivity.java:20: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/appliance/AddApplianceActivity.java:15: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/appliance/event/AddEventActivity.java:8: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
/Users/sysadmin/Documents/projects/esp32/energy-monitor/Android/prototype/app/src/main/java/prototype/com/myapp/ui/welcome/WelcomeActivity.java:10: error: cannot find symbol
import prototype.com.myapp.di.DaggerAppComponent;
^
symbol:   class DaggerAppComponent
location: package prototype.com.myapp.di
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
6 errors

Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
Task :app:mergeDebugShaders UP-TO-DATE
Task :app:compileDebugShaders NO-SOURCE
Task :app:generateDebugAssets UP-TO-DATE
Task :app:mergeDebugAssets UP-TO-DATE
Task :app:compressDebugAssets UP-TO-DATE
Task :app:processDebugJavaRes NO-SOURCE
Task :app:checkDebugDuplicateClasses UP-TO-DATE
Task :app:desugarDebugFileDependencies UP-TO-DATE
Task :app:mergeExtDexDebug UP-TO-DATE
Task :app:mergeLibDexDebug UP-TO-DATE
Task :app:mergeDebugJniLibFolders UP-TO-DATE
Task :app:mergeDebugNativeLibs NO-SOURCE
Task :app:stripDebugDebugSymbols NO-SOURCE
Task :app:validateSigningDebug UP-TO-DATE
Task :app:writeDebugAppMetadata UP-TO-DATE
Task :app:writeDebugSigningConfigVersions UP-TO-DATE

FAILURE: Build failed with an exception.

What went wrong:
Execution failed for task ':app:compileDebugJavaWithJavac'.

java.lang.ExceptionInInitializerError

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/7.0.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 1s
29 actionable tasks: 1 executed, 28 up-to-date

答: I'd love to comment but I have not enough reputation, anyway, are you using room in your project? I had the same issue also only on my Mac M1, it was caused by the room version, I updated it to 2.4.0-alpha03 and it builds fine since then. if not, you may want to check the version of the libraries you are using, but yeah only on Mac M1, hope it helps.</p>


问:
Getting error while creating react project Aborting installation errno: -4094, code: 'UNKNOWN', syscall: 'spawn'
Getting the following error when creating react app</p>
```<code>E:\React>create-react-app ecomerce

Creating a new React app in E:\React\ecomerce.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Aborting installation.
Unexpected error. Please report it as a bug:
Error: spawn UNKNOWN
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at Object.spawn (node:child_process:698:9)
    at spawn (C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\node_modules\cross-spawn\index.js:12:24)
    at C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:390:19
    at new Promise (<anonymous>)
    at install (C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:341:10)
    at C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:468:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  errno: -4094,
  code: 'UNKNOWN',
  syscall: 'spawn'
}

Deleting generated file... package.json
Deleting ecomerce/ from E:\React
Done.
</code>```

答: I'm using windows 10, at that time I installed panda antivirus, after that my visual studio code became very slow, and the error occurred. I have done several ways but there is no change. then I tried to uninstall the antivirus. And finally the error is no longer, and my pc is not slow anymore.</p>

Body:
Getting the following error when creating react app

E:\React>create-react-app ecomerce

Creating a new React app in E:\React\ecomerce.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Aborting installation.
Unexpected error. Please report it as a bug:
Error: spawn UNKNOWN
    at ChildProcess.spawn (node:internal/child_process:412:11)
    at Object.spawn (node:child_process:698:9)
    at spawn (C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\node_modules\cross-spawn\index.js:12:24)
    at C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:390:19
    at new Promise (<anonymous>)
    at install (C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:341:10)
    at C:\Users\reeba\AppData\Roaming\npm\node_modules\create-react-app\createReactApp.js:468:16
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  errno: -4094,
  code: 'UNKNOWN',
  syscall: 'spawn'
}

Deleting generated file... package.json
Deleting ecomerce/ from E:\React
Done.


问:
npm install error with node-gyp\node_modules\@tootallnate
this error happens to me when I want to do the npm install and it is canceled in the middle of the process, It should be noted that this did not happen before.

I already applied many of the suggestions I saw, for example: disable the anti virus, run as administrator, among others.

version node :10.13.0 and 10.16.0 (nvm)
version angular :8.0.0

error console PowerShell

my dependencies project

```<code>  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular-material-components/datetime-picker": "^2.0.3",
    "@angular-material-components/moment-adapter": "^2.0.1",
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/fire": "^5.2.3",
    "@angular/flex-layout": "^7.0.0-beta.23",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.2.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.2",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/platform-server": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@auth0/angular-jwt": "^2.1.0",
    "@ng-bootstrap/ng-bootstrap": "^4.0.1",
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0",
    "@swimlane/ngx-datatable": "^15.0.0",
    "@tinymce/tinymce-angular": "^3.5.0",
    "@types/lodash": "^4.14.106",
    "@types/pdfjs-dist": "~2.0.1",
    "amazing-time-picker": "^1.8.0",
    "angular-calendar": "^0.27.19",
    "angularfire2": "^5.1.1",
    "animate.css": "^3.7.0",
    "card": "^2.4.0",
    "chart.js": "^2.8.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.2",
    "css-element-queries": "^1.1.1",
    "date-fns": "^1.30.1",
    "easy-pie-chart": "^2.1.7",
    "file-saver": "^2.0.2",
    "firebase": "^5.8.0",
    "font-awesome": "4.7.0",
    "hammerjs": "^2.0.8",
    "intl": "^1.2.5",
    "jquery": "^3.3.1",
    "moment": "^2.23.0",
    "ng-block-ui": "^2.1.0",
    "ng-circle-progress": "^1.5.1",
    "ng-currency-format": "^0.1.6",
    "ng2-charts": "^1.6.0",
    "ng2-currency-mask": "^5.3.1",
    "ng2-pdf-viewer": "~5.3.4",
    "ng2-validation": "^4.2.0",
    "ng2modules-easypiechart": "0.0.4",
    "ng5-breadcrumb": "0.0.6",
    "ngx-device-detector": "1.4.2",
    "ngx-mat-select-search": "^1.7.6",
    "ngx-perfect-scrollbar": "^7.2.0",
    "ngx-slick-carousel": "^0.4.4",
    "ngx-spinner": "^7.1.0",
    "ngx-toastr": "^9.1.1",
    "ngx-tour-core": "4.1.1",
    "ngx-tour-md-menu": "4.1.1",
    "ngx-tour-ng-bootstrap": "^4.0.1",
    "ngx-webcam": "^0.2.5",
    "node-sass": "^4.14.1",
    "normalize.css": "^8.0.1",
    "pdfjs-dist": "2.5.207",
    "perfect-scrollbar": "^1.4.0",
    "promise-polyfill": "^8.1.0",
    "rxjs": "^6.3.3",
    "rxjs-compat": "^6.3.3",
    "screenfull": "^4.0.0",
    "slick-carousel": "^1.8.1",
    "sortablejs": "^1.8.1",
    "sweetalert2": "^8.19.0",
    "ts-helpers": "^1.1.2",
    "videogular2": "^6.4.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@types/jasmine": "^3.3.7",
    "@types/jquery": "^3.3.29",
    "@types/node": "^10.12.18",
    "@types/systemjs": "^0.20.6",
    "@types/webpack-env": "^1.13.7",
    "codelyzer": "^4.5.0",
    "gulp-sass": "^5.0.0",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.0.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "node-sass-magic-importer": "^5.3.2",
    "protractor": "^5.4.2",
    "rxjs-tslint": "^0.1.6",
    "ts-node": "^7.0.1",
    "tslint": "^5.12.1",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^4.5.0"
  }
</code>```

答:
Application Usage

The error might be coming up as it is already in use by another program (without you realising about it, meaning it is running in the background).

To fix this issue, you need to find out which process(es) is/are using the folder. There are multiple methods to do this, and there is a discussion about this here.

You can use the Resource Monitor on Windows 7, 8, 10 and 11, or you can also use PowerShell. There is also an application made by Microsoft in the Sysinternals suite called Process Explorer.

Once you've found the process which is using the folder, you can kill the task. Warning! Do not kill the program if you are unsure of what it is, as it could be a core system file, and ending it may result in irregular behaviour, crashes, and more.

Once you've done that, and the process has been successfully ended, you can run the following command again.

```<code>npm install
</code>```

Hopefully, then, the command should run successfully when the install script changes the folder!

Permission Lack

To fix a permission lack, you need to run the script as an administrator. To do this, run the script in an Administrator Command Prompt or Administrator PowerShell window.

Then, inside of it, run the following command.

```<code>npm install
</code>```

If that doesn't work, you may have to change the permissions of the folder. You can see the instructions here.

Body:
this error happens to me when I want to do the npm install and it is canceled in the middle of the process, It should be noted that this did not happen before.

I already applied many of the suggestions I saw, for example: disable the anti virus, run as administrator, among others.

version node :10.13.0 and 10.16.0 (nvm)
version angular :8.0.0

error console PowerShell

my dependencies project

  "dependencies": {
    "@agm/core": "^1.0.0-beta.5",
    "@angular-material-components/datetime-picker": "^2.0.3",
    "@angular-material-components/moment-adapter": "^2.0.1",
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/fire": "^5.2.3",
    "@angular/flex-layout": "^7.0.0-beta.23",
    "@angular/forms": "^8.0.0",
    "@angular/http": "^7.2.1",
    "@angular/material": "^8.0.0",
    "@angular/material-moment-adapter": "^8.0.2",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/platform-server": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@auth0/angular-jwt": "^2.1.0",
    "@ng-bootstrap/ng-bootstrap": "^4.0.1",
    "@ngx-translate/core": "^11.0.1",
    "@ngx-translate/http-loader": "^4.0.0",
    "@swimlane/ngx-datatable": "^15.0.0",
    "@tinymce/tinymce-angular": "^3.5.0",
    "@types/lodash": "^4.14.106",
    "@types/pdfjs-dist": "~2.0.1",
    "amazing-time-picker": "^1.8.0",
    "angular-calendar": "^0.27.19",
    "angularfire2": "^5.1.1",
    "animate.css": "^3.7.0",
    "card": "^2.4.0",
    "chart.js": "^2.8.0",
    "classlist.js": "^1.1.20150312",
    "core-js": "^2.6.2",
    "css-element-queries": "^1.1.1",
    "date-fns": "^1.30.1",
    "easy-pie-chart": "^2.1.7",
    "file-saver": "^2.0.2",
    "firebase": "^5.8.0",
    "font-awesome": "4.7.0",
    "hammerjs": "^2.0.8",
    "intl": "^1.2.5",
    "jquery": "^3.3.1",
    "moment": "^2.23.0",
    "ng-block-ui": "^2.1.0",
    "ng-circle-progress": "^1.5.1",
    "ng-currency-format": "^0.1.6",
    "ng2-charts": "^1.6.0",
    "ng2-currency-mask": "^5.3.1",
    "ng2-pdf-viewer": "~5.3.4",
    "ng2-validation": "^4.2.0",
    "ng2modules-easypiechart": "0.0.4",
    "ng5-breadcrumb": "0.0.6",
    "ngx-device-detector": "1.4.2",
    "ngx-mat-select-search": "^1.7.6",
    "ngx-perfect-scrollbar": "^7.2.0",
    "ngx-slick-carousel": "^0.4.4",
    "ngx-spinner": "^7.1.0",
    "ngx-toastr": "^9.1.1",
    "ngx-tour-core": "4.1.1",
    "ngx-tour-md-menu": "4.1.1",
    "ngx-tour-ng-bootstrap": "^4.0.1",
    "ngx-webcam": "^0.2.5",
    "node-sass": "^4.14.1",
    "normalize.css": "^8.0.1",
    "pdfjs-dist": "2.5.207",
    "perfect-scrollbar": "^1.4.0",
    "promise-polyfill": "^8.1.0",
    "rxjs": "^6.3.3",
    "rxjs-compat": "^6.3.3",
    "screenfull": "^4.0.0",
    "slick-carousel": "^1.8.1",
    "sortablejs": "^1.8.1",
    "sweetalert2": "^8.19.0",
    "ts-helpers": "^1.1.2",
    "videogular2": "^6.4.0",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@types/jasmine": "^3.3.7",
    "@types/jquery": "^3.3.29",
    "@types/node": "^10.12.18",
    "@types/systemjs": "^0.20.6",
    "@types/webpack-env": "^1.13.7",
    "codelyzer": "^4.5.0",
    "gulp-sass": "^5.0.0",
    "jasmine-core": "^3.3.0",
    "jasmine-spec-reporter": "^4.2.1",
    "karma": "^4.0.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-cli": "^2.0.0",
    "karma-coverage-istanbul-reporter": "^2.0.4",
    "karma-jasmine": "^2.0.1",
    "karma-jasmine-html-reporter": "^1.4.0",
    "karma-phantomjs-launcher": "^1.0.4",
    "node-sass-magic-importer": "^5.3.2",
    "protractor": "^5.4.2",
    "rxjs-tslint": "^0.1.6",
    "ts-node": "^7.0.1",
    "tslint": "^5.12.1",
    "typescript": "3.4.5",
    "webpack-bundle-analyzer": "^4.5.0"
  }

Body:
Application Usage

The error might be coming up as it is already in use by another program (without you realising about it, meaning it is running in the background).

To fix this issue, you need to find out which process(es) is/are using the folder. There are multiple methods to do this, and there is a discussion about this here.

You can use the Resource Monitor on Windows 7, 8, 10 and 11, or you can also use PowerShell. There is also an application made by Microsoft in the Sysinternals suite called Process Explorer.

Once you've found the process which is using the folder, you can kill the task. Warning! Do not kill the program if you are unsure of what it is, as it could be a core system file, and ending it may result in irregular behaviour, crashes, and more.

Once you've done that, and the process has been successfully ended, you can run the following command again.

npm install

Hopefully, then, the command should run successfully when the install script changes the folder!

Permission Lack

To fix a permission lack, you need to run the script as an administrator. To do this, run the script in an Administrator Command Prompt or Administrator PowerShell window.

Then, inside of it, run the following command.

npm install

If that doesn't work, you may have to change the permissions of the folder. You can see the instructions here.


问:
postgres combining two queries from the result between them
I Have two postgres query.
This is the first query

```<code>SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22';
</code>```

with result

```<code>quantity |    origin     | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02317 |   6528
25.00 | SNL/OUT/02306 |   6774
150.00 | SNL/OUT/02337 |   6774
</code>```

And the second query is

```<code>SELECT spo.product_qty, spo.lot_id
FROM stock_pack_operation spo
LEFT JOIN stock_picking sp ON sp.id=spo.picking_id
WHERE sp.origin='PO/2021/1/2307';
</code>```

with the result of second query:

```<code>product_qty | lot_id
-------------+--------
  200.00 |   6774
  200.00 |   6852
</code>```

The question is what is the query to have result like this

```<code>quantity |    origin     | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02306 |   6774
150.00 | SNL/OUT/02337 |   6774
</code>```

Thank you for the help

答:
Finally, I got the answer. It use IN</p>
```<code>SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22'
AND spo.lot_id IN
(SELECT spo2.lot_id
FROM stock_pack_operation spo2
LEFT JOIN stock_picking sp2 ON sp2.id=spo2.picking_id
WHERE sp2.origin='PO/2021/1/2307');
</code>```

Body:
I Have two postgres query.
This is the first query

SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22';

with result

quantity |    origin     | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02317 |   6528
25.00 | SNL/OUT/02306 |   6774
150.00 | SNL/OUT/02337 |   6774

And the second query is

SELECT spo.product_qty, spo.lot_id
FROM stock_pack_operation spo
LEFT JOIN stock_picking sp ON sp.id=spo.picking_id
WHERE sp.origin='PO/2021/1/2307';

with the result of second query:

product_qty | lot_id
-------------+--------
  200.00 |   6774
  200.00 |   6852

The question is what is the query to have result like this

quantity |    origin     | lot_id
----------+---------------+--------
25.00 | SNL/OUT/02306 |   6774
150.00 | SNL/OUT/02337 |   6774

Thank you for the help

Body:
Finally, I got the answer. It use IN

SELECT line.quantity, inv.origin, spo.lot_id
FROM account_invoice inv
INNER JOIN account_invoice_line line on inv.id=line.invoice_id
LEFT JOIN stock_picking pick on inv.origin=pick.name
LEFT JOIN stock_pack_operation spo ON pick.id=spo.picking_id
WHERE line.product_id=4988
AND pick.min_date between '2021-02-20' and '2021-03-22'
AND spo.lot_id IN
(SELECT spo2.lot_id
FROM stock_pack_operation spo2
LEFT JOIN stock_picking sp2 ON sp2.id=spo2.picking_id
WHERE sp2.origin='PO/2021/1/2307');


答:
You can only add Nodes to the scene graph, and your Castle class is not a node.

Your draw() method looks strange. It creates a Rectangle (which is a Node), but doesn't do anything with it. It also takes a GraphicsContext2D as a parameter, which looks like you're going to draw on a canvas, but you don't have a canvas.

You just need to organize the code so that, one way or another, your Castle class provides some kind of Node.

One way is to refactor your draw method as

```<code>public Node draw() {
    Rectangle rec = new Rectangle(x, y);
    rec.setX(100);
    rec.setY(100);
    rec.setWidth(100);
    rec.setHeight(100);
    rec.setFill(Color.RED);
    return rec ;
}
</code>```

and then replace

```<code>    root.getChildren().add(castle);
</code>```

with

```<code>    root.getChildren().add(castle.draw());
</code>```

Note that with this setup, each time you call draw() on a single Castle instance will create a new Node, which may or may not be what you want, but it is a very simple task to refactor it if it's not what you want.

Title: Trying to add a JavaFX shape from another class and create it in my main class. The Class cannot be converted to node

Body:
You can only add Nodes to the scene graph, and your Castle class is not a node.

Your draw() method looks strange. It creates a Rectangle (which is a Node), but doesn't do anything with it. It also takes a GraphicsContext2D as a parameter, which looks like you're going to draw on a canvas, but you don't have a canvas.

You just need to organize the code so that, one way or another, your Castle class provides some kind of Node.

One way is to refactor your draw method as

public Node draw() {
    Rectangle rec = new Rectangle(x, y);
    rec.setX(100);
    rec.setY(100);
    rec.setWidth(100);
    rec.setHeight(100);
    rec.setFill(Color.RED);
    return rec ;
}

and then replace

    root.getChildren().add(castle);

with

    root.getChildren().add(castle.draw());

Note that with this setup, each time you call draw() on a single Castle instance will create a new Node, which may or may not be what you want, but it is a very simple task to refactor it if it's not what you want.


问:
How to remove cache after logout in asp.net core
When you click on browser back button, it brings page from cache not from server, But user will not be able to perform any action on page displayed after back button. So I want to to remove that pages in cache how can I achieve this asp.net core?</p>

答:
Add the below mentioned attribute to the action methods in .net core.
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]

ContentLicense: CC BY-SA 3.0


问:
Downloading file from S3 bucket - AWS Oracle RDS
I'm new to Oracle AWS RDS, we have a RDS deployed and an S3 bucket. The download from S3 works fine, however I wanted to write a script which checks if the file download has been completed.

```<code>DECLARE
V_TASKID VARCHAR2(100);
V_CTR integer := 0;
V_CMD VARCHAR2(4000) := NULL;

BEGIN
SELECT rdsadmin.rdsadmin_s3_tasks.download_from_s3(p_bucket_name => 'humm-cards-dev',  p_directory_name => 'DATA_PUMP_DIR') INTO V_TASKID FROM DUAL;
dbms_output.put_line( V_TASKID ) ;

WHILE V_CTR = 0 LOOP
    dbms_output.put_line(V_CMD);
    V_CMD := 'SELECT count(*) FROM table(rdsadmin.rds_file_util.read_text_file(''BDUMP'', ''dbtask-' || V_TASKID || '.log'')) WHERE text LIKE ''%finished successfully%''';
    dbms_output.put_line(V_CMD);
    execute immediate V_CMD INTO V_CTR;
    IF V_CTR > 0 THEN EXIT; END IF;
END LOOP;
END;
/
</code>```

The script kicks off the download - I get the TaskID and the V_CMD output in the DBMS Output.
However the script fails on

```<code>execute immediate V_CMD INTO V_CTR
</code>```

with this error

ORA-06512: at "RDSADMIN.RDS_FILE_UTIL", line 90 ORA-06512: at line 14
29283. 00000 -  "invalid file operation%s"
*Cause:    An attempt was made to read from a file or directory that does
not exist, or file or directory access was denied by the
operating system.
*Action:   Verify file and directory access privileges on the file system,
and if reading, verify that the file exists.

Interesting thing is, that if I run the DBMS output of V_CMD separately, it works just fine. DBMS output is below.

```<code>SELECT count(*) FROM table(rdsadmin.rds_file_util.read_text_file('BDUMP', 'dbtask-1636692191529-641.log')) WHERE text LIKE '%finished successfully%';
</code>```

Does anyone have any idea what I'm doing wrong?

答:
Not sure if your issue was resolved, but I faced same problem and I think I found the reason for this. Once you download from s3 bucket, you need to wait till the file download is complete. What happens with your code (And my old code too), was that the file download operation was started, but not completed and hence I believe the log is still not available when you immediately try to read it.

What I did was after the download operation, put a while loop to find if the log file dbtask-taskid.log exists in the BDUMP directory.

```<code>v_logfilename:='dbtask-'|| taskid ||'.log';

v_logs_created:=0;

WHILE v_logs_created<1)
    LOOP
        Select Count(1)
        INTO v_logs_created
        FROM TABLE(rdsadmin.rds_file_util.listdir(p_directory=>'BDUMP')) where filename=logfilename;
    END LOOP;
</code>```

Once it was, I would proceed to the next step that is read if there is a success message in that.

Body:
I'm new to Oracle AWS RDS, we have a RDS deployed and an S3 bucket. The download from S3 works fine, however I wanted to write a script which checks if the file download has been completed.

DECLARE
V_TASKID VARCHAR2(100);
V_CTR integer := 0;
V_CMD VARCHAR2(4000) := NULL;

BEGIN
SELECT rdsadmin.rdsadmin_s3_tasks.download_from_s3(p_bucket_name => 'humm-cards-dev',  p_directory_name => 'DATA_PUMP_DIR') INTO V_TASKID FROM DUAL;
dbms_output.put_line( V_TASKID ) ;

WHILE V_CTR = 0 LOOP
    dbms_output.put_line(V_CMD);
    V_CMD := 'SELECT count(*) FROM table(rdsadmin.rds_file_util.read_text_file(''BDUMP'', ''dbtask-' || V_TASKID || '.log'')) WHERE text LIKE ''%finished successfully%''';
    dbms_output.put_line(V_CMD);
    execute immediate V_CMD INTO V_CTR;
    IF V_CTR > 0 THEN EXIT; END IF;
END LOOP;
END;
/

The script kicks off the download - I get the TaskID and the V_CMD output in the DBMS Output.
However the script fails on

execute immediate V_CMD INTO V_CTR

with this error

ORA-06512: at "RDSADMIN.RDS_FILE_UTIL", line 90 ORA-06512: at line 14
29283. 00000 -  "invalid file operation%s"
*Cause:    An attempt was made to read from a file or directory that does
not exist, or file or directory access was denied by the
operating system.
*Action:   Verify file and directory access privileges on the file system,
and if reading, verify that the file exists.

Interesting thing is, that if I run the DBMS output of V_CMD separately, it works just fine. DBMS output is below.

SELECT count(*) FROM table(rdsadmin.rds_file_util.read_text_file('BDUMP', 'dbtask-1636692191529-641.log')) WHERE text LIKE '%finished successfully%';

Does anyone have any idea what I'm doing wrong?

Body:
Not sure if your issue was resolved, but I faced same problem and I think I found the reason for this. Once you download from s3 bucket, you need to wait till the file download is complete. What happens with your code (And my old code too), was that the file download operation was started, but not completed and hence I believe the log is still not available when you immediately try to read it.

What I did was after the download operation, put a while loop to find if the log file dbtask-taskid.log exists in the BDUMP directory.

v_logfilename:='dbtask-'|| taskid ||'.log';

v_logs_created:=0;

WHILE v_logs_created<1)
    LOOP
        Select Count(1)
        INTO v_logs_created
        FROM TABLE(rdsadmin.rds_file_util.listdir(p_directory=>'BDUMP')) where filename=logfilename;
    END LOOP;

Once it was, I would proceed to the next step that is read if there is a success message in that.


问:
Replace null values from a select command in jq with the value of another field
Goal is to search for null values of part_description and insert in part field value.

```<code>[
  {
    "part": "brake-01982",
    "part_description": null,
  }
]
</code>```

Expected Output

```<code>[
  {
    "part": "brake-01982",
    "part_description": "brake-01982",
  }
]
</code>```

Command:
jq '(.[] | select(.part_description==null).part_description) |= .part'

Results in no change

What does work is if I try to insert a string value. The double quoted string results in what I would expect. Demo below. How do I pass another fields value into this command vs a quoted string?

Command: jq '(.[] | select(.part_description==null).part_description) |= "test"'

Demo

Output

```<code>[
  {
    "part": "brake-01982",
    "part_description": "test"
  }
]
</code>```

答:
The alternative operator // retains the first value, unless it is null, false, or empty (i.e. missing), in which case it takes on the second. Combined with the update operator |=, this can be contracted to //=.

jq '.[] |= (.part_description //= .part)'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "part": "brake-01982",
    "part_description": "brake-01982"
  }
]
</code>```

Demo

Edit: To strictly update only in the case of null, i.e. to keep a value of false, and to not create the field if it's missing, the filter needs to check explicity for null:

jq '.[] |= ((select(has("part_description")).part_description | select(. == null)) = .part)'
```
<pre class="lang-json prettyprint-override"><code>[
  {
    "part": "brake-01982",
    "part_description": "brake-01982"
  }
]
</code>```

Demo

Body:
Goal is to search for null values of part_description and insert in part field value.

[
  {
    "part": "brake-01982",
    "part_description": null,
  }
]

Expected Output

[
  {
    "part": "brake-01982",
    "part_description": "brake-01982",
  }
]

Command:
jq '(.[] | select(.part_description==null).part_description) |= .part'

Results in no change

What does work is if I try to insert a string value. The double quoted string results in what I would expect. Demo below. How do I pass another fields value into this command vs a quoted string?

Command: jq '(.[] | select(.part_description==null).part_description) |= "test"'

Demo

Output

[
  {
    "part": "brake-01982",
    "part_description": "test"
  }
]

Body:
The alternative operator // retains the first value, unless it is null, false, or empty (i.e. missing), in which case it takes on the second. Combined with the update operator |=, this can be contracted to //=.

jq '.[] |= (.part_description //= .part)'

[
  {
    "part": "brake-01982",
    "part_description": "brake-01982"
  }
]

Demo

Edit: To strictly update only in the case of null, i.e. to keep a value of false, and to not create the field if it's missing, the filter needs to check explicity for null:

jq '.[] |= ((select(has("part_description")).part_description | select(. == null)) = .part)'

[
  {
    "part": "brake-01982",
    "part_description": "brake-01982"
  }
]

Demo


问:
Unable to create call adapter for class example.Simple
I am using retrofit 2.0.0-beta1 with SimpleXml. I want the retrieve a Simple (XML) resource from a REST service.
Marshalling/Unmarshalling the Simple object with SimpleXML works fine.

When using this code (converted form pre 2.0.0 code):

```<code>final Retrofit rest = new Retrofit.Builder()
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .baseUrl(endpoint)
    .build();
SimpleService service = rest.create(SimpleService.class);
LOG.info(service.getSimple("572642"));
</code>```

Service:

```<code>public interface SimpleService {

    @GET("/simple/{id}")
    Simple getSimple(@Path("id") String id);

}
</code>```

I get this exception:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.Simple
    for method SimpleService.getSimple
    at retrofit.Utils.methodError(Utils.java:201)
    at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:51)
    at retrofit.MethodHandler.create(MethodHandler.java:30)
    at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)
    at retrofit.Retrofit$1.invoke(Retrofit.java:127)
    at com.sun.proxy.$Proxy0.getSimple(Unknown Source)
</code>```

What am i missing? I know that wrapping the return type by a Call works. But I want the service to return business objects as type (and working in sync mode).

UPDATE

After added the extra dependancies and .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) as suggested by different answers, I still get this error:

```<code>Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class simple.Simple. Tried:
 * retrofit.RxJavaCallAdapterFactory
 * retrofit.DefaultCallAdapter$1
</code>```

答:
For this case :

```<code>val apiService = RetrofitFactory.makeRetrofitService()

CoroutineScope(Dispatchers.IO).launch {

    val response = apiService.myGetRequest()

    // process response...

}

interface ApiService {

   @GET("/my-get-request")
   suspend fun myGetRequest(): Response<String>
}
</code>```

All methods used within  suspend functions must be marked as suspend because of it's manageability by the Corountine. Check more info here.

So if you dont mark your API service function as suspend when you call it inside a CoroutineScope or any suspend marked method, android app crashes and throws the Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.class error.

Body:
I am using retrofit 2.0.0-beta1 with SimpleXml. I want the retrieve a Simple (XML) resource from a REST service.
Marshalling/Unmarshalling the Simple object with SimpleXML works fine.

When using this code (converted form pre 2.0.0 code):

final Retrofit rest = new Retrofit.Builder()
    .addConverterFactory(SimpleXmlConverterFactory.create())
    .baseUrl(endpoint)
    .build();
SimpleService service = rest.create(SimpleService.class);
LOG.info(service.getSimple("572642"));

Service:

public interface SimpleService {

    @GET("/simple/{id}")
    Simple getSimple(@Path("id") String id);

}

I get this exception:

Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.Simple
    for method SimpleService.getSimple
    at retrofit.Utils.methodError(Utils.java:201)
    at retrofit.MethodHandler.createCallAdapter(MethodHandler.java:51)
    at retrofit.MethodHandler.create(MethodHandler.java:30)
    at retrofit.Retrofit.loadMethodHandler(Retrofit.java:138)
    at retrofit.Retrofit$1.invoke(Retrofit.java:127)
    at com.sun.proxy.$Proxy0.getSimple(Unknown Source)

What am i missing? I know that wrapping the return type by a Call works. But I want the service to return business objects as type (and working in sync mode).

UPDATE

After added the extra dependancies and .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) as suggested by different answers, I still get this error:

Caused by: java.lang.IllegalArgumentException: Could not locate call adapter for class simple.Simple. Tried:
 * retrofit.RxJavaCallAdapterFactory
 * retrofit.DefaultCallAdapter$1

Body:
For this case :

val apiService = RetrofitFactory.makeRetrofitService()

CoroutineScope(Dispatchers.IO).launch {

    val response = apiService.myGetRequest()

    // process response...

}

interface ApiService {

   @GET("/my-get-request")
   suspend fun myGetRequest(): Response<String>
}

All methods used within  suspend functions must be marked as suspend because of it's manageability by the Corountine. Check more info here.

So if you dont mark your API service function as suspend when you call it inside a CoroutineScope or any suspend marked method, android app crashes and throws the Exception in thread "main" java.lang.IllegalArgumentException: Unable to create call adapter for class example.class error.


问:
How to retrieve a random value from an array that has values separate by a new line
I am a complete newbie at JS and currently using it in a testing capacity along with the Karate framework to perform some UI testing. I am having the following problem:

There is a dropdown that has the following HTML:

<select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
<option value="4">Honda</option>
<option value="5">Toyota</option>
<option value="6">VW</option>
</select>
```
<p>I used the following Karate method to get all text values under the dropdown:</p>
```def grabValues = scriptAll('#CarId', '_.textContent')
```
<p>Once printed, the array look like this:</p>
<pre class="lang-js prettyprint-override"><code>[
  "Mercedes\nBMW\nLexus\nHonda\nToyota\nVW\n"
]

console.log(Math.floor(Math.random() * (grabValues.length-1)))
</code>```

When printed, it keeps giving me 0.0. I am assuming this is because the array contains new lines vs comma delimitated? If so, how can I get rid of the new lines and replace with commas?

答:
One line code is console.log(myArr[0].split('\n'))

OR

Let's assume : The array of String is stored in myArr

```<code>let myArr = ["ABC\nDEF\nGHI\nJKL\nMNO\nPQR\nSTU\nVWX\nYZA\n"]
</code>```

To get the string from the array

```<code>let stringOfArr = myArr[0]
</code>```

Storing the new array from the stringOfArr deleminated by '\n' in newArray

```<code>let newArray = stringOfArr.split('\n')

console.log(newArray)
</code>```

Body:
I am a complete newbie at JS and currently using it in a testing capacity along with the Karate framework to perform some UI testing. I am having the following problem:

There is a dropdown that has the following HTML:

<select class=id="CarId" name="CarId" aria-describedby="CarId-error" aria-invalid="false" xpath="1">
<option value="1">Mercedes</option>
<option value="2">BMW</option>
<option value="3">Lexus</option>
<option value="4">Honda</option>
<option value="5">Toyota</option>
<option value="6">VW</option>
</select>

I used the following Karate method to get all text values under the dropdown:

def grabValues = scriptAll('#CarId', '_.textContent')

Once printed, the array look like this:

[
  "Mercedes\nBMW\nLexus\nHonda\nToyota\nVW\n"
]

console.log(Math.floor(Math.random() * (grabValues.length-1)))

When printed, it keeps giving me 0.0. I am assuming this is because the array contains new lines vs comma delimitated? If so, how can I get rid of the new lines and replace with commas?

Body:
One line code is console.log(myArr[0].split('\n'))

OR

Let's assume : The array of String is stored in myArr

let myArr = ["ABC\nDEF\nGHI\nJKL\nMNO\nPQR\nSTU\nVWX\nYZA\n"]

To get the string from the array

let stringOfArr = myArr[0]

Storing the new array from the stringOfArr deleminated by '\n' in newArray

let newArray = stringOfArr.split('\n')

console.log(newArray)


问:
Parsing XML file with duplicate tags
I currently use an XML parser to extract the name of a route from a GPX (XML) file.

Each GPX files contains a single "name" tag which is what I've been extracting.

Here's the script:

#! /bin/bash

gpxpath=/mnt/gpxfiles; export gpxpath

for file in $gpxpath/*
do

filename=`ls $file`; export filenanme
gpxname=`$scripts/xmlparse.pl "$file"`

echo $filename "    "$gpxname >> gpxparse.tmp

done

sort -k 2,2 gpxparse.tmp > gpxparse.out

cat gpxparse.out
```
<p>And here's xmlparse.pl:</p>
```#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new(
    twig_handlers => {
        'name' => sub { print $_ ->text }
    }
    )->parse( <> );
```
<p>Here's an example GPX file:</p>
```<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="creator" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <metadata>
        <referrer>Referrer</referrer>
        <time>2019-06-17T06:02:23.000Z</time>
    </metadata>
    <trk>
        <name>Another GPX file</name>
        <trkseg>
            <trkpt lon="-1.91990" lat="53.00131">
                <ele>112.1</ele>
                <time>2019-06-17T06:02:23.000Z</time>
            </trkpt>
            <trkpt lon="-1.91966" lat="53.00126">
                <ele>113.6</ele>
                <time>2019-06-17T06:02:25.000Z</time>
            </trkpt>
            <trkpt lon="-1.91962" lat="53.00125">
                <ele>114.1</ele>
                <time>2019-06-17T06:02:25.000Z</time>
            </trkpt>
            <trkpt lon="-1.91945" lat="53.00120">
                <ele>115.5</ele>
                <time>2019-06-17T06:02:26.000Z</time>
            </trkpt>
        </trkseg>
    </trk>
</gpx>
```

I can successfully extract the name of the route using the scripts above However, I'd additionally like to extract the first co-ordinate pair in each file.

Atrack can defined by a "trk" element and within a track can be multiple segments or "trkseg".  Finally, within a trkseg are multiple "trkpt" (track points).

A track point usually consists of a latitdue and longitude co-ordinate pair along with elevation and timestamp information.

I'm only looking to extract the first lat and lon within the first trkpt of the GPX file.  Ideally, once the script has found the first co-ordinate pair it should exit and move onto the next file.

I've tried crafting an additional perl script

I've added an additional perl parse script using XML::Twig but it seems to stumble when there are multiple elements with duplicate names.

答:
I see some more elegant methods in other answers, but I'd probably use a brute force method:

```<code>grep name {file} | head -1
grep "trkpt lon" {file} | head -1
</code>```

and then use perl or sed to edit the result to the parts wanted.

Title: Parsing XML file with duplicate tags

Body:
I currently use an XML parser to extract the name of a route from a GPX (XML) file.

Each GPX files contains a single "name" tag which is what I've been extracting.

Here's the script:

#! /bin/bash

gpxpath=/mnt/gpxfiles; export gpxpath

for file in $gpxpath/*
do

filename=`ls $file`; export filenanme
gpxname=`$scripts/xmlparse.pl "$file"`

echo $filename "    "$gpxname >> gpxparse.tmp

done

sort -k 2,2 gpxparse.tmp > gpxparse.out

cat gpxparse.out

And here's xmlparse.pl:

#!/usr/bin/perl

use strict;
use warnings;

use XML::Twig;

XML::Twig->new(
    twig_handlers => {
        'name' => sub { print $_ ->text }
    }
    )->parse( <> );

Here's an example GPX file:

<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="creator" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <metadata>
        <referrer>Referrer</referrer>
        <time>2019-06-17T06:02:23.000Z</time>
    </metadata>
    <trk>
        <name>Another GPX file</name>
        <trkseg>
            <trkpt lon="-1.91990" lat="53.00131">
                <ele>112.1</ele>
                <time>2019-06-17T06:02:23.000Z</time>
            </trkpt>
            <trkpt lon="-1.91966" lat="53.00126">
                <ele>113.6</ele>
                <time>2019-06-17T06:02:25.000Z</time>
            </trkpt>
            <trkpt lon="-1.91962" lat="53.00125">
                <ele>114.1</ele>
                <time>2019-06-17T06:02:25.000Z</time>
            </trkpt>
            <trkpt lon="-1.91945" lat="53.00120">
                <ele>115.5</ele>
                <time>2019-06-17T06:02:26.000Z</time>
            </trkpt>
        </trkseg>
    </trk>
</gpx>

I can successfully extract the name of the route using the scripts above However, I'd additionally like to extract the first co-ordinate pair in each file.

Atrack can defined by a "trk" element and within a track can be multiple segments or "trkseg".  Finally, within a trkseg are multiple "trkpt" (track points).

A track point usually consists of a latitdue and longitude co-ordinate pair along with elevation and timestamp information.

I'm only looking to extract the first lat and lon within the first trkpt of the GPX file.  Ideally, once the script has found the first co-ordinate pair it should exit and move onto the next file.

I've tried crafting an additional perl script

I've added an additional perl parse script using XML::Twig but it seems to stumble when there are multiple elements with duplicate names.

Body:
I see some more elegant methods in other answers, but I'd probably use a brute force method:

grep name {file} | head -1
grep "trkpt lon" {file} | head -1

and then use perl or sed to edit the result to the parts wanted.


问:
How does one implement an Iterator for a an Object that has generic types?
So I have an object called DetailedResponse<T>. Now I want to use this for an API where I can pass some data into it. Let's say this is the implementation for DetailedResponse

#[derive(serde::Deserialize, serde::Serialize)]
pub struct DetailedResponse<T> {
    pub data: Option<T>,
    pub success: bool,
    pub message: String,
}

impl<T> DetailedResponse<T> {
    pub fn new() -> DetailedResponse<T> {
        DetailedResponse {
            data: None,
            success: false,
            message: "".to_string(),
        }
    }
}
```
<p>And now in the API I want to use actix::Json to map some data lests say: <code>DetailedResponse<Vec<i16>></code> and I want to implement the response in code like this:</p>
<pre class="lang-rust prettyprint-override"><code>let response = DetailedResponse<Vec<i16>>::new();
// Do something
response.map(Json)
</code>```

I know I need to implement an Iterator trait for detailed response but I haven't seen good examples for what I want to accomplish. What I am imagining is that I will need to do something like this:

pub struct DetailedResponseIter<T> {
    // stuck here
}

impl<'a, T> DetailedResponseIter<T> {
    type Item = DetailedResponse<T>

    // Also Stuck here.
}
```

Thank you for your help and I will edit any more needed information.

答:
Try something like this:

impl<T> Iterator for /*...*/ {
    type Item = /*...*/;

    fn next(&mut self) -> Option<Self::Item> {
        // ...
    }
}
```

See https://doc.rust-lang.org/std/iter/index.html#implementing-iterator, https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods, and https://doc.rust-lang.org/reference/items/implementations.html#generic-implementations.

P.S. What is your iterator intended to do?

Body:
So I have an object called DetailedResponse<T>. Now I want to use this for an API where I can pass some data into it. Let's say this is the implementation for DetailedResponse

#[derive(serde::Deserialize, serde::Serialize)]
pub struct DetailedResponse<T> {
    pub data: Option<T>,
    pub success: bool,
    pub message: String,
}

impl<T> DetailedResponse<T> {
    pub fn new() -> DetailedResponse<T> {
        DetailedResponse {
            data: None,
            success: false,
            message: "".to_string(),
        }
    }
}

And now in the API I want to use actix::Json to map some data lests say: DetailedResponse<Vec<i16>> and I want to implement the response in code like this:

let response = DetailedResponse<Vec<i16>>::new();
// Do something
response.map(Json)

I know I need to implement an Iterator trait for detailed response but I haven't seen good examples for what I want to accomplish. What I am imagining is that I will need to do something like this:

pub struct DetailedResponseIter<T> {
    // stuck here
}

impl<'a, T> DetailedResponseIter<T> {
    type Item = DetailedResponse<T>

    // Also Stuck here.
}

Thank you for your help and I will edit any more needed information.

Body:
Try something like this:

impl<T> Iterator for /*...*/ {
    type Item = /*...*/;

    fn next(&mut self) -> Option<Self::Item> {
        // ...
    }
}

See https://doc.rust-lang.org/std/iter/index.html#implementing-iterator, https://doc.rust-lang.org/book/ch10-02-traits.html#using-trait-bounds-to-conditionally-implement-methods, and https://doc.rust-lang.org/reference/items/implementations.html#generic-implementations.

P.S. What is your iterator intended to do?


问:
Adding constructor to third party class/struct definition
A third party library has structs defined as

```<code>typedef struct _Example
{
  int member;
} Example;
</code>```

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

答:
```<code>Why not struct Example { ... } ?
</code>```

struct Example {...}; is the way how you should define a struct in C++, while the typedef form is old C-style.

```<code>functions and constructors shouldn't change the underlying byte layout of the
class/struct
</code>```

That depends. Functions are stored separated with your data in text section. So adding a normal function won't affect the size and layout of your struct. However, if there is any virtual functions, a "hidden" VPTR will be added in your class. Thus the layout could be very different from that w/o virtual functions.

```<code>Is it safe to just change my version of the 3rd party header file by adding a
constructor to the struct definition? Or alternatively, to just copy that definition
to my own code base, rename it, add a constructor, and reinterpret_cast to it?
</code>```

I strongly recommend you not to copy the definition. That's a very bad idea, especially when that is 3rd-party class out of your control. What if they change its definition one day? There are several ways that you can handle it. E.g., either use aggregation or inheritance. Actually, in this case I think the use of aggregation excels.

```<code>// The layout of this struct is the same as
// that of struct Example
struct MyExample
{
   Example m_ex;
   MyExample(int member)
   {
      m_ex.member = member;
   }
   //..
};
</code>```

Body:
A third party library has structs defined as

typedef struct _Example
{
  int member;
} Example;

As a side question, just out of interest, why that definition? Why not struct Example { ... }?

Anyhow, I want to serialize the information with boost::serialization, and for that need a constructor. Is it safe to just change my version of the 3rd party header file by adding a constructor to the struct definition? Or alternatively, to just copy that definition to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I assume it would be because as I understand functions and constructors shouldn't change the underlying byte layout of the class/struct, is this correct?

Thanks

Body:
Why not struct Example { ... } ?

struct Example {...}; is the way how you should define a struct in C++, while the typedef form is old C-style.

functions and constructors shouldn't change the underlying byte layout of the
class/struct

That depends. Functions are stored separated with your data in text section. So adding a normal function won't affect the size and layout of your struct. However, if there is any virtual functions, a "hidden" VPTR will be added in your class. Thus the layout could be very different from that w/o virtual functions.

Is it safe to just change my version of the 3rd party header file by adding a
constructor to the struct definition? Or alternatively, to just copy that definition
to my own code base, rename it, add a constructor, and reinterpret_cast to it?

I strongly recommend you not to copy the definition. That's a very bad idea, especially when that is 3rd-party class out of your control. What if they change its definition one day? There are several ways that you can handle it. E.g., either use aggregation or inheritance. Actually, in this case I think the use of aggregation excels.

// The layout of this struct is the same as
// that of struct Example
struct MyExample
{
   Example m_ex;
   MyExample(int member)
   {
      m_ex.member = member;
   }
   //..
};


问:
Why does extracting a specific git tag to a /tmp directory mess up the working tree?
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

```<code>mkdir /tmp/lastRelease
</code>```

and extracted the last release in that directory

```<code>git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .
</code>```

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

答:
What you wanted to do was either

```<code>git archive v2.1 | tar Cx /path/to/tmp/tree
</code>```

or

```<code>git worktree add /path/to/tmp/tree v2.1
</code>```

or

```<code>git clone -sb v2.3 . /path/to/tmp/tree
</code>```

or even

```<code>scratch=`mktemp -d`
GIT_INDEX_FILE=$PWD/.git/scratch-index git --work-tree=$scratch read-tree -um v2.1
</code>```

because as @torek points out git checkout is a convenience command, built for "standard" workflows where your work trees are for content you're actively tracking; the index is Git's manifest for what you last checked out or added there, and HEAD is its ancestor commit.

Body:
Because I wanted to look at the files in the last release, tagged v2.1, to run it in isolation from my working directory, I created a tmp directory

mkdir /tmp/lastRelease

and extracted the last release in that directory

git --work-tree=/tmp/lastRelease checkout tags/v2.1 -- .

The files are indeed extracted just fine to /tmp/lastRelease.

But now when I run git status in the working directory I find that very many files (all the files modified since tag v2.1?) appear as staged for commit, and another long list of files (that are in HEAD) appears as not staged for commit.

Was this last command the right way to extract a specific tag? How do I reset to HEAD? (The obvious git checkout HEAD doesn't modify what git status says, even though the files are there.)

Body:
What you wanted to do was either

git archive v2.1 | tar Cx /path/to/tmp/tree

or

git worktree add /path/to/tmp/tree v2.1

or

git clone -sb v2.3 . /path/to/tmp/tree

or even

scratch=`mktemp -d`
GIT_INDEX_FILE=$PWD/.git/scratch-index git --work-tree=$scratch read-tree -um v2.1

because as @torek points out git checkout is a convenience command, built for "standard" workflows where your work trees are for content you're actively tracking; the index is Git's manifest for what you last checked out or added there, and HEAD is its ancestor commit.


问:
servlet can't get option value from jsp
I'm doing a java web application using jsp and servlets.
I have a form and I retrieve different values from my db to populate an option. This is my form:

```<code>    <form class="form" action ="<%=request.getContextPath()%>/aggiungiLibro" method ="post">
    <div class="form__group">
        <input type="text" placeholder="Titolo" class="form__input" name = "titolo"/>
    </div>

    <div class="form__group">
        <input type="text" placeholder="Quantità disponibile" class="form__input" name="quantita" />
    </div>

    <div class="form__group">
    <select class="form__input" name="autore">
        <c:forEach items="${listaAutori}" var = "autore" >
            <option value="${autore.idAutore}"><c:out value="${autore.nome} ${autore.cognome}" /></option>
        </c:forEach>
        </select>
    </div>
        <button class="btn btn-light" type="submit">Inserisci nuovo libro</button>
    </form>
</code>```

In the servlet I retrive my data with

```<code>String titolo = request.getParameter("titolo");
int quantita = Integer.parseInt(request.getParameter("quantita"));
int autore = Integer.parseInt(request.getParameter("autore"));
</code>```

I get right values for 'titolo' and 'quantita' but I get the string '${autore.nome}' for 'autore'.
It seems like it doesn't replace the string with the actual value.
The field idAutore is spelt right.
(In the jsp page I see the correct values for ${autore.nome} ${autore.cognome})

Anyone can help me please? What I'm doing wrong?

答:
I solved replacing this:

```<code><option value="${autore.idAutore}">
</code>```

with this:

```<code><option value="<c:out value='${autore.idAutore}' />">
</code>```

Title: servlet can't get option value from jsp

Body:
I'm doing a java web application using jsp and servlets.
I have a form and I retrieve different values from my db to populate an option. This is my form:

    <form class="form" action ="<%=request.getContextPath()%>/aggiungiLibro" method ="post">

        <input type="text" placeholder="Titolo" class="form__input" name = "titolo"/>

        <input type="text" placeholder="Quantità disponibile" class="form__input" name="quantita" />

    <select class="form__input" name="autore">
        <c:forEach items="${listaAutori}" var = "autore" >
            <option value="${autore.idAutore}"><c:out value="${autore.nome} ${autore.cognome}" /></option>
        </c:forEach>
        </select>

        <button class="btn btn-light" type="submit">Inserisci nuovo libro</button>
    </form>

In the servlet I retrive my data with

String titolo = request.getParameter("titolo");
int quantita = Integer.parseInt(request.getParameter("quantita"));
int autore = Integer.parseInt(request.getParameter("autore"));

I get right values for 'titolo' and 'quantita' but I get the string '${autore.nome}' for 'autore'.
It seems like it doesn't replace the string with the actual value.
The field idAutore is spelt right.
(In the jsp page I see the correct values for ${autore.nome} ${autore.cognome})

Anyone can help me please? What I'm doing wrong?

Body:
I solved replacing this:

<option value="${autore.idAutore}">

with this:

<option value="<c:out value='${autore.idAutore}' />">