问:
Tkinter - How to close one window whilst opening another window in Tkinter - Python 3
I am extremely new to Tkinter and must use this for my programming coursework, i am looking for help to understand how to I destroy/hide the LoginWindow when the SuccessfulLogin window is opened. Bear in mind that i am new to tkinter. Thank you.

```<code>import tkinter
from tkinter import ttk
</code>```

-----------------------------------------------------------------------------------------------------------------------

```<code>class loginWindow():

def __init__(self, master): #constructor

    self.master = master
    self.master.title("Main Menu") #window title
    self.master.geometry("400x400") #window size
    self.master.configure(background = "#fff1d0") #window colour, hexadecimal codes

    #self.photo = PhotoImage(file = "filename.png") #sets up image
    #self.photoLabel = Label(self.master, image = self.photo, bg = "red") #puts image on label
    #self.photoLabel.place(x=350 y=600) #places onto the screen with specified coordinates

    self.enterLabel = tkinter.Label(self.master, text = "Launcher", font = ("Helvetica", 16), bg = "#fff1d0")
    self.enterLabel.pack(pady = 10)

    self.emptySpace = tkinter.Label(self.master, text = " ", bg = "#fff1d0")
    self.emptySpace.pack(pady = 10)

    self.username = tkinter.Label(self.master, text = "Username:", bg = "#fff1d0") #Label widget and properties
    self.username.pack()
    self.enterUser = tkinter.ttk.Entry(self.master, width = 40) #Creates text entry widget
    self.enterUser.pack()

    self.password = tkinter.Label(self.master, text = "Password:", bg = "#fff1d0") #Label widget and properties
    self.password.pack()
    self.enterPass = tkinter.ttk.Entry(self.master, width = 40, show = "*") #Creates text entry widget
    self.enterPass.pack()

    self.loginButton = tkinter.ttk.Button(self.master, width = 40, text = "Login", command = self.loginAccess)
    self.loginButton.pack(pady = 10)

def loginAccess(self):

    username = "Aaron" #Needs to become a dictionary or database  or something with all usernames and passwords
    password = "Password"
    global userUsername
    userUsername = self.enterUser.get()
    userPassword = self.enterPass.get()

    if userUsername != username and userPassword != password:

         self.enterLabel.configure(text = "Invalid username and password. Please try again.", font = (10))
         self.enterUser.delete(0, "end")
         self.enterPass.delete(0, "end")

    if userUsername == username and userPassword != password:

        self.enterLabel.configure(text="Invalid password. Please try again.", font = (10))
        self.enterPass.delete(0, "end")

    if userUsername == username and userPassword == password:

        self.enterUser.delete(0, "end")
        self.enterPass.delete(0, "end")
        self.goToSuccessfulLoginWindow()

def goToSuccessfulLoginWindow(self):

    root2 = tkinter.Toplevel()
    myGUI = successfulLogin(root2)
    myGUI.setName(userUsername)
</code>```

-----------------------------------------------------------------------------------------------------------------------

```<code>class successfulLogin():

def __init__(self, master):

    self.master = master
    self.master.title("Login Successful")
    self.master.geometry("700x700")
    self.master.configure(background="#fff1d0")

    self.confirmLabel = tkinter.Label(self.master, text = " ", font = ("Helvetica", 16), bg = "#fff1d0")
    self.confirmLabel.pack()

    self.quitButton = tkinter.ttk.Button(self.master, text = "Quit", command = self.quitWindow)
    self.quitButton.pack()

    self.logOutButton = tkinter.ttk.Button(self.master, text = "Log out", command = self.logout)
    self.logOutButton.pack()

def setName(self, username):
    name = username
    self.confirmLabel.configure(text = "welcome " + name)

def quitWindow(self):
    self.master.quit()

def logout(self):
    loginWindow(root)
    self.master.destroy()
</code>```

-----------------------------------------------------------------------------------------------------------------------

```<code>def centerWindow(width=300, height=200):
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))

root = tkinter.Tk()
centerWindow(310, 375)
root.resizable(False,False)
loginWindow(root)
root.mainloop(
</code>```

答:
Based on this answer example below can be produced.

```<code>import tkinter as tk

root = tk.Tk()

#In order to hide main window
root.withdraw()

tk.Label(root, text="This is the main window").pack()

aWindow = tk.Toplevel(root)

def change_window():
    #remove the other window entirely
    aWindow.destroy()

    #make root visible again
    root.iconify()
    root.deiconify()

tk.Button(aWindow, text="This is aWindow", command=change_window).pack()

root.mainloop()
</code>```

In the example first there's a window aWindow, and when you click the button on it, it destroys aWindow and makes the root window visible again.

Body:
I am extremely new to Tkinter and must use this for my programming coursework, i am looking for help to understand how to I destroy/hide the LoginWindow when the SuccessfulLogin window is opened. Bear in mind that i am new to tkinter. Thank you.

import tkinter
from tkinter import ttk

-----------------------------------------------------------------------------------------------------------------------

class loginWindow():

def __init__(self, master): #constructor

    self.master = master
    self.master.title("Main Menu") #window title
    self.master.geometry("400x400") #window size
    self.master.configure(background = "#fff1d0") #window colour, hexadecimal codes

    #self.photo = PhotoImage(file = "filename.png") #sets up image
    #self.photoLabel = Label(self.master, image = self.photo, bg = "red") #puts image on label
    #self.photoLabel.place(x=350 y=600) #places onto the screen with specified coordinates

    self.enterLabel = tkinter.Label(self.master, text = "Launcher", font = ("Helvetica", 16), bg = "#fff1d0")
    self.enterLabel.pack(pady = 10)

    self.emptySpace = tkinter.Label(self.master, text = " ", bg = "#fff1d0")
    self.emptySpace.pack(pady = 10)

    self.username = tkinter.Label(self.master, text = "Username:", bg = "#fff1d0") #Label widget and properties
    self.username.pack()
    self.enterUser = tkinter.ttk.Entry(self.master, width = 40) #Creates text entry widget
    self.enterUser.pack()

    self.password = tkinter.Label(self.master, text = "Password:", bg = "#fff1d0") #Label widget and properties
    self.password.pack()
    self.enterPass = tkinter.ttk.Entry(self.master, width = 40, show = "*") #Creates text entry widget
    self.enterPass.pack()

    self.loginButton = tkinter.ttk.Button(self.master, width = 40, text = "Login", command = self.loginAccess)
    self.loginButton.pack(pady = 10)

def loginAccess(self):

    username = "Aaron" #Needs to become a dictionary or database  or something with all usernames and passwords
    password = "Password"
    global userUsername
    userUsername = self.enterUser.get()
    userPassword = self.enterPass.get()

    if userUsername != username and userPassword != password:

         self.enterLabel.configure(text = "Invalid username and password. Please try again.", font = (10))
         self.enterUser.delete(0, "end")
         self.enterPass.delete(0, "end")

    if userUsername == username and userPassword != password:

        self.enterLabel.configure(text="Invalid password. Please try again.", font = (10))
        self.enterPass.delete(0, "end")

    if userUsername == username and userPassword == password:

        self.enterUser.delete(0, "end")
        self.enterPass.delete(0, "end")
        self.goToSuccessfulLoginWindow()

def goToSuccessfulLoginWindow(self):

    root2 = tkinter.Toplevel()
    myGUI = successfulLogin(root2)
    myGUI.setName(userUsername)

-----------------------------------------------------------------------------------------------------------------------

class successfulLogin():

def __init__(self, master):

    self.master = master
    self.master.title("Login Successful")
    self.master.geometry("700x700")
    self.master.configure(background="#fff1d0")

    self.confirmLabel = tkinter.Label(self.master, text = " ", font = ("Helvetica", 16), bg = "#fff1d0")
    self.confirmLabel.pack()

    self.quitButton = tkinter.ttk.Button(self.master, text = "Quit", command = self.quitWindow)
    self.quitButton.pack()

    self.logOutButton = tkinter.ttk.Button(self.master, text = "Log out", command = self.logout)
    self.logOutButton.pack()

def setName(self, username):
    name = username
    self.confirmLabel.configure(text = "welcome " + name)

def quitWindow(self):
    self.master.quit()

def logout(self):
    loginWindow(root)
    self.master.destroy()

-----------------------------------------------------------------------------------------------------------------------

def centerWindow(width=300, height=200):
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))

root = tkinter.Tk()
centerWindow(310, 375)
root.resizable(False,False)
loginWindow(root)
root.mainloop(

Body:
Based on this answer example below can be produced.

import tkinter as tk

root = tk.Tk()

#In order to hide main window
root.withdraw()

tk.Label(root, text="This is the main window").pack()

aWindow = tk.Toplevel(root)

def change_window():
    #remove the other window entirely
    aWindow.destroy()

    #make root visible again
    root.iconify()
    root.deiconify()

tk.Button(aWindow, text="This is aWindow", command=change_window).pack()

root.mainloop()

In the example first there's a window aWindow, and when you click the button on it, it destroys aWindow and makes the root window visible again.


来源: stackexchange

问:
Angular 5 animate SVG viewBox
I would like to change viewBox attribute of SVG (zoom in to specific area) and I would like this change to be animated. Can I do it using angular animations?

I calculate new viewBox value dynamically based on where user click on SVG.

答:
Example of dynamic resizing viewBox

The animation for resizing the viewBox uses the SVG command:

<animate  attributeName="viewBox" />

Initial value:  viewBox="200 200 2700 2700"

The final value is: viewBox =" 0 0 300 300 "

As a result, the user viewing window is increased 9 times.

```<code><animate  attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="1.5s" fill="freeze"  restart="whenNotActive" />
</code>```

Animation starts when you click on svg window

body {
padding:0;
margin:0;
}
svg text {
fill:white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg id="svg1" width="300" height="300" viewBox="200 200 2700 2700" style="border:1px solid grey;">
<text x="235" y="255" font-size="24" > Click me </text>
<rect id="R1" x="0" y="0" width="100" height="100" fill="#5A9C6E" />
<rect id="R2" x="100" y="0" width="100" height="100" fill="#A8BF5A" />
<rect id="R3" x="200" y="0" width="100" height="100" fill="#FAC46E" />

<rect id="R4" x="0" y="100" width="100" height="100" fill="greenyellow" />
<rect id="R5" x="100" y="100" width="100" height="100" fill="#5A9C6E" />
<rect id="R6" x="200" y="100" width="100" height="100" fill="skyblue" />

<rect id="R7" x="0" y="200" width="100" height="100" fill="#FAC46E" />
<rect id="R8" x="100" y="200" width="100" height="100" fill="yellow" />
<rect id="R9" x="200" y="200" width="100" height="100" fill="#5A9C6E" />

<text x="35" y="55" font-size="24" > R1 </text>
<text x="135" y="55" font-size="24" > R2 </text>
<text x="235" y="55" font-size="24" > R3</text>

<text x="35" y="155" font-size="24" style="fill:grey;" > R4 </text>
<text x="135" y="155" font-size="24" > R5 </text>
<text x="235" y="155" font-size="24" > R6 </text>

<text x="35" y="255" font-size="24" > R7 </text>
<text x="135" y="255" font-size="24" style="fill:grey;" > R8 </text>
<text x="235" y="255" font-size="24" > R9 </text>

<animate  attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="1.5s" fill="freeze"  restart="whenNotActive" />
 </svg></code>```

Example of sequential increase and decrease of viewBox

<svg id="svg1" width="300" height="300" viewBox="200 200 2700 2700" style="border:1px solid grey;">
<text x="235" y="255" font-size="24" > Click me </text>
<rect id="R1" x="0" y="0" width="100" height="100" fill="#5A9C6E" />
<rect id="R2" x="100" y="0" width="100" height="100" fill="#A8BF5A" />
<rect id="R3" x="200" y="0" width="100" height="100" fill="#FAC46E" />

<rect id="R4" x="0" y="100" width="100" height="100" fill="greenyellow" />
<rect id="R5" x="100" y="100" width="100" height="100" fill="#5A9C6E" />
<rect id="R6" x="200" y="100" width="100" height="100" fill="skyblue" />

<rect id="R7" x="0" y="200" width="100" height="100" fill="#FAC46E" />
<rect id="R8" x="100" y="200" width="100" height="100" fill="yellow" />
<rect id="R9" x="200" y="200" width="100" height="100" fill="#5A9C6E" />

<text x="35" y="55" font-size="24" > R1 </text>
<text x="135" y="55" font-size="24" > R2 </text>
<text x="235" y="55" font-size="24" > R3</text>

<text x="35" y="155" font-size="24" style="fill:grey;" > R4 </text>
<text x="135" y="155" font-size="24" > R5 </text>
<text x="235" y="155" font-size="24" > R6 </text>

<text x="35" y="255" font-size="24" > R7 </text>
<text x="135" y="255" font-size="24" style="fill:grey;" > R8 </text>
<text x="235" y="255" font-size="24" > R9 </text>

<animate id="an1" attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="4.5s" fill="freeze"  restart="whenNotActive" />
<animate id="an2" attributeName="viewBox"  begin="an1.end+2.25s" values="0 0 300 300;200 200 2700 2700" dur="2.5s" fill="freeze"  restart="whenNotActive" />

 </svg>```

ContentLicense: CC BY-SA 3.0

Title: Angular 5 animate SVG viewBox

Body:
Example of dynamic resizing viewBox

The animation for resizing the viewBox uses the SVG command:

<animate  attributeName="viewBox" />

Initial value:  viewBox="200 200 2700 2700"

The final value is: viewBox =" 0 0 300 300 "

As a result, the user viewing window is increased 9 times.

<animate  attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="1.5s" fill="freeze"  restart="whenNotActive" />

Animation starts when you click on svg window

body {
padding:0;
margin:0;
}
svg text {
fill:white;
}

<svg id="svg1" width="300" height="300" viewBox="200 200 2700 2700" style="border:1px solid grey;">
<text x="235" y="255" font-size="24" > Click me </text>
<rect id="R1" x="0" y="0" width="100" height="100" fill="#5A9C6E" />
<rect id="R2" x="100" y="0" width="100" height="100" fill="#A8BF5A" />
<rect id="R3" x="200" y="0" width="100" height="100" fill="#FAC46E" />

<rect id="R4" x="0" y="100" width="100" height="100" fill="greenyellow" />
<rect id="R5" x="100" y="100" width="100" height="100" fill="#5A9C6E" />
<rect id="R6" x="200" y="100" width="100" height="100" fill="skyblue" />

<rect id="R7" x="0" y="200" width="100" height="100" fill="#FAC46E" />
<rect id="R8" x="100" y="200" width="100" height="100" fill="yellow" />
<rect id="R9" x="200" y="200" width="100" height="100" fill="#5A9C6E" />

<text x="35" y="55" font-size="24" > R1 </text>
<text x="135" y="55" font-size="24" > R2 </text>
<text x="235" y="55" font-size="24" > R3</text>

<text x="35" y="155" font-size="24" style="fill:grey;" > R4 </text>
<text x="135" y="155" font-size="24" > R5 </text>
<text x="235" y="155" font-size="24" > R6 </text>

<text x="35" y="255" font-size="24" > R7 </text>
<text x="135" y="255" font-size="24" style="fill:grey;" > R8 </text>
<text x="235" y="255" font-size="24" > R9 </text>

<animate  attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="1.5s" fill="freeze"  restart="whenNotActive" />
 </svg>

Example of sequential increase and decrease of viewBox

<style>
body {
padding:0;
margin:0;
}
svg text {
fill:white;
}
</style>

<svg id="svg1" width="300" height="300" viewBox="200 200 2700 2700" style="border:1px solid grey;">
<text x="235" y="255" font-size="24" > Click me </text>
<rect id="R1" x="0" y="0" width="100" height="100" fill="#5A9C6E" />
<rect id="R2" x="100" y="0" width="100" height="100" fill="#A8BF5A" />
<rect id="R3" x="200" y="0" width="100" height="100" fill="#FAC46E" />

<rect id="R4" x="0" y="100" width="100" height="100" fill="greenyellow" />
<rect id="R5" x="100" y="100" width="100" height="100" fill="#5A9C6E" />
<rect id="R6" x="200" y="100" width="100" height="100" fill="skyblue" />

<rect id="R7" x="0" y="200" width="100" height="100" fill="#FAC46E" />
<rect id="R8" x="100" y="200" width="100" height="100" fill="yellow" />
<rect id="R9" x="200" y="200" width="100" height="100" fill="#5A9C6E" />

<text x="35" y="55" font-size="24" > R1 </text>
<text x="135" y="55" font-size="24" > R2 </text>
<text x="235" y="55" font-size="24" > R3</text>

<text x="35" y="155" font-size="24" style="fill:grey;" > R4 </text>
<text x="135" y="155" font-size="24" > R5 </text>
<text x="235" y="155" font-size="24" > R6 </text>

<text x="35" y="255" font-size="24" > R7 </text>
<text x="135" y="255" font-size="24" style="fill:grey;" > R8 </text>
<text x="235" y="255" font-size="24" > R9 </text>

<animate id="an1" attributeName="viewBox"  begin="svg1.click+0.25s" values="200 200 2700 2700;0 0 300 300" dur="4.5s" fill="freeze"  restart="whenNotActive" />
<animate id="an2" attributeName="viewBox"  begin="an1.end+2.25s" values="0 0 300 300;200 200 2700 2700" dur="2.5s" fill="freeze"  restart="whenNotActive" />

 </svg>


问:
Analyzing efficiency of non-recursive algorithm
I am trying to analyze an algorithm to estimate its time efficiency using 5 steps.

The five steps are:

Decide on parameter n indicating input size.

Identify algorithm’s basic operation.

Determine worst, average, and best case for input of size n.

Set up summation for C(n) reflecting algorithm’s loop
structure.

Simplify summation.

The algorithm is:

```<code>Algorithm UniqueElements (A[0 … n-1)
– //Check whether all the elements in a given array are
distinct
– //Input: an array A[0 … n]
– //Output: returns “true” if all the elements in A are
distinct and “false” otherwise
for i ← 0 to n - 2 do
 for j ← i + 1 to n - 1 do
– If A[i] = A[j] return false
return true
</code>```

My way to solve this is:

Since I'm only deciding on an input size, I chose 6.

I said the algorithm's basic operation is the comparison between A[i] = A[j].

Best case: n = 1. Worst case = 6. Average case = 3.

Summation:

Summation will be simplified to n^2

Did I do this correctly?

答:
I believe this should be solved as follows:

Decide parameter n.
I think this is asking for what is 'n' in the equation. So here, it's the length of the input array.

I agree with the basic operation. The comparison A[i] == A[j].

Since this algorithm breaks early if two elements are the same, then we know that the worst case is when all elements are distinct. In this situation, we'd have two loops-- one nested in the other-- each linearly related to the input length (n).

This means our worst case is bounded by O(n^2).

Our average case is calculated by summing all possible outcomes and dividing by all outcomes. This looks very similar to the summating for C(n). The sum of possible times it will take to run giving an input of length n is:

maths to calculate average time
This comes out to be Theta(n^2)

Finally, best case time. This is almost trivial<\i>. The best case here is where the first and second items in the array are identical. This is constant time, so best case is theta(1).

For this part, refer again the to linked maths.

I agree with your simplification here! n^2 is correct.

Hope this helps!

Body:
I am trying to analyze an algorithm to estimate its time efficiency using 5 steps.

The five steps are:

Decide on parameter n indicating input size.

Identify algorithm’s basic operation.

Determine worst, average, and best case for input of size n.

Set up summation for C(n) reflecting algorithm’s loop
structure.

Simplify summation.

The algorithm is:

Algorithm UniqueElements (A[0 … n-1)
– //Check whether all the elements in a given array are
distinct
– //Input: an array A[0 … n]
– //Output: returns “true” if all the elements in A are
distinct and “false” otherwise
for i ← 0 to n - 2 do
 for j ← i + 1 to n - 1 do
– If A[i] = A[j] return false
return true

My way to solve this is:

Since I'm only deciding on an input size, I chose 6.

I said the algorithm's basic operation is the comparison between A[i] = A[j].

Best case: n = 1. Worst case = 6. Average case = 3.

Summation:

Summation will be simplified to n^2

Did I do this correctly?


问:
Replace value with consecutive column across multiple columns r
I have a dataframe like this:

```<code>     Q1  Q1a    Q2    Q2a   Q2b
1   foo <NA>    fee   <NA>  <NA>
2   bar <NA>  other    ree  <NA>
3 other  roo    bee   <NA>  <NA>
4   bar <NA>    fee   <NA>  <NA>
5   bar <NA>  other    fee  <NA>
6 other  fee  other    <NA>  roo
</code>```

I would like to replace any occurrence of 'other' with the value from the consecutive column in the same row (i.e. Qx a) so that I can get rid of the sparse columns:

```<code>     Q1    Q2
1   foo   fee
2   bar   ree
3   roo   bee
4   bar   fee
5   bar   fee
6   fee   roo
</code>```

I could imagine doing this for one column like so:

```<code>Lines = "
Q1  Q1a    Q2    Q2a   Q2b
foo NA fee  NA  NA
bar NA other  ree  NA
other roo  bee   NA  NA
bar NA    fee   NA  NA
bar NA    other fee  NA
other  fee  other NA  roo"

df = read.table(text = Lines, header = TRUE, as.is = TRUE)

df$Q1[df$Q1=='other'] = df$Q1a[df$Q1=='other']
</code>```

and then looping through for each column, but this is a bit tiresome and slow with lots of columns and multiple values in each column.

Is there a neater way of doing this? (Also, my method wouldn't extend neatly to the Q2a Q2b example.)

答:
We can split the dataset based on similar columns, then loop through the list of data.frames and replace the values that are 'other' based on the index created with max.col

```<code>data.frame(lapply(split.default(df, sub("[a-z]+$", "", names(df))), function(x) {
          i1 <- x[,1] == "other"
          i2 <- x[-1] != "other" & !is.na(x[-1])
          x[,1][i1] <- x[-1][cbind(1:nrow(i2), (max.col(i2))* i1)]
       x[,1]
  }))
#   Q1  Q2
#1 foo fee
#2 bar ree
#3 roo bee
#4 bar fee
#5 bar fee
#6 fee roo
</code>```

Or with tidyverse

```<code>library(dplyr)
library(purrr)
split.default(df, sub("[a-z]+$", "", names(df))) %>%
       map_df(~ replace(., .== 'other', NA) %>%
                 do.call(paste, .) %>%
                 gsub("\\s*|(NA\\s*)+", "", .))
# A tibble: 6 x 2
#     Q1    Q2
#   <chr> <chr>
#1   foo   fee
#2   bar   ree
#3   roo   bee
#4   bar   fee
#5   bar   fee
#6   fee   roo
</code>```

Body:
I have a dataframe like this:

     Q1  Q1a    Q2    Q2a   Q2b
1   foo <NA>    fee   <NA>  <NA>
2   bar <NA>  other    ree  <NA>
3 other  roo    bee   <NA>  <NA>
4   bar <NA>    fee   <NA>  <NA>
5   bar <NA>  other    fee  <NA>
6 other  fee  other    <NA>  roo

I would like to replace any occurrence of 'other' with the value from the consecutive column in the same row (i.e. Qx a) so that I can get rid of the sparse columns:

     Q1    Q2
1   foo   fee
2   bar   ree
3   roo   bee
4   bar   fee
5   bar   fee
6   fee   roo

I could imagine doing this for one column like so:

Lines = "
Q1  Q1a    Q2    Q2a   Q2b
foo NA fee  NA  NA
bar NA other  ree  NA
other roo  bee   NA  NA
bar NA    fee   NA  NA
bar NA    other fee  NA
other  fee  other NA  roo"

df = read.table(text = Lines, header = TRUE, as.is = TRUE)

df$Q1[df$Q1=='other'] = df$Q1a[df$Q1=='other']

and then looping through for each column, but this is a bit tiresome and slow with lots of columns and multiple values in each column.

Is there a neater way of doing this? (Also, my method wouldn't extend neatly to the Q2a Q2b example.)

Body:
We can split the dataset based on similar columns, then loop through the list of data.frames and replace the values that are 'other' based on the index created with max.col

data.frame(lapply(split.default(df, sub("[a-z]+$", "", names(df))), function(x) {
          i1 <- x[,1] == "other"
          i2 <- x[-1] != "other" & !is.na(x[-1])
          x[,1][i1] <- x[-1][cbind(1:nrow(i2), (max.col(i2))* i1)]
       x[,1]
  }))
#   Q1  Q2
#1 foo fee
#2 bar ree
#3 roo bee
#4 bar fee
#5 bar fee
#6 fee roo

Or with tidyverse

library(dplyr)
library(purrr)
split.default(df, sub("[a-z]+$", "", names(df))) %>%
       map_df(~ replace(., .== 'other', NA) %>%
                 do.call(paste, .) %>%
                 gsub("\\s*|(NA\\s*)+", "", .))
# A tibble: 6 x 2
#     Q1    Q2
#   <chr> <chr>
#1   foo   fee
#2   bar   ree
#3   roo   bee
#4   bar   fee
#5   bar   fee
#6   fee   roo


问:
Why do some websites have styles that aren't assigned to elements when I inspect the markup?
I found something really weird to me on Github:

body.impress-on-applepie #applepie-image,
body.impress-on-applepie-pro #applepie-image,
body.impress-on-applepie-con #applepie-image,
body.impress-on-conclusion #applepie-image,
body.impress-on-overview #applepie-image {
    opacity: 0.7;
    transition:  opacity 2s;
}
```

<pre class="lang-html prettyprint-override"><code><body class="impress-not-supported">
...
</body>
</code>```

As you can see,  only has the class impress-not-supported, so why are there so many other classes in the stylesheet which do not exist or aren't declared in HTML, and how do these styles work?

(these selectors are start from line 197 in presentation.css file.)

答:
Some part of html DOM tree can be loaded in the page after page loaded completely based on JavaScript or JQuery functions which maybe related on user behavior or not (I mean automatically run some functions after page load event).

So you won't be able to see this parts of html DOM tree in compile time but those styles are needed to be exist in page.

Body:
I found something really weird to me on Github:

body.impress-on-applepie #applepie-image,
body.impress-on-applepie-pro #applepie-image,
body.impress-on-applepie-con #applepie-image,
body.impress-on-conclusion #applepie-image,
body.impress-on-overview #applepie-image {
    opacity: 0.7;
    transition:  opacity 2s;
}

...

As you can see,  only has the class impress-not-supported, so why are there so many other classes in the stylesheet which do not exist or aren't declared in HTML, and how do these styles work?

(these selectors are start from line 197 in presentation.css file.)


问:
Python - Shift/Delete Elements in a 2-Dimensional Array
I need help with shifting and deleting elements in a 2-dimensional array.

If the value in a list is negative and their is a list above it with positive values in the same location. It should shift everything down, causing the negative values to disappear.

If there isn't any list above it or the corresponding values in the list above are just 0. It will replace the negative values with 0.

Note: The positive values should never disappear, they can only move down when needed. Only the negative values (below -100) disappear.

These examples should explain it better:

Scenario 1:

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0], [-103, -103, -103, 0, 0]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]

Scenario 2:

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, -101, -101, -101], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]

Scenario 3: (This is the only one that I got working in my code below.)

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [-102, -102, -102, 0, 0], [3, 1, 3, 0, 0]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]

```<code>def move(data):

    c_count = 4

    while c_count >= 0:

        count = len(data) - 1
        prev = count - 1

        while count > 0 and prev >= 0:
            if data[count][c_count] < -100:

                while prev >= 0 and data[prev][c_count] == 0:
                    prev -= 1

                data[count][c_count] = data[prev][c_count]
                data[prev][c_count]= 0

            count -= 1
            prev -= 1

        c_count -= 1

    return data

my_data = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [-102, -102, -102, 0, 0], [3, 1, 3, 0, 0]]
x = move(my_data) # This is (scenario 3) is the only one that works.
print(x)
</code>```

Thanks so much for your help! I have been stuck on this for a while.

答:
I work with columns separately, not with full rows.

search in column from bottom to top

find negative value

find positive value (bigger then zero) above

if not found then put zero in place of negative

if found then move down all value above

move above to row, above-1 to row-1, above-2 to row-2, etc.

BTW: it is easier to search solution when rows are displayed one below another.

```<code>def move(data):

    # work in column, not with full rows
    for col in range(len(data)):

        # move from bottom to top
        for row in range(len(data[0])-1, -1, -1):

            # check if negative value
            if data[row][col] < 0:
                print('debug: negative:', data[row][col])

                # find positive value above
                above = row-1
                while above > -1 and data[above][col] <= 0:
                    above -= 1

                # check if found positive value
                if above == -1:
                    # put zero if not found value above
                    print('debug: put zero')
                    data[row][col] = 0
                else:
                    # move down all values above
                    print('debug: move down', above+1, 'element(s)')
                    while above > -1:
                        data[row][col] = data[above][col]
                        data[above][col] = 0
                        row -= 1
                        above -= 1

    return data

# --- function to run one scenario, display data and check result ---

def run(data, expect):
    print('data:')
    print('\n'.join(str(row) for row in data))
    print()
    result = move(data)
    print()
    print('result:')
    print(result)
    print('expect:')
    print(expect)
    print('expect == result:', expect == result)
    print('---')

# --- scenarios ---

def scenario1():

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 2, 1, 0, 0],
        [2, 1, 2, 0, 0],
        [-103, -103, -103, 0, 0]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 2, 1, 0, 0],
        [2, 1, 2, 0, 0]
    ]

    run(DATA, EXPECT)

def scenario2():

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 2, -101, -101, -101],
        [0, 1, 2, 3, 2],
        [0, 3, 3, 2, 3]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 2, 0, 0, 0],
        [0, 1, 2, 3, 2],
        [0, 3, 3, 2, 3]
    ]

    run(DATA, EXPECT)

def scenario3(): #(This is the only one that I got working in my code below.)

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 3, 1, 0, 0],
        [-102, -102, -102, 0, 0],
        [3, 1, 3, 0, 0]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 3, 1, 0, 0],
        [3, 1, 3, 0, 0]
    ]

    run(DATA, EXPECT)

# --- start scenarios ---

scenario1()
scenario2()
scenario3()
</code>```

Results:

```<code>data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 1, 0, 0]
[2, 1, 2, 0, 0]
[-103, -103, -103, 0, 0]

debug: negative: -103
debug: move down 4 element(s)
debug: negative: -103
debug: move down 4 element(s)
debug: negative: -103
debug: move down 4 element(s)

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]
expect == result: True
---
data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 2, -101, -101, -101]
[0, 1, 2, 3, 2]
[0, 3, 3, 2, 3]

debug: negative: -101
debug: put zero
debug: negative: -101
debug: put zero
debug: negative: -101
debug: put zero

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]
expect == result: True
---
data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 3, 1, 0, 0]
[-102, -102, -102, 0, 0]
[3, 1, 3, 0, 0]

debug: negative: -102
debug: move down 3 element(s)
debug: negative: -102
debug: move down 3 element(s)
debug: negative: -102
debug: move down 3 element(s)

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]
expect == result: True
---
</code>```

Body:
I need help with shifting and deleting elements in a 2-dimensional array.

If the value in a list is negative and their is a list above it with positive values in the same location. It should shift everything down, causing the negative values to disappear.

If there isn't any list above it or the corresponding values in the list above are just 0. It will replace the negative values with 0.

Note: The positive values should never disappear, they can only move down when needed. Only the negative values (below -100) disappear.

These examples should explain it better:

Scenario 1:

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0], [-103, -103, -103, 0, 0]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]

Scenario 2:

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, -101, -101, -101], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]

Scenario 3: (This is the only one that I got working in my code below.)

DATA: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [-102, -102, -102, 0, 0], [3, 1, 3, 0, 0]]

EXPECT: [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]

def move(data):

    c_count = 4

    while c_count >= 0:

        count = len(data) - 1
        prev = count - 1

        while count > 0 and prev >= 0:
            if data[count][c_count] < -100:

                while prev >= 0 and data[prev][c_count] == 0:
                    prev -= 1

                data[count][c_count] = data[prev][c_count]
                data[prev][c_count]= 0

            count -= 1
            prev -= 1

        c_count -= 1

    return data

my_data = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [-102, -102, -102, 0, 0], [3, 1, 3, 0, 0]]
x = move(my_data) # This is (scenario 3) is the only one that works.
print(x)

Thanks so much for your help! I have been stuck on this for a while.

Body:
I work with columns separately, not with full rows.

search in column from bottom to top

find negative value

find positive value (bigger then zero) above

if not found then put zero in place of negative

if found then move down all value above

move above to row, above-1 to row-1, above-2 to row-2, etc.

BTW: it is easier to search solution when rows are displayed one below another.

def move(data):

    # work in column, not with full rows
    for col in range(len(data)):

        # move from bottom to top
        for row in range(len(data[0])-1, -1, -1):

            # check if negative value
            if data[row][col] < 0:
                print('debug: negative:', data[row][col])

                # find positive value above
                above = row-1
                while above > -1 and data[above][col] <= 0:
                    above -= 1

                # check if found positive value
                if above == -1:
                    # put zero if not found value above
                    print('debug: put zero')
                    data[row][col] = 0
                else:
                    # move down all values above
                    print('debug: move down', above+1, 'element(s)')
                    while above > -1:
                        data[row][col] = data[above][col]
                        data[above][col] = 0
                        row -= 1
                        above -= 1

    return data

# --- function to run one scenario, display data and check result ---

def run(data, expect):
    print('data:')
    print('\n'.join(str(row) for row in data))
    print()
    result = move(data)
    print()
    print('result:')
    print(result)
    print('expect:')
    print(expect)
    print('expect == result:', expect == result)
    print('---')

# --- scenarios ---

def scenario1():

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 2, 1, 0, 0],
        [2, 1, 2, 0, 0],
        [-103, -103, -103, 0, 0]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 2, 1, 0, 0],
        [2, 1, 2, 0, 0]
    ]

    run(DATA, EXPECT)

def scenario2():

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 2, -101, -101, -101],
        [0, 1, 2, 3, 2],
        [0, 3, 3, 2, 3]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 2, 0, 0, 0],
        [0, 1, 2, 3, 2],
        [0, 3, 3, 2, 3]
    ]

    run(DATA, EXPECT)

def scenario3(): #(This is the only one that I got working in my code below.)

    DATA = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 3, 1, 0, 0],
        [-102, -102, -102, 0, 0],
        [3, 1, 3, 0, 0]
    ]

    EXPECT = [
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0],
        [1, 3, 1, 0, 0],
        [3, 1, 3, 0, 0]
    ]

    run(DATA, EXPECT)

# --- start scenarios ---

scenario1()
scenario2()
scenario3()

Results:

data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 2, 1, 0, 0]
[2, 1, 2, 0, 0]
[-103, -103, -103, 0, 0]

debug: negative: -103
debug: move down 4 element(s)
debug: negative: -103
debug: move down 4 element(s)
debug: negative: -103
debug: move down 4 element(s)

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 2, 1, 0, 0], [2, 1, 2, 0, 0]]
expect == result: True
---
data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 2, -101, -101, -101]
[0, 1, 2, 3, 2]
[0, 3, 3, 2, 3]

debug: negative: -101
debug: put zero
debug: negative: -101
debug: put zero
debug: negative: -101
debug: put zero

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 1, 2, 3, 2], [0, 3, 3, 2, 3]]
expect == result: True
---
data:
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[1, 3, 1, 0, 0]
[-102, -102, -102, 0, 0]
[3, 1, 3, 0, 0]

debug: negative: -102
debug: move down 3 element(s)
debug: negative: -102
debug: move down 3 element(s)
debug: negative: -102
debug: move down 3 element(s)

result:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]
expect:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 3, 1, 0, 0], [3, 1, 3, 0, 0]]
expect == result: True
---


问:
PHP password recovery
I realize that for security that passwords should not be stored in a DB as plaintext.  If I hash them, I can validate them for login purposes.

But if I want to set up a password recovery system, what's the best strategy since there is no undoing of the hashing?

Could someone give me a brief overview of a good and secure strategy for storing and recovering passwords?

答:
You don't 'recover' passwords.  What you do is one of 2 things.

Email the user a link to create a new password, overriding the current one

Email the user a randomly generated password, then ask them to change it

Title: PHP password recovery

ContentLicense: CC BY-SA 2.5


问:
MySQL insert query where a value does not match
I would like to insert some data into mySQL like this:

```<code>INSERT INTO user_data (user_id,value) VALUES (1,2)
</code>```

Is there a way to make sure the same value for the user doesn't exist? I want it to only insert the data if value for user_id does not already exist?

So basically a user_id can have multiple values. I know this can be done unique field. But I am looking to do this with a SQL query

答:
Like others have pointed out in the comments, it would be easier/better if you could add UNIQUE key to the table and then you could simply use INSERT INTO ... ON DUPLICATE KEY UPDATE

But since you said that is not an option this could also work

```<code>INSERT INTO user_data (user_id, value)
SELECT * FROM (SELECT 1, 2) AS tmp
WHERE NOT EXISTS (
    SELECT user_id FROM user_data WHERE user_id = 1 AND value = 2
) LIMIT 1;
</code>```

Body:
I would like to insert some data into mySQL like this:

INSERT INTO user_data (user_id,value) VALUES (1,2)

Is there a way to make sure the same value for the user doesn't exist? I want it to only insert the data if value for user_id does not already exist?

So basically a user_id can have multiple values. I know this can be done unique field. But I am looking to do this with a SQL query

Body:
Like others have pointed out in the comments, it would be easier/better if you could add UNIQUE key to the table and then you could simply use INSERT INTO ... ON DUPLICATE KEY UPDATE

But since you said that is not an option this could also work

INSERT INTO user_data (user_id, value)
SELECT * FROM (SELECT 1, 2) AS tmp
WHERE NOT EXISTS (
    SELECT user_id FROM user_data WHERE user_id = 1 AND value = 2
) LIMIT 1;


问:
Formatting strings from a text file
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.

This is the code for my program:

```<code>def makeTuple (employee):

    myTuple = employee.split(" ")
    payroll, salary, job_title, *othernames, surname = myTuple
    myTuple = tuple(myTuple)
    return(myTuple)

def printTuple (data):

    employee_str = "{}, {} {:>8} {} {:>5}"
    print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    text_file = open(path, "r")
except IOError:
    print('The file could not be opened.')
    exit()

record = text_file.readline()

myTuple = makeTuple(record)
printTuple(myTuple)
</code>```

This is the text file I'm reading from:

```<code>12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger
</code>```

The output I get at the moment is:

```<code>Simpson
, Bart    12345 Consultant 55000
</code>```

Whereas I want it to look like:

```<code>Simpson, Bart    12345 Consultant 55000
</code>```

答:
You can do it with split and join:</p>

```<code>s = '''Simpson
, Bart    12345 Consultant 55000'''

print(''.join(s.split('\n')))
</code>```

Title: Formatting strings from a text file

Body:
I'm trying to format my text line by line read from a .txt file. Firstly I'm just trying to figure out how to print just one line, then attempt multiple lines after. I've managed to print the text of one line, but when I try to format it they way I want it to look, a new line is created after I attempt to print the last word of the line (using index of -1). The last word is creating a new line, so I think I need to find a way to read the lines as seperate strings but I'm not sure.

This is the code for my program:

def makeTuple (employee):

    myTuple = employee.split(" ")
    payroll, salary, job_title, *othernames, surname = myTuple
    myTuple = tuple(myTuple)
    return(myTuple)

def printTuple (data):

    employee_str = "{}, {} {:>8} {} {:>5}"
    print(employee_str.format(data[-1], " ".join(data[3:-1], data[0], data[2], data[1]))

get_file = input(str("Please enter a filename: "))
path = get_file + ".txt"

try:
    text_file = open(path, "r")
except IOError:
    print('The file could not be opened.')
    exit()

record = text_file.readline()

myTuple = makeTuple(record)
printTuple(myTuple)

This is the text file I'm reading from:

12345 55000 Consultant Bart Simpson
12346 25000 Teacher Ned Flanders
12347 20000 Secretary Lisa Simpson
12348 20000 Wizard Hermione Grainger

The output I get at the moment is:

Simpson
, Bart    12345 Consultant 55000

Whereas I want it to look like:

Simpson, Bart    12345 Consultant 55000

Body:
You can do it with split and join:

s = '''Simpson
, Bart    12345 Consultant 55000'''

print(''.join(s.split('\n')))


问:
Partition a large Hibernate model to manage schema dependencies
We are considering splitting our hibernate tables into packages or domains (invoicing, sales, ..etc), primarily for dependency management issues.

It doesn't break neatly of course, so we aren't sure how to handle relationships that cross domains.  It would be nice to have a new entity annotation for this, but meanwhile one idea is to make multiple copies of model in which there is some variation in how relations are annotated to 'snip off the loose ends'.  These altered entites would probably need to be made 'read only' in the other models they don't belong to.  Also, we would keep using the existing full model for a while as we transition apps to use the smaller ones.

So for example, most tables should exist entirely in one model or another; but if Domain1.Table1 relates to Domain2.Table2, then you would make a read-only copy of each in the other's domain.  The copy would have it's other relationships in it's domain changed into 'dead ends' (probably by replacing relationship links with an integer fk reference attribute instead).

The point being, we'd like to have some way to manage our maven builds so that when someone changes an attribute on a table, we have declared dependencies on just that domain's model, so we can reduce the number of apps that need to be rebuilt. (we have tight deployment outage windows).

Oh, and all the domains have to use the same java package for compatibility with our legacy EJB persistence tool

So that's the idea.  Any suggestions/feedback/comments?  Thanks!

答:
You suggest copying the related table's entities into the required domains (not it's domain) and then changing it's own domain dependencies into "dead-ends" a.k.a. Integer FK values which could be potentially used to do lookups if necessary.

My suggestion would be you should do this at the edge of each domain and to not copy anything. So if, Domain1.Table1 relates to Domain2.Table2, it simply has a FK, int fields maybe called table2Id. This would creates the dead-ends at the edge of each domain instead of needing crossover and duplication.

I have to ask though...

Are you sure you have multiple domains?

The root of you problem seems to come from the fact that your data is related, indicating to me that they are part of the same domain. For instance, you speak of sales and invoicing as separate domains but they probably both share customer references. This all feels like it belongs together to me. Some projects'/industries' domains are large and breaking them up for convenience and simplicity usually turns out to be a mistake in the end and often adds unanticipated complexity. For instance, if you need to do a Sale look up which should have a reference to the invoice, but instead now you have to do a separate invoice lookup, it makes your API's clients' usage a little heavyweight.


问:
User defined system variable throws null pointer exception when executed as testng suite
There has been a situation when I need to run with the user defined <systemPropertyVariables> in one of my utility class.

```<code><systemPropertyVariables>
<environment>uat</environment>
</systemPropertyVariables>
</code>```

I have defined this in my pom.xml file.

inside my utility class I am extracting this value using below

```<code>System.getProperty("environment");
</code>```

When I run the test case through pom.xml it runs fine. But when I try to run it through testing.xml file or as a testng test, it gives me nullpointerException.

I have defined vmarguments in run configuration as a temp solution but when this code gets distributed again this won't work as run configuration is limited to the local machines.

Can anyone please help me on how to resolve this error. Where should I define the SystemPropertyVariable so that it also works when I run the testng suite individually.

答:
Hi i have found a solution for this if any one else is stuck with this type of problem while designing framework.

Write a simple java code

```<code>try{
your code
}catch(NullPointerException ee){
environment="";
e.printStackTrace();
}catch(Exception e){
Assert.assertTrue(fail);
}
</code>```

it only handles your code when you run via testng.xml (which is not part of your major test runs) and fails when we get any other exceptions.

Body:
There has been a situation when I need to run with the user defined <systemPropertyVariables> in one of my utility class.

<systemPropertyVariables>
<environment>uat</environment>
</systemPropertyVariables>

I have defined this in my pom.xml file.

inside my utility class I am extracting this value using below

System.getProperty("environment");

When I run the test case through pom.xml it runs fine. But when I try to run it through testing.xml file or as a testng test, it gives me nullpointerException.

I have defined vmarguments in run configuration as a temp solution but when this code gets distributed again this won't work as run configuration is limited to the local machines.

Can anyone please help me on how to resolve this error. Where should I define the SystemPropertyVariable so that it also works when I run the testng suite individually.

Body:
Hi i have found a solution for this if any one else is stuck with this type of problem while designing framework.

Write a simple java code

try{
your code
}catch(NullPointerException ee){
environment="";
e.printStackTrace();
}catch(Exception e){
Assert.assertTrue(fail);
}

it only handles your code when you run via testng.xml (which is not part of your major test runs) and fails when we get any other exceptions.


问:
Opening excel file with tkfiledialog
I have few code to open file in excel spreadsheet

```<code>filename = filedialog.askopenfilename(initialdir="C:/", title="select file",
                                          filetypes=(("excel files", "*.xls"), ("all files", "*.*")))

os.system(r"excel.exe" + filename)
</code>```

when i select the file i want read i get the following error:

excel.exeC:' is not recognized as an internal or external command,
  operable program or batch file.

I tried to open with notepad wiht the os.system(r"notepad.exe" + filename) but i want to open it in excel using the excel.
I welcome your suggestion to open it in excel file.

答:
You can specifically refer to the excel .exe file, however, you would need to use the full location and this can be different from machine to machine depending on OS, whether they've done a custom install etc.

Instead, you can simply refer to the file itself and the OS should just launch the file in the computer's default program for the file type:

```<code>from tkinter import filedialog
import os

filename = filedialog.askopenfilename(initialdir="C:/", title="select file")

os.system(filename)
</code>```

Additionally, the reason why you're getting that error is that when you're calling os.system(r"excel.exe" + filename) you're calling excel.exe[filename] without a space character.

This means that if you were trying to open, say, C:/excel.xls then you'd be calling excel.exeC:/excel.xls which isn't a valid command.

Title: Opening excel file with tkfiledialog

Body:
I have few code to open file in excel spreadsheet

filename = filedialog.askopenfilename(initialdir="C:/", title="select file",
                                          filetypes=(("excel files", "*.xls"), ("all files", "*.*")))

os.system(r"excel.exe" + filename)

when i select the file i want read i get the following error:

excel.exeC:' is not recognized as an internal or external command,
  operable program or batch file.

I tried to open with notepad wiht the os.system(r"notepad.exe" + filename) but i want to open it in excel using the excel.
I welcome your suggestion to open it in excel file.

Body:
You can specifically refer to the excel .exe file, however, you would need to use the full location and this can be different from machine to machine depending on OS, whether they've done a custom install etc.

Instead, you can simply refer to the file itself and the OS should just launch the file in the computer's default program for the file type:

from tkinter import filedialog
import os

filename = filedialog.askopenfilename(initialdir="C:/", title="select file")

os.system(filename)

Additionally, the reason why you're getting that error is that when you're calling os.system(r"excel.exe" + filename) you're calling excel.exe[filename] without a space character.

This means that if you were trying to open, say, C:/excel.xls then you'd be calling excel.exeC:/excel.xls which isn't a valid command.


问:
Jboss EAP 6.3 and Spring boot 1.5.2 - deployment starup issue with logback
Environment:
 - Spring Boot 1.5.2 (war)
 - java 1.7

 - jboss EAP 6.3

I am stuck with following error while running spring boot application war on jboss EAP:

Same issue listed here but did not mention what to do with Jboss EAP 6.3.

Appreciate your help!

17:48:22,682 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-13) MSC000001: Failed to start service jboss.deployment.unit."basp.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."basp.war".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment "basp.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:166) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1980) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1913) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:210)
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.deploy(ServletContainerInitializerDeploymentProcessor.java:131)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:159) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    ... 5 more
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:202)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: # See javax.servlet.ServletContainerInitializer javadocs from [Module "deployment.basp.war:main" from Service Module Loader]

    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:194)
    ... 7 more

Dependencies as following:

```<code><parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.7</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>

            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>

        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
    </dependency>
</dependencies>
</code>```

答:
It is caused by https://jira.qos.ch/browse/LOGBACK-1265.

You have to upgrade (or downgrade) logback.

Body:
Environment:
 - Spring Boot 1.5.2 (war)
 - java 1.7

 - jboss EAP 6.3

I am stuck with following error while running spring boot application war on jboss EAP:

Same issue listed here but did not mention what to do with Jboss EAP 6.3.

Appreciate your help!

17:48:22,682 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-13) MSC000001: Failed to start service jboss.deployment.unit."basp.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."basp.war".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment "basp.war"
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:166) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1980) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1913) [jboss-msc-1.1.5.Final-redhat-1.jar:1.1.5.Final-redhat-1]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_80]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_80]
    at java.lang.Thread.run(Thread.java:745) [rt.jar:1.7.0_80]
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:210)
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.deploy(ServletContainerInitializerDeploymentProcessor.java:131)
    at org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:159) [jboss-as-server-7.4.0.Final-redhat-19.jar:7.4.0.Final-redhat-19]
    ... 5 more
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: JBAS018104: Deployment error processing SCI for jar: logback-classic-1.1.11.jar
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:202)
    ... 7 more
Caused by: java.lang.ClassNotFoundException: # See javax.servlet.ServletContainerInitializer javadocs from [Module "deployment.basp.war:main" from Service Module Loader]

    at org.jboss.modules.ModuleClassLoader.findClass(ModuleClassLoader.java:213) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassUnchecked(ConcurrentClassLoader.java:459) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClassChecked(ConcurrentClassLoader.java:408) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.performLoadClass(ConcurrentClassLoader.java:389) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.modules.ConcurrentClassLoader.loadClass(ConcurrentClassLoader.java:134) [jboss-modules.jar:1.3.3.Final-redhat-1]
    at org.jboss.as.web.deployment.ServletContainerInitializerDeploymentProcessor.loadSci(ServletContainerInitializerDeploymentProcessor.java:194)
    ... 7 more

Dependencies as following:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
</parent>

<properties>
    <java.version>1.7</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.auth0</groupId>
        <artifactId>java-jwt</artifactId>
        <version>3.0.1</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>

            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>

        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>6.0</version>
    </dependency>
</dependencies>


问:
AngularJs WebAPI No HTTP resource was found
I'm developing an Angular app with WebAPI. When I call any method, i have the HTTP resource not found.
Angular call

```<code>service.Login = function (email, password, callback) {
        var Url = Constants.apiDevUrl + 'api/login/GetLoginByEmailPassword';

        $http.post(Url, JSON.stringify({ email: email, password: password })).then(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword:');
                console.log(error.config.url);
                console.log(error.data.Message);
                console.log(error.data.MessageDetail);
                console.log(error.status);
                console.log(error.statusText);
            });
    };
</code>```

Controller webAPI

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Esox_Elo_Calculator.API
{
    [RoutePrefix("api/login")]
    public class LoginController : ApiController
    {
        [Route("GetLoginByEmailPassword")]
        [HttpPost]
        public LoggedUser GetLoginByEmailPassword(string email, string password)
        {
            return new BOLogin().GetLoginByEmailPassword(email, password);
        }
    }
}
</code>```

WebApiConfig

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Esox_Elo_Calculator
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
            config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
            config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssK";

            config.Routes.Clear();
            config.Routes.MapHttpRoute(
                name: "api",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MapHttpAttributeRoutes();
        }

    }
}
</code>```

What is wrong? I think that the controllers name were the problem, but I changed without success. FYI, web.config is avaible here: https://pastebin.com/aGcEVgdS

答:
It seems, you miss the config.MapHttpAttributeRoutes(); configuration in WebApiConfig. This configuration is required when you would like to try with attribute routing.

In Web API, post action parameter retrieve data from FormBody and there at most one parameter allowed. So if you need more parameter value, you should declare an object and use that object as parameter.

So for your case, you need to create an object as

```<code>public class UserModel
{
    public string email { get; set; }
    public string password { get; set; }
}
</code>```

Then your controller action should be

```<code>    [Route("GetLoginByEmailPassword")]
    [HttpPost]
    public LoggedUser GetLoginByEmailPassword(UserModel user)
    {
        return new BOLogin().GetLoginByEmailPassword(user.email,
user.password);
    }
</code>```

Then your WebApiConfig configuration should be

```<code>        // Web API configuration and services
        config.Formatters.Remove(config.Formatters.XmlFormatter);

config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
Newtonsoft.Json.DateTimeZoneHandling.Local;

       config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling
= Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
        config.Formatters.JsonFormatter.SerializerSettings.DateFormatString
= "yyyy-MM-ddTHH:mm:ssK";

        config.Routes.Clear();
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
</code>```

Please make sure config.MapHttpAttributeRoutes(); will be placed before config.Routes.MapHttpRoute(......)

Then your post request send object instead of JSON.stringify.

```<code>    var data = { email: email, password: password };
    $http.post(Url, data).then(
        function (response) {
            var data = response.data
            callback(data);
        }).catch(function (error) {
            console.log('ERROR GetLoginByEmailPassword:');
            console.log(error.config.url);
            console.log(error.data.Message);
            console.log(error.data.MessageDetail);
            console.log(error.status);
            console.log(error.statusText);
        });
</code>```

Hope its working for you.

Body:
I'm developing an Angular app with WebAPI. When I call any method, i have the HTTP resource not found.
Angular call

service.Login = function (email, password, callback) {
        var Url = Constants.apiDevUrl + 'api/login/GetLoginByEmailPassword';

        $http.post(Url, JSON.stringify({ email: email, password: password })).then(
            function (response) {
                var data = response.data
                callback(data);
            }).catch(function (error) {
                console.log('ERROR GetLoginByEmailPassword:');
                console.log(error.config.url);
                console.log(error.data.Message);
                console.log(error.data.MessageDetail);
                console.log(error.status);
                console.log(error.statusText);
            });
    };

Controller webAPI

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Esox_Elo_Calculator.API
{
    [RoutePrefix("api/login")]
    public class LoginController : ApiController
    {
        [Route("GetLoginByEmailPassword")]
        [HttpPost]
        public LoggedUser GetLoginByEmailPassword(string email, string password)
        {
            return new BOLogin().GetLoginByEmailPassword(email, password);
        }
    }
}

WebApiConfig

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace Esox_Elo_Calculator
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
            config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
            config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssK";

            config.Routes.Clear();
            config.Routes.MapHttpRoute(
                name: "api",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.MapHttpAttributeRoutes();
        }

    }
}

What is wrong? I think that the controllers name were the problem, but I changed without success. FYI, web.config is avaible here: https://pastebin.com/aGcEVgdS

Body:
It seems, you miss the config.MapHttpAttributeRoutes(); configuration in WebApiConfig. This configuration is required when you would like to try with attribute routing.

In Web API, post action parameter retrieve data from FormBody and there at most one parameter allowed. So if you need more parameter value, you should declare an object and use that object as parameter.

So for your case, you need to create an object as

public class UserModel
{
    public string email { get; set; }
    public string password { get; set; }
}

Then your controller action should be

    [Route("GetLoginByEmailPassword")]
    [HttpPost]
    public LoggedUser GetLoginByEmailPassword(UserModel user)
    {
        return new BOLogin().GetLoginByEmailPassword(user.email,
user.password);
    }

Then your WebApiConfig configuration should be

        // Web API configuration and services
        config.Formatters.Remove(config.Formatters.XmlFormatter);

config.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling =
Newtonsoft.Json.DateTimeZoneHandling.Local;

       config.Formatters.JsonFormatter.SerializerSettings.DateFormatHandling
= Newtonsoft.Json.DateFormatHandling.IsoDateFormat;
        config.Formatters.JsonFormatter.SerializerSettings.DateFormatString
= "yyyy-MM-ddTHH:mm:ssK";

        config.Routes.Clear();
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "api",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

Please make sure config.MapHttpAttributeRoutes(); will be placed before config.Routes.MapHttpRoute(......)

Then your post request send object instead of JSON.stringify.

    var data = { email: email, password: password };
    $http.post(Url, data).then(
        function (response) {
            var data = response.data
            callback(data);
        }).catch(function (error) {
            console.log('ERROR GetLoginByEmailPassword:');
            console.log(error.config.url);
            console.log(error.data.Message);
            console.log(error.data.MessageDetail);
            console.log(error.status);
            console.log(error.statusText);
        });

Hope its working for you.


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
What about</p>

```<code>SELECT * FROM users, tags WHERE tags.user_id = users.user_id AND tags.name = 'tag1'
INTERSECT
SELECT * FROM users, tags WHERE tags.user_id = users.user_id AND tags.name = 'tag2'
</code>```

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
What about

SELECT * FROM users, tags WHERE tags.user_id = users.user_id AND tags.name = 'tag1'
INTERSECT
SELECT * FROM users, tags WHERE tags.user_id = users.user_id AND tags.name = 'tag2'


问:
how to remove star(*) from date as a Regex match Group T1 output
In below regex check and match groups, T1 output is *May 13 01:16:14.736.

I would like to remove start (*) from the output (May 13 01:16:14.736), whats change is required in Regex expression?

```<code>var input = @": *May 13 01:16:14.736 UTC: %XYZ";
        var regex = new Regex(@":\s+(?<T1>.*)UTC:\s%+(?<T2>.*)");
        //var regex = new Regex(@":\s*+(?<T1>.*)UTC:\s%+(?<T2>.*)");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine(match.Groups["T1"]);
            Console.WriteLine(match.Groups["T2"]);
        }
</code>```

I tried below expression, but getting exception,

```<code>var regex = new Regex(@":\s*+(?<T1>.*)UTC:\s%+(?<T2>.*)");
</code>```

Body:
In below regex check and match groups, T1 output is *May 13 01:16:14.736.

I would like to remove start (*) from the output (May 13 01:16:14.736), whats change is required in Regex expression?

var input = @": *May 13 01:16:14.736 UTC: %XYZ";
        var regex = new Regex(@":\s+(?<T1>.*)UTC:\s%+(?<T2>.*)");
        //var regex = new Regex(@":\s*+(?<T1>.*)UTC:\s%+(?<T2>.*)");
        var match = regex.Match(input);
        if (match.Success)
        {
            Console.WriteLine(match.Groups["T1"]);
            Console.WriteLine(match.Groups["T2"]);
        }

I tried below expression, but getting exception,

var regex = new Regex(@":\s*+(?<T1>.*)UTC:\s%+(?<T2>.*)");

Body:
:\s+\*(?<T1>.*)UTC:\s%+(?<T2>.*)

Take a look at the demo here...


问:
How to add an attachment to a test set in ALM OTA via c#?
I run the following code but nothing shows up in ALM:

```<code>AttachmentFactory attachmentFactory = (AttachmentFactory)tsTest.Attachments;
TDAPIOLELib.Attachment attachment = (TDAPIOLELib.Attachment)attachmentFactory.AddItem("test");
attachment.Post();
</code>```

The AddItem method on the second line keeps asking for "object ItemData" but I have no idea what that is exactly.  HP has such poor documentation that there is really nothing explaining it.   Does anyone know how to programatically using c# add a file attachment to a test run in HP ALM?

答:
If anyone is wondering how to do that on the requirement-module, here is the code:</p>

```<code>Req req = Globals.Connection.ReqFactory.Item(*ID*));
VersionControl versionControl = ((IVersionedEntity)req).VC as VersionControl;
versionControl.CheckOut(string.Empty);
AttachmentFactory attFac = req.Attachments;
Attachment att = (Attachment)attFac.AddItem(System.DBNull.Value);
att.Description = "*Your description here";
att.Type = (int)TDAPI_ATTACH_TYPE.TDATT_FILE; //for URL, change here
att.FileName = "*Your path including filename here*";
att.Post();
versionControl.CheckIn("*Your check-in comment here*");
</code>```

Body:
I run the following code but nothing shows up in ALM:

AttachmentFactory attachmentFactory = (AttachmentFactory)tsTest.Attachments;
TDAPIOLELib.Attachment attachment = (TDAPIOLELib.Attachment)attachmentFactory.AddItem("test");
attachment.Post();

The AddItem method on the second line keeps asking for "object ItemData" but I have no idea what that is exactly.  HP has such poor documentation that there is really nothing explaining it.   Does anyone know how to programatically using c# add a file attachment to a test run in HP ALM?

Body:
If anyone is wondering how to do that on the requirement-module, here is the code:

Req req = Globals.Connection.ReqFactory.Item(*ID*));
VersionControl versionControl = ((IVersionedEntity)req).VC as VersionControl;
versionControl.CheckOut(string.Empty);
AttachmentFactory attFac = req.Attachments;
Attachment att = (Attachment)attFac.AddItem(System.DBNull.Value);
att.Description = "*Your description here";
att.Type = (int)TDAPI_ATTACH_TYPE.TDATT_FILE; //for URL, change here
att.FileName = "*Your path including filename here*";
att.Post();
versionControl.CheckIn("*Your check-in comment here*");


问:
How to apply filters in Googlesheet API using Java
I have an API built along with Google Sheet API which interact with my google sheet and returns all the data. Is there a possible way to apply filter in google sheet and get only the data available to the filter(As like how we do filter in google sheet manually)?</p>

答:
You may check the following:

DataFilter that describes what data should be selected or returned from a request.

```<code>{
  // Union field filter can be only one of the following:
  "developerMetadataLookup": {
    object(DeveloperMetadataLookup)
  },
  "a1Range": string,
  "gridRange": {
    object(GridRange)
  },
  // End of list of possible types for union field filter.
}
</code>```

FilterCriteria for showing/hiding rows in a filter or filter view.

```<code>{
  "hiddenValues": [
    string
  ],
  "condition": {
    object(BooleanCondition)
  },
}
</code>```

PivotFilterCriteria for showing/hiding rows in a pivot table.

```<code>{
  "visibleValues": [
    string
  ],
}
</code>```

Hope this helps!

Body:
You may check the following:

DataFilter that describes what data should be selected or returned from a request.

{
  // Union field filter can be only one of the following:
  "developerMetadataLookup": {
    object(DeveloperMetadataLookup)
  },
  "a1Range": string,
  "gridRange": {
    object(GridRange)
  },
  // End of list of possible types for union field filter.
}

FilterCriteria for showing/hiding rows in a filter or filter view.

{
  "hiddenValues": [
    string
  ],
  "condition": {
    object(BooleanCondition)
  },
}

PivotFilterCriteria for showing/hiding rows in a pivot table.

{
  "visibleValues": [
    string
  ],
}

Hope this helps!


问:
Windows kernel driver for direct I/O - anyone been there?
I need to handle direct I/O to a parallel port in a better way that we are doing it at the moment - presently we use a kernel driver that 'opens up' useable addresses using the I/O protection map. This works ok but is getting more and more left behind. We still wish to continue using a parallel port and there are very satisfactory parallel port card vendors for CardBus ExpressCard etc. I'd like to create a driver that knew about the address assigned to the device by the bus enumerator and allowed me to write to this address from my (Delphi) app. Due to the appernt complexity of this topic I'm struggling with where to start. Has anyone been this route please?</p>

答:
You might try inoutp32.dll.
Please visit:

http://sheepdogguides.com/dt4j.htm

OwnerDisplayName: Brian Frost

ContentLicense: CC BY-SA 4.0

OwnerDisplayName: Michael


问:
mysql escaping single and double quotes
I have a script that i am writing to move certain fields to a new db like

```<code>$results = mysql_query ( "SELECT body, title  FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
    $insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
    mysql_query($insert);
    }
}
</code>```

but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something

```<code>INSERT INTO wp_posts (`body`,`title`)
            VALUES
                ('Here are the final returns from today's ...<br /><br />he stayed home...<br />
<div class="entry-content">
<div class="entry-body">', 'something')
</code>```

答:
The other option is to use mysqli and prepared statements

```<code>$stmt = $this->db->prepare("insert into table (id,name,longstring) values (?,?,?));
$stmt->bind_param('iss',$row["id"],$row["name"],$row["body"]);
$stmt->execute();
</code>```

mysqli will bind the assigned parameters to the ? in the prepared statement as an integer (i) or a string (s).

Title: mysql escaping single and double quotes

Body:
I have a script that i am writing to move certain fields to a new db like

$results = mysql_query ( "SELECT body, title  FROM $source_db.Post" );
while ($row = mysql_fetch_array($results)) {
if(mysql_num_rows($users_result) > 0){
    $insert = "INSERT INTO wp_posts (`body`,`title`) VALUES ('{$row['body']}', '{$row['row']}')";
    mysql_query($insert);
    }
}

but as you can see the query will break everytime due to the single and double quotes, is there a solution to this problem like herdok or something

INSERT INTO wp_posts (`body`,`title`)
            VALUES
                ('Here are the final returns from today's ...

he stayed home...

', 'something')

Body:
The other option is to use mysqli and prepared statements

$stmt = $this->db->prepare("insert into table (id,name,longstring) values (?,?,?));
$stmt->bind_param('iss',$row["id"],$row["name"],$row["body"]);
$stmt->execute();

mysqli will bind the assigned parameters to the ? in the prepared statement as an integer (i) or a string (s).


问:
Pixi js fill shape with a texture from canvas
I am trying to figure out a way I can fill a shape in PIXI.js using a texture created from a canvas.
The reason for this is I wanna be able to create a gradient on a normal html canvas, and they make a texture out of it and add it to the pixi stage. Now I can do that, that was the first thing I tested, it works. But the end goal is to create shapes in PIXI.js using the Graphics class and then fill them with my gradient. I do not know how to accomplish this, as the .beginFill() method only accepts a color. How do I fill a shape with a texture?
Here is my code. I know the auxillary canvas creation is a little verbose, but that is a problem for later.</p>

```<code>$(document).ready(function() {
    var stage = new PIXI.Container();
    var renderer = PIXI.autoDetectRenderer(800, 600);
    document.body.appendChild(renderer.view);

    //Aliases
    var Sprite = PIXI.Sprite;
    var TextureCache = PIXI.utils.TextureCache;
    var resources = PIXI. loader.resources;

    function AuxCanvas(id, w, h, color1, color2) {
        this.id = id;
        this.w = w;
        this.h = h;
        this.color1 = color1;
        this.color2 = color2;
    }
    // create and append the canvas to body
    AuxCanvas.prototype.create = function() {
        $('body').append('<canvas id="'+
            this.id+'"  width="'+
            this.w+'" height="'+
            this.h+'"></canvas>');
    }
    // draw gradient
    AuxCanvas.prototype.drawGradient = function() {
        var canvas = document.getElementById(this.id);
        var ctx = canvas.getContext('2d');
        var gradient = ctx.createLinearGradient(0, 0, 800, 0);
        gradient.addColorStop(0, this.color1);
        gradient.addColorStop(1, this.color2);
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, this.w, this.h);
    }

    function setup() {

        var graphics = new PIXI.Graphics();
        graphics.beginFill(PIXI.Texture.fromCanvas(can1)); //This doesn't work obviously
        graphics.drawCircle(60, 185, 40);
        graphics.endFill();
        stage.addChild(graphics);
        renderer.render(stage);
    }

    var can1 = new AuxCanvas("can1", 800, 600, "green", "yellow");
    can1.create();
    can1.drawGradient();

    var can2 = new AuxCanvas("can2", 800, 600, "blue", "red");
    can2.create();
    can2.drawGradient();

    setup();
})
</code>```

答:
Allright I figured out a way, actually it was easy.
Just make the Graphics object a mask for the sprite created from the html canvas.

```<code>function setup() {
    var can2 = document.getElementById('can2');
    var sprite = new Sprite(PIXI.Texture.fromCanvas(can2))
    var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(300, 300, 200);
    graphics.endFill();
    sprite.mask = graphics;
    stage.addChild(sprite);
    renderer.render(stage);
}
</code>```

Moreover, appending the graphic as a child of the sprite is the best way to go, just need to make sure that they are the same dimentions. With this done, I can move the sprite freely, and it's gradient texture doesn't change, or more precisely, it moves with the sprite. Of course everything has to be equal in dimentions.

```<code>var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(100, 100, 100);
    graphics.endFill();
    sprite.addChild(graphics);
    sprite.mask = graphics;
</code>```

Body:
I am trying to figure out a way I can fill a shape in PIXI.js using a texture created from a canvas.
The reason for this is I wanna be able to create a gradient on a normal html canvas, and they make a texture out of it and add it to the pixi stage. Now I can do that, that was the first thing I tested, it works. But the end goal is to create shapes in PIXI.js using the Graphics class and then fill them with my gradient. I do not know how to accomplish this, as the .beginFill() method only accepts a color. How do I fill a shape with a texture?
Here is my code. I know the auxillary canvas creation is a little verbose, but that is a problem for later.

$(document).ready(function() {
    var stage = new PIXI.Container();
    var renderer = PIXI.autoDetectRenderer(800, 600);
    document.body.appendChild(renderer.view);

    //Aliases
    var Sprite = PIXI.Sprite;
    var TextureCache = PIXI.utils.TextureCache;
    var resources = PIXI. loader.resources;

    function AuxCanvas(id, w, h, color1, color2) {
        this.id = id;
        this.w = w;
        this.h = h;
        this.color1 = color1;
        this.color2 = color2;
    }
    // create and append the canvas to body
    AuxCanvas.prototype.create = function() {
        $('body').append('<canvas id="'+
            this.id+'"  width="'+
            this.w+'" height="'+
            this.h+'"></canvas>');
    }
    // draw gradient
    AuxCanvas.prototype.drawGradient = function() {
        var canvas = document.getElementById(this.id);
        var ctx = canvas.getContext('2d');
        var gradient = ctx.createLinearGradient(0, 0, 800, 0);
        gradient.addColorStop(0, this.color1);
        gradient.addColorStop(1, this.color2);
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, this.w, this.h);
    }

    function setup() {

        var graphics = new PIXI.Graphics();
        graphics.beginFill(PIXI.Texture.fromCanvas(can1)); //This doesn't work obviously
        graphics.drawCircle(60, 185, 40);
        graphics.endFill();
        stage.addChild(graphics);
        renderer.render(stage);
    }

    var can1 = new AuxCanvas("can1", 800, 600, "green", "yellow");
    can1.create();
    can1.drawGradient();

    var can2 = new AuxCanvas("can2", 800, 600, "blue", "red");
    can2.create();
    can2.drawGradient();

    setup();
})

Body:
Allright I figured out a way, actually it was easy.
Just make the Graphics object a mask for the sprite created from the html canvas.

function setup() {
    var can2 = document.getElementById('can2');
    var sprite = new Sprite(PIXI.Texture.fromCanvas(can2))
    var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(300, 300, 200);
    graphics.endFill();
    sprite.mask = graphics;
    stage.addChild(sprite);
    renderer.render(stage);
}

Moreover, appending the graphic as a child of the sprite is the best way to go, just need to make sure that they are the same dimentions. With this done, I can move the sprite freely, and it's gradient texture doesn't change, or more precisely, it moves with the sprite. Of course everything has to be equal in dimentions.

var graphics = new PIXI.Graphics();
    graphics.beginFill();
    graphics.drawCircle(100, 100, 100);
    graphics.endFill();
    sprite.addChild(graphics);
    sprite.mask = graphics;


问:
Cannot instantiate: unexpected 'class_name' (T_STRING)
I'm trying this script on PHP 7.0, but I cannot instantiate. I've reviewed time after time, but I cannot figure out where is the error. Please could you help me?</p>

```<code><?php
class MiClase
{
    public $var1 = 'Publica';
    protected $var2 = 'Protegida';
    private $var3 = 'Privada';

    public function imprimir()
    {
        echo "Funcion Imprimir:<br>";
        echo $this->var1 . "<br/>";
        echo $this->var2 . "<br/>";
        echo $this->var3 . "<br/>";
        echo "---------------<br/>";
    }
}

$miclase = $new MiClase();
$miclase->imprimir();
echo "var1: ".$miclase->var1 . "<br/>";
echo "var2: ".$miclase->var2 . "<br/>";
echo "var3: ".$miclase->var3 . "<br/>";
</code>```

答:
You have to use New keyword to instantiate class with out  dollar sign please follow the below code:

```<code>$miclase = new MiClase();
</code>```

instead of

```<code>$miclase = $new MiClase();
</code>```

Body:
I'm trying this script on PHP 7.0, but I cannot instantiate. I've reviewed time after time, but I cannot figure out where is the error. Please could you help me?

<?php
class MiClase
{
    public $var1 = 'Publica';
    protected $var2 = 'Protegida';
    private $var3 = 'Privada';

    public function imprimir()
    {
        echo "Funcion Imprimir:
";
        echo $this->var1 . "
";
        echo $this->var2 . "
";
        echo $this->var3 . "
";
        echo "---------------
";
    }
}

$miclase = $new MiClase();
$miclase->imprimir();
echo "var1: ".$miclase->var1 . "
";
echo "var2: ".$miclase->var2 . "
";
echo "var3: ".$miclase->var3 . "
";

Body:
You have to use New keyword to instantiate class with out  dollar sign please follow the below code:

$miclase = new MiClase();

instead of

$miclase = $new MiClase();


问:
Enter triggers button click
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

```<code>$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})
</code>```

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.

答: I would do it like the following: In the handler for the onclick event of the button (not submit) check the event object's keycode. If it is "enter" I would return false.</p>

Title: Enter triggers button click

Body:
I have a page with two buttons. One is a <button> element and the other is a <input type="submit">. The buttons appear on the page in that order. If I'm in a text field anywhere in the form and press <Enter>, the button element's click event is triggered. I assume that's because the button element sits first.

I can't find anything that looks like a reliable way of setting the default button, nor do I necessarily want to at this point. In the absence of anything better, I've captured a keypress anywhere on the form and, if it was the <Enter> key that was pressed, I'm just negating it:

$('form').keypress( function( e ) {
  var code = e.keyCode || e.which;

  if( code === 13 ) {
    e.preventDefault();
    return false;
  }
})

As far as I can tell so far, it seems to be working, but it feels incredibly ham-fisted.

Does anyone know of a more sophisticated technique for doing this?

Similarly, are there any pitfalls to this solution that I'm just not aware of?

Thanks.


问:
Filter on generic types

I'm trying to write a function using TypeScript that will allow me to filter a list of objects depending on their type. The result should be a function that will allow me to do either:

```<code>filter<Foo>(items);
</code>```

or

```<code>filter(items, Foo);
</code>```

I've been trying to do it in the following way:

```<code>class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = <T extends Foo>(items: any[], typeT: T): T[] => {
    return items.filter(item => item instanceof typeT)
};

console.log(filter(items, Foo));
</code>```

But this doesn't work.

How can I make this work?

TypeScript example

答:
When you pass in the type you are actually passing in the constructor of the class. Your signature is passing in an instance of T. You should try:

```<code>const filter = <T extends Foo>(items: any[], typeT: new (...params : any[]) => T): T[] => {
    return items.filter(item => item instanceof typeT)
};
</code>```

Note: In your example all the items in the array will pass the filter, because Bar is derived from Foo and thus is also an instance of Foo. If you want only object of type Foo and not derived, you could use item.constructor == typeT

Title: Filter on generic types

Body:
I'm trying to write a function using TypeScript that will allow me to filter a list of objects depending on their type. The result should be a function that will allow me to do either:

filter<Foo>(items);

or

filter(items, Foo);

I've been trying to do it in the following way:

class Foo {
    public constructor(public name: string, public type: string) {

    }
}

class Bar extends Foo { }

const items: Foo[] = [
    new Foo('Foo', 'A'),
    new Bar('bar', 'A'),
    new Foo('baz', 'B'),
];

const filter = <T extends Foo>(items: any[], typeT: T): T[] => {
    return items.filter(item => item instanceof typeT)
};

console.log(filter(items, Foo));

But this doesn't work.

How can I make this work?

<a href="https://www.typescriptlang.org/play/#src=class%20Foo%20%7B%0D%0A%20%20%20%20public%20constructor(public%20name%3A%20string%2C%20public%20type%3A%20string)%20%7B%0D%0A%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aclass%20Bar%20extends%20Foo%20%7B%20%7D%0D%0A%0D%0Aconst%20items%3A%20Foo%5B%5D%20%3D%20%5B%0D%0A%20%20%20%20new%20Foo('Foo'%2C%20'A')%2C%0D%0A%20%20%20%20new%20Bar('bar'%2C%20'A')%2C%0D%0A%20%20%20%20new%20Foo('baz'%2C%20'B')%2C%0D%0A%5D%3B%0D%0A%0D%0Aconst%20filter%20%3D%20%3CT%20extends%20Foo%3E(items%3A%20any%5B%5D%2C%20typeT%3A%20T)%3A%20T%5B%5D%20%3D%3E%20%7B%0D%0A%20%20%20%20return%20items.filter(item%20%3D%3E%20item%20instanceof%20typeT)%0D%0A%7D%3B%0D%0A%0D%0Aconsole.log(filter(items%2C%20Foo))%3B" rel="noreferrer">TypeScript example

Body:
When you pass in the type you are actually passing in the constructor of the class. Your signature is passing in an instance of T. You should try:

const filter = <T extends Foo>(items: any[], typeT: new (...params : any[]) => T): T[] => {
    return items.filter(item => item instanceof typeT)
};

Note: In your example all the items in the array will pass the filter, because Bar is derived from Foo and thus is also an instance of Foo. If you want only object of type Foo and not derived, you could use item.constructor == typeT


问:
Syntax for JSTL Ternary with variable
I am trying to figure out the proper syntax for using ternary in JSTL.

The following is what I have

```<code>value="${(contains == 'false' && facultyMember eq true) ? '${prepTime}' : ''}"/>
</code>```

However when this evaluates to true it does not give the $prepTime variable like I want.

I tried taking the single quotes out from around the variable name like so

```<code>value="${(contains == 'false' && facultyMember eq true) ? ${prepTime} : ''}"/>
</code>```

however this is also not correct.

any help is appreciated.

thanks

答:
Change ${prepTime} to prepTime

```<code>value="${((contains == 'false') && (facultyMember eq true)) ? prepTime : ''}"/>
</code>```

Title: Syntax for JSTL Ternary with variable

Body:
I am trying to figure out the proper syntax for using ternary in JSTL.

The following is what I have

value="${(contains == 'false' && facultyMember eq true) ? '${prepTime}' : ''}"/>

However when this evaluates to true it does not give the $prepTime variable like I want.

I tried taking the single quotes out from around the variable name like so

value="${(contains == 'false' && facultyMember eq true) ? ${prepTime} : ''}"/>

however this is also not correct.

any help is appreciated.

thanks

Body:
Change ${prepTime} to prepTime

value="${((contains == 'false') && (facultyMember eq true)) ? prepTime : ''}"/>