问:
Why is (TypeError: 'str' object cannot be interpreted as an integer) appearing on my reminder system
After much work on my mini assistant, I have come across a large bug I can't fix in the reminder system. Where, after asking for a reminder, it crashes. Its meant to store it in a variable and a notepad file, to be used after the time (set by minutes) runs out. Sorry for any jumbled up code and showing the entire code, I can't pinpoint where the code goes wrong. The code is for python 3.4

Code

```<code>#import win32com.client as wincl
import webbrowser, os, datetime, time, re
#speak = wincl.Dispatch("SAPI.SpVoice")
global speech
speech=1
print("I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy")
reminderTime=[]
reminderMessage=[]

def writeFile(timestamp,message):
    f=open("reminders.txt","a")
    f.write(str(timestamp))
    f.write(",")
    f.write(message)
    f.write(",")
    f.close()

def loadFile():
    f=open("reminders.txt","r")
    f=f.read()
    timestamp=""
    for i in range (len(f)):
        if f[i]==",":
            if timestamp.isdigit()==True:
                reminderTime.append(int(timestamp))
                timestamp=""
            else:
                reminderMessage.append(timestamp)
                timestamp=""
        else:
            timestamp=timestamp+f[i]
    print(timestamp)

loadFile()
def unixToTime(UnixTime):
    return datetime.datetime.fromtimestamp(int(UnixTime)).strftime('%Y-%m-%d %H:%M:%S')

def readReminders(reminderTime,reminderMessage):
    for i in range (len(reminderTime)):
        if reminderTime[i]<time.time():
            print("Im reminding you that: ",reminderMessage[i], " at ",unixToTime(reminderTime[i]))
            reminderTime.pop(i)
            reminderMessage.pop(i)

def analyse(user_input):
    global speech
    ui_lower = user_input.lower()
    #conversation
    if ui_lower in ["hi", "hello"]:
        r = "Hello"
elif all(x in ui_lower for x in ("who", "you")):
    r = "I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or... bonzi buddy"

elif all(x in ui_lower for x in ("how","are","you")):
    r = "I'm Ok"

elif all(x in ui_lower for x in ("what","favorite","color")):
    r = "I like Green"

elif all(x in ui_lower for x in ("what","favorite","food")):
    r = "I am a computer program, I do not eat"

elif all(x in ui_lower for x in ("are","we","friend")):
    r = "Yes, we are friends"

elif all(x in ui_lower for x in ("we","are","friend")):
    r = "why thank you"

elif all(x in ui_lower for x in ("you","not","friend")):
    r = "Gasp how could you"

elif all(x in ui_lower for x in ("i","dont","hate","you")):
    r = "ok umm thanks"

elif all(x in ui_lower for x in ("cortana", "better")):
    r = "that is true"

elif all(x in ui_lower for x in ("i","hate","you")):
    r = "Why must you be so cruel"

#functions
elif all(x in ui_lower for x in ("speech","off")):
    speech=0
    r = "ok"

elif all(x in ui_lower for x in ("speech","on")):
    speech=1
    r = "ok"

elif all(x in ui_lower for x in ("search")):
    url="https://www.google.co.uk/search?safe=strict&site=&source=hp&q="+ui_lower[6:]+"&oq=test+search&gs_l=hp.3..0l10.46616.51804.0.52437.23.17.4.2.2.0.148.1449.13j3.16.0....0...1c.1.64.hp..1.19.1245.0..35i39k1j0i131k1j0i67k1j0i20k1j0i10i67k1.WktWginLj04"
    webbrowser.open_new(url)
    r = "ok"

elif all(x in ui_lower for x in ("open")):
    os.system("start "+str(ui_lower)[5:])
    r = "Opening"

#Reminders
elif all(x in ui_lower for x in ("remind")):
    mins=str(re.findall(r' +[0-9]+ ', ui_lower))[3:-3]
    message=ui_lower[8+len(mins):]
    reminderMessage.append(message)
    reminderTime.append(round(time.time()+(int(mins)*60)))
    #print(reminder)
    mins = str(mins)
    writeFile(round(time.time()+(int(mins)*60),message))
    r = "reminder saved"
else:
    r = "I'm unable to comply"

if speech==1:
    #speak.Speak(r)
    return r
running=1
while running==1:
    user_input=[""]
    user_input[0] = input(">>> ")
    for s in (user_input):
        if user_input[0].lower()=="end":
            print("A: Goodbye")
            running=0
            break
        readReminders(reminderTime,reminderMessage)
        print("Q: {}".format(s))
        print("{}".format(analyse(s)))
</code>```

Interpreter

```<code>    I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy

>>> remind 1 hi
Im reminding you that:  test  at  2017-05-26 13:58:31
Q: remind 1 hi
Traceback (most recent call last):
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 127, in <module>
    print("{}".format(analyse(s)))
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 108, in analyse
    writeFile(round(time.time()+(int(mins)*60),message))
TypeError: 'str' object cannot be interpreted as an integer
>>>
</code>```

Any answers will be helpful, even with the layout of the code

Body:
After much work on my mini assistant, I have come across a large bug I can't fix in the reminder system. Where, after asking for a reminder, it crashes. Its meant to store it in a variable and a notepad file, to be used after the time (set by minutes) runs out. Sorry for any jumbled up code and showing the entire code, I can't pinpoint where the code goes wrong. The code is for python 3.4

Code

#import win32com.client as wincl
import webbrowser, os, datetime, time, re
#speak = wincl.Dispatch("SAPI.SpVoice")
global speech
speech=1
print("I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy")
reminderTime=[]
reminderMessage=[]

def writeFile(timestamp,message):
    f=open("reminders.txt","a")
    f.write(str(timestamp))
    f.write(",")
    f.write(message)
    f.write(",")
    f.close()

def loadFile():
    f=open("reminders.txt","r")
    f=f.read()
    timestamp=""
    for i in range (len(f)):
        if f[i]==",":
            if timestamp.isdigit()==True:
                reminderTime.append(int(timestamp))
                timestamp=""
            else:
                reminderMessage.append(timestamp)
                timestamp=""
        else:
            timestamp=timestamp+f[i]
    print(timestamp)

loadFile()
def unixToTime(UnixTime):
    return datetime.datetime.fromtimestamp(int(UnixTime)).strftime('%Y-%m-%d %H:%M:%S')

def readReminders(reminderTime,reminderMessage):
    for i in range (len(reminderTime)):
        if reminderTime[i]<time.time():
            print("Im reminding you that: ",reminderMessage[i], " at ",unixToTime(reminderTime[i]))
            reminderTime.pop(i)
            reminderMessage.pop(i)

def analyse(user_input):
    global speech
    ui_lower = user_input.lower()
    #conversation
    if ui_lower in ["hi", "hello"]:
        r = "Hello"
elif all(x in ui_lower for x in ("who", "you")):
    r = "I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or... bonzi buddy"

elif all(x in ui_lower for x in ("how","are","you")):
    r = "I'm Ok"

elif all(x in ui_lower for x in ("what","favorite","color")):
    r = "I like Green"

elif all(x in ui_lower for x in ("what","favorite","food")):
    r = "I am a computer program, I do not eat"

elif all(x in ui_lower for x in ("are","we","friend")):
    r = "Yes, we are friends"

elif all(x in ui_lower for x in ("we","are","friend")):
    r = "why thank you"

elif all(x in ui_lower for x in ("you","not","friend")):
    r = "Gasp how could you"

elif all(x in ui_lower for x in ("i","dont","hate","you")):
    r = "ok umm thanks"

elif all(x in ui_lower for x in ("cortana", "better")):
    r = "that is true"

elif all(x in ui_lower for x in ("i","hate","you")):
    r = "Why must you be so cruel"

#functions
elif all(x in ui_lower for x in ("speech","off")):
    speech=0
    r = "ok"

elif all(x in ui_lower for x in ("speech","on")):
    speech=1
    r = "ok"

elif all(x in ui_lower for x in ("search")):
    url="https://www.google.co.uk/search?safe=strict&site=&source=hp&q="+ui_lower[6:]+"&oq=test+search&gs_l=hp.3..0l10.46616.51804.0.52437.23.17.4.2.2.0.148.1449.13j3.16.0....0...1c.1.64.hp..1.19.1245.0..35i39k1j0i131k1j0i67k1j0i20k1j0i10i67k1.WktWginLj04"
    webbrowser.open_new(url)
    r = "ok"

elif all(x in ui_lower for x in ("open")):
    os.system("start "+str(ui_lower)[5:])
    r = "Opening"

#Reminders
elif all(x in ui_lower for x in ("remind")):
    mins=str(re.findall(r' +[0-9]+ ', ui_lower))[3:-3]
    message=ui_lower[8+len(mins):]
    reminderMessage.append(message)
    reminderTime.append(round(time.time()+(int(mins)*60)))
    #print(reminder)
    mins = str(mins)
    writeFile(round(time.time()+(int(mins)*60),message))
    r = "reminder saved"
else:
    r = "I'm unable to comply"

if speech==1:
    #speak.Speak(r)
    return r
running=1
while running==1:
    user_input=[""]
    user_input[0] = input(">>> ")
    for s in (user_input):
        if user_input[0].lower()=="end":
            print("A: Goodbye")
            running=0
            break
        readReminders(reminderTime,reminderMessage)
        print("Q: {}".format(s))
        print("{}".format(analyse(s)))

Interpreter

    I am Squeep Bot, my current purpose is to have meaningless conversations with you or search the internet, like siri, cortana, or bonzi buddy

>>> remind 1 hi
Im reminding you that:  test  at  2017-05-26 13:58:31
Q: remind 1 hi
Traceback (most recent call last):
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 127, in <module>
    print("{}".format(analyse(s)))
  File "U:\My Documents\py scripter\Squeepbot\Squeepbot.py", line 108, in analyse
    writeFile(round(time.time()+(int(mins)*60),message))
TypeError: 'str' object cannot be interpreted as an integer
>>>

Any answers will be helpful, even with the layout of the code

Body: writeFile(round(time.time()+(int(mins)*60)),message)


来源: stackexchange

问:
Angular 2 unable to load images when ng build dist folder( renamed to myapp) is deployed in tomcat webapp folder
I'm passing the relative path, and using the following command to build!

```<code>ng build --prod --aot --base-href /myapp/
</code>```

I get the below error 404 Resource not found error.

```<code>bkgraph.jpeg:1 GET http://localhost:8081/assets/bkgraph.jpeg 404 ()

  <img src="../../assets/bkgraph.jpeg" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail">
</code>```

答: To load the images you need to remove the '../../' before the assets. it should be  like this in the tomcat server.

ContentLicense: CC BY-SA 3.0

Body:
I'm passing the relative path, and using the following command to build!

ng build --prod --aot --base-href /myapp/

I get the below error 404 Resource not found error.

bkgraph.jpeg:1 GET http://localhost:8081/assets/bkgraph.jpeg 404 ()

Body: To load the images you need to remove the '../../' before the assets. it should be <img src="assets/bkgraph.jpeg" width="200" height="200" class="img-responsive" alt="Generic placeholder thumbnail"> like this in the tomcat server.


问:
Excel VBA: Merging a range inside a loop

I want to merge that repeating Chapters into just one cell by Chapter.

Here is how my code does the looping.

```<code>        Dim label As Control
        Dim itm As Object
        For ctr = 1 To InfoForm.Chapter.ListCount - 1
            For Each label In InfoForm.Controls
                If TypeName(label) = "Label" Then
                    With ActiveSheet
                        i = i + 1

                        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                        lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                        If label <> "Chapter" Then
                            .Cells(lastColumn, i).Value = "Chapter " & ctr

                            .Cells(lastRow, i).Value = label.Caption
                        End If
                    End With
                End If
            Next
        Next
</code>```

I've tried merging it like this

```<code>.Range(Cells(1, lastColumn), Cells(1,i)).Merge
</code>```

But it merges all the repeating chapters into one cell instead

Expected Result:

答:
If you know the ranges before hand then you could adjust the code below. I've created this by recording a macro and then disabling/enabling alerts as appropriate. I've included a function to convert integer column values to alph equivalents.The MainLoop Intcol1 and intcol2 would be values that you would provide based on the input from the original Form.

```<code>Sub MainLoop()
 Dim StrMycol_1 As String
 Dim StrMycol_2 As String
 Dim intcol1 As Integer
 Dim intcol2 As Integer

  intcol1 = 5: intcol2 = 7

  StrMycol_1 = WColNm(intcol1) ' mycell.column is numeric. Function returns integer
  StrMycol_2 = WColNm(intcol2) ' mycell.column is numeric. Function returns integer
'
  do_merge_centre StrMycol_1, StrMycol_2
End Sub

Sub do_merge_centre(col1, col2)
Range(col1 + "1:" + col2 + "1").Select
Application.DisplayAlerts = False
With Selection
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With
Selection.Merge
Application.DisplayAlerts = True
End Sub
'
Public Function WColNm(ColNum) As String
    WColNm = Split(Cells(1, ColNum).Address, "$")(1)
End Function
</code>```

Body:
I want to merge that repeating Chapters into just one cell by Chapter.

Here is how my code does the looping.

        Dim label As Control
        Dim itm As Object
        For ctr = 1 To InfoForm.Chapter.ListCount - 1
            For Each label In InfoForm.Controls
                If TypeName(label) = "Label" Then
                    With ActiveSheet
                        i = i + 1

                        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                        lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                        If label <> "Chapter" Then
                            .Cells(lastColumn, i).Value = "Chapter " & ctr

                            .Cells(lastRow, i).Value = label.Caption
                        End If
                    End With
                End If
            Next
        Next

I've tried merging it like this

.Range(Cells(1, lastColumn), Cells(1,i)).Merge

But it merges all the repeating chapters into one cell instead

Expected Result:

Body:
If you know the ranges before hand then you could adjust the code below. I've created this by recording a macro and then disabling/enabling alerts as appropriate. I've included a function to convert integer column values to alph equivalents.The MainLoop Intcol1 and intcol2 would be values that you would provide based on the input from the original Form.

Sub MainLoop()
 Dim StrMycol_1 As String
 Dim StrMycol_2 As String
 Dim intcol1 As Integer
 Dim intcol2 As Integer

  intcol1 = 5: intcol2 = 7

  StrMycol_1 = WColNm(intcol1) ' mycell.column is numeric. Function returns integer
  StrMycol_2 = WColNm(intcol2) ' mycell.column is numeric. Function returns integer
'
  do_merge_centre StrMycol_1, StrMycol_2
End Sub

Sub do_merge_centre(col1, col2)
Range(col1 + "1:" + col2 + "1").Select
Application.DisplayAlerts = False
With Selection
    .HorizontalAlignment = xlCenter
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = False
End With
Selection.Merge
Application.DisplayAlerts = True
End Sub
'
Public Function WColNm(ColNum) As String
    WColNm = Split(Cells(1, ColNum).Address, "$")(1)
End Function


问:
Formatting date-Time in Thymeleaf "HH:mm"
I need to use a format mask but I can only use DATE type 'dd-MMM-yyyy' but I need time format 'HH: mm'   .

```<code>//ENTITY DateTimeFormat annotation on the method that's calling the DB to get date-time.
@Entity
@Table(name="horario")
public class Horario implements Serializable {} ....

@NotNull
@Column(name = "duracao")
@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern ="HH:mm")
private Date duracao;

@NotNull
@Column(name ="hora_inicial")
@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern = "HH:mm")
private Date horaInicial;

@NotNull
@Column(name ="hora_final")
@Temporal(value = TemporalType.TIME )
@DateTimeFormat(pattern = "HH:mm")
private Date horaFinal;
</code>```

And made dynamic with thymeleaf

I think thymeleaf does not interact well with javascript equal angular

```<code>//HTML
 <div class="form-group" th:each="horarios, rowStat : *{horarios}" th:if="${rowStat.index} < 5">
                                <div class="col-sm-4 col-md-4 col-4">
                                    <div class="form-group"
                                         th:classappend="${#fields.hasErrors('horarios[__${rowStat.index}__].duracao')} ? has-error">
                                        <label class="control-label required" th:text="#{mensagem.duracao}">Duração</label>
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="fa fa-clock-o"></i>
                                            </span>
                                            <input type="text" class="form-control" th:id="duracao+${rowStat.index}" th:field="*{{horarios[__${rowStat.index}__].duracao}}"
   I'm starting with this div,
once it's resolved, I've moved on to the others-------------> th:value="${#dates.format(horarios.duracao, 'HH:mm')}" />
                                        </div>
                                        <label class="error" th:if="${#fields.hasErrors('horarios[__${rowStat.index}__].duracao')}"
                                               th:errors="*{horarios[__${rowStat.index}__].duracao}"></label>
                                    </div>
                                </div>

                                <div class="col-sm-4 col-md-4 col-4">
                                    <div class="form-group"
                                         th:classappend="${#fields.hasErrors('horarios[__${rowStat.index}__].horaInicial')} ? has-error">
                                        <label class="control-label required"
                                               th:text="#{mensagem.horaInicial}">horaInicial</label>
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                    <i class="fa fa-clock-o"></i>
                                                </span>
                                            <input type="text" class="form-control" th:id="horaInicial+${rowStat.index}"
                                                   th:field="*{horarios[__${rowStat.index}__].horaInicial}"
                                                  />
                                        </div>
                                        <label class="error" th:if="${#fields.hasErrors('horarios[__${rowStat.index}__].horaInicial')}"
                                               th:errors="*{horarios[__${rowStat.index}__].horaInicial}"></label>
                                    </div>
                                </div>

                                <div class="col-sm-3 col-md-3 col-3">
                                    <div class="form-group"
                                         th:classappend="${#fields.hasErrors('horarios[__${rowStat.index}__].horaFinal')} ? has-error">
                                        <label class="control-label required"
                                               th:text="#{mensagem.horaFinal}">horaFinal</label>
                                        <div class="input-group">
                                            <span class="input-group-addon">
                                                <i class="fa fa-clock-o"></i>
                                            </span>
                                                <input type="text" class="form-control" th:id="horaFinal"
                                                       th:field="*{horarios[__${rowStat.index}__].horaFinal}" readonly="readonly"/>
                                        </div>
                                        <label class="error" th:if="${#fields.hasErrors('horarios[__${rowStat.index}__].horaFinal')}"
                                               th:errors="*{horarios[__${rowStat.index}__].horaFinal}"></label>
                                    </div>
                                </div>
                                <div clas="col-sm-1">
                                    <button class="btn btn-danger padding-buttons" type="submit" name="removeRow" th:value="${rowStat.index}" th:if="${rowStat.index} ge 0 and ${#lists.size(horarioAula.horarios) ne 1}">
                                        <i class="fa fa-minus" style="color:white;"></i>
                                    </button>

                                </div>
                        </div>
</code>```

My return is this
enter image description here

答:
To make use @DateTimeFormat annotation, try to use double brackets syntax:

```<code>th:value="${{horarios.duracao}}"
</code>```

Alternatively you can use th:field attribute and this conversion will occur automatically.

Related documentation: http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#double-brace-syntax

Body:
I need to use a format mask but I can only use DATE type 'dd-MMM-yyyy' but I need time format 'HH: mm'   .

//ENTITY DateTimeFormat annotation on the method that's calling the DB to get date-time.
@Entity
@Table(name="horario")
public class Horario implements Serializable {} ....

@NotNull
@Column(name = "duracao")
@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern ="HH:mm")
private Date duracao;

@NotNull
@Column(name ="hora_inicial")
@Temporal(TemporalType.TIME)
@DateTimeFormat(pattern = "HH:mm")
private Date horaInicial;

@NotNull
@Column(name ="hora_final")
@Temporal(value = TemporalType.TIME )
@DateTimeFormat(pattern = "HH:mm")
private Date horaFinal;

And made dynamic with thymeleaf

I think thymeleaf does not interact well with javascript equal angular

//HTML
 <div class="form-group" th:each="horarios, rowStat : *{horarios}" th:if="${rowStat.index} < 5">

                                        Duração

                                            <input type="text" class="form-control" th:id="duracao+${rowStat.index}" th:field="*{{horarios[__${rowStat.index}__].duracao}}"
   I'm starting with this div,
once it's resolved, I've moved on to the others-------------> th:value="${#dates.format(horarios.duracao, 'HH:mm')}" />

                                        horaInicial

                                            <input type="text" class="form-control" th:id="horaInicial+${rowStat.index}"
                                                   th:field="*{horarios[__${rowStat.index}__].horaInicial}"
                                                  />

                                        horaFinal

                                                <input type="text" class="form-control" th:id="horaFinal"
                                                       th:field="*{horarios[__${rowStat.index}__].horaFinal}" readonly="readonly"/>

                                    <button class="btn btn-danger padding-buttons" type="submit" name="removeRow" th:value="${rowStat.index}" th:if="${rowStat.index} ge 0 and ${#lists.size(horarioAula.horarios) ne 1}">

                                    </button>

My return is this
enter image description here

Body:
To make use @DateTimeFormat annotation, try to use double brackets syntax:

th:value="${{horarios.duracao}}"

Alternatively you can use th:field attribute and this conversion will occur automatically.

Related documentation: http://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html#double-brace-syntax


问:
TypeError: Cannot use 'in' operator to search for 'ch' in hi
In angular 1.6, passing actions up (from a presentational component to a controller component), I got stocked on this:

Chat (Controller component)

```<code>const Chat = ['messages', function (ms) {
    ...
    this.sendMessage = (userInput) => {
        ms.sendMessage(userInput)
            .then((res) => {
                console.log(res)
            })
    }
}]
</code>```

Html Template:

```<code><div class="messages">
    <conversation messages="ch.messages" ng-if="ch.messages" ></conversation>
    <user-input send="ch.sendMessage(userInput)"></user-input>
</div>
</code>```

UserInput Component (Presentational component):

```<code>const UserInput = function () {
    ...
    this.checkAndSend = () => {
        this.send(this.input)
        this.input = this._clear()
    }
}

angular
    .module('chatbot-andrea')
    .component('userInput', {
        bindings: {
            send: '&'
        },
        ...
    })
</code>```

答:
I was making a terrible mistake, as velesin.io explains

"This is because the '&' binding is not really a callback function but
  an expressions, and the title and description are not function
  parameters but variables visible in the scope of the expression
  context"

So using,

```<code>this.send(this.input)
</code>```

never would not work. Instead of that you have to use:

```<code>this.send({userInput: this.input})
</code>```

Codelord.net also explained in a straightforward way.

Body:
In angular 1.6, passing actions up (from a presentational component to a controller component), I got stocked on this:

Chat (Controller component)

const Chat = ['messages', function (ms) {
    ...
    this.sendMessage = (userInput) => {
        ms.sendMessage(userInput)
            .then((res) => {
                console.log(res)
            })
    }
}]

Html Template:

    <conversation messages="ch.messages" ng-if="ch.messages" ></conversation>
    <user-input send="ch.sendMessage(userInput)"></user-input>

UserInput Component (Presentational component):

const UserInput = function () {
    ...
    this.checkAndSend = () => {
        this.send(this.input)
        this.input = this._clear()
    }
}

angular
    .module('chatbot-andrea')
    .component('userInput', {
        bindings: {
            send: '&'
        },
        ...
    })

Body:
I was making a terrible mistake, as velesin.io explains

"This is because the '&' binding is not really a callback function but
  an expressions, and the title and description are not function
  parameters but variables visible in the scope of the expression
  context"

So using,

this.send(this.input)

never would not work. Instead of that you have to use:

this.send({userInput: this.input})

Codelord.net also explained in a straightforward way.


问:
Android: Draggable Toast, Or Alternative?
I'm drawing a number of bitmaps on a canvas, and using MotionEvents to let me drag them around.

When each item is pressed, I'd like to display a Toast, or, Toast-like mini information-panel that tracks the movement of the bitmap being dragged during an ACTION_MOVE.  The "Toast" would appear on ACTION_DOWN and vanish on ACTION_UP.

The problem with using Toast is that I have to give it a duration, and, also, I can't change its position once it has been displayed.  Unless I can kill the Toast for each ACTION_MOVE, and display a new one right away at the current coordinates? (Sorry, thinking aloud at this point, can't get to my dev machine to test...)

I don't know what other options there might be to achieve this, and I'd very much appreciate suggestions from the community.

答: A Toast isn't suitable in this case for reasons you already mentioned. It will be better to define a region on the Canvas and draw the message string there using drawText. Put this in the onDraw method and call invalidate whenever you need to update the text or the position of the message board.</p>

ContentLicense: CC BY-SA 2.5


问:
main thread pfquerytableviewcontroller
I have a pfquery tableview controller that has many pfobjects inside the class that are loading in my pfquerytableviewcontroller. I have to problems. When I refresh my table view I get this error in my debugger "Warning: A long-running operation is being executed on the main thread.
 Break on warnBlockingOperationOnMainThread() to debug.". And when I try to swipe in my tableview, the tableview lags and slides very slowly. I assume that this is happening because the data is being loaded on the main thread. Here is my code. Can someone show me what I could do to fix both of these problems. Much appreciated. Thanks </p>

```<code>class ProductTableViewController: PFQueryTableViewController{
override func queryForTable() -> PFQuery<PFObject> {
    var query : PFQuery<PFObject>!

        query = PFQuery(className: "Products")
        query.includeKey("User")
        query.limit = 25
        query.skip = 25

                query.order(byAscending: "createdAt")

}

override func viewDidLoad() {
    super.viewDidLoad()
    let nib = UINib(nibName: "ProductTableViewCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: reuseIdentifier)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! ProductTableViewCell

    if let files : [PFFile] = object?["Images"] as? [PFFile] {
        cell.ProductImage.file = files.first
        cell.ProductImage.loadInBackground()
    }

   }
  }
</code>```

答:
Why not using a normal tableViewController?</p>

```<code>var show = 0
let maxload = 250
var objects = [PFObject]()

func loaddata() {
    self.objects.removeAll(keepingCapacity: false)
    self.show = 25

    let query = PFQuery(className:"Ledger")
    query.limit = self.maxload
    query.findObjectsInBackground {
        (objects: [PFObject]?, error: Error?) -> Void in
        if error == nil {
            if let objects = objects as [PFObject]! {
                for object in objects {
                    self.objects.append(object)
                }
                //reload TableView
                self.tableView.reloadData()
                print("retrieved \(self.objects.count)")

            }
        }
    }
}

@IBAction func refreshButton(_ sender: AnyObject) {
    loaddata()
    self.tableView.reloadData()
}

func numberOfSections(in tableView: UITableView) -> Int {
    if self.objects.count <= 0 {
        return 0
    } else {
        if show > self.objects.count {
            return self.objects.count
        } else if show > maxload {
            return maxload
        } else {
            return show
        }
    }
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath as NSIndexPath).section == self.show - 1 {
        self.show += 25
        print("showing more data")
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewController

    if self.objects.count - 1 > (indexPath as NSIndexPath).section {
        let objects = self.objects[(indexPath as NSIndexPath).section]
    }

    return cell
}
</code>```

Title: main thread pfquerytableviewcontroller

Body:
I have a pfquery tableview controller that has many pfobjects inside the class that are loading in my pfquerytableviewcontroller. I have to problems. When I refresh my table view I get this error in my debugger "Warning: A long-running operation is being executed on the main thread.
 Break on warnBlockingOperationOnMainThread() to debug.". And when I try to swipe in my tableview, the tableview lags and slides very slowly. I assume that this is happening because the data is being loaded on the main thread. Here is my code. Can someone show me what I could do to fix both of these problems. Much appreciated. Thanks

class ProductTableViewController: PFQueryTableViewController{
override func queryForTable() -> PFQuery<PFObject> {
    var query : PFQuery<PFObject>!

        query = PFQuery(className: "Products")
        query.includeKey("User")
        query.limit = 25
        query.skip = 25

                query.order(byAscending: "createdAt")

}

override func viewDidLoad() {
    super.viewDidLoad()
    let nib = UINib(nibName: "ProductTableViewCell", bundle: nil)
    tableView.register(nib, forCellReuseIdentifier: reuseIdentifier)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath, object: PFObject?) -> PFTableViewCell? {
    let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! ProductTableViewCell

    if let files : [PFFile] = object?["Images"] as? [PFFile] {
        cell.ProductImage.file = files.first
        cell.ProductImage.loadInBackground()
    }

   }
  }

Body:
Why not using a normal tableViewController?

var show = 0
let maxload = 250
var objects = [PFObject]()

func loaddata() {
    self.objects.removeAll(keepingCapacity: false)
    self.show = 25

    let query = PFQuery(className:"Ledger")
    query.limit = self.maxload
    query.findObjectsInBackground {
        (objects: [PFObject]?, error: Error?) -> Void in
        if error == nil {
            if let objects = objects as [PFObject]! {
                for object in objects {
                    self.objects.append(object)
                }
                //reload TableView
                self.tableView.reloadData()
                print("retrieved \(self.objects.count)")

            }
        }
    }
}

@IBAction func refreshButton(_ sender: AnyObject) {
    loaddata()
    self.tableView.reloadData()
}

func numberOfSections(in tableView: UITableView) -> Int {
    if self.objects.count <= 0 {
        return 0
    } else {
        if show > self.objects.count {
            return self.objects.count
        } else if show > maxload {
            return maxload
        } else {
            return show
        }
    }
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if (indexPath as NSIndexPath).section == self.show - 1 {
        self.show += 25
        print("showing more data")
    }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! TableViewController

    if self.objects.count - 1 > (indexPath as NSIndexPath).section {
        let objects = self.objects[(indexPath as NSIndexPath).section]
    }

    return cell
}


问:
Django distinct on case sensitive entries
I have the following query:

```<code>>>> z = Restaurant.objects.values_list('city',flat=True).order_by('city').distinct()
>>> z
[u'ELURU', u'Eluru', u'Hyderabad']
</code>```

As you can see, it is not completely distinct because of the case sensitivity. How do i correct this issue?

答:
You can use annotate in conjunction with Lower (or Upper, etc...) to normalize your values and return truly distinct values like this...

```<code>from django.db.models.functions import Lower

z = Restaurant.objects.annotate(
   city_lower=Lower('city')).values_list(
      'city_lower',flat=True).order_by('city_lower').distinct()
</code>```

Note: Make sure order_by is set to 'city_lower' and not 'city' to avoid duplicates.

Body:
I have the following query:

>>> z = Restaurant.objects.values_list('city',flat=True).order_by('city').distinct()
>>> z
[u'ELURU', u'Eluru', u'Hyderabad']

As you can see, it is not completely distinct because of the case sensitivity. How do i correct this issue?

Body:
You can use annotate in conjunction with Lower (or Upper, etc...) to normalize your values and return truly distinct values like this...

from django.db.models.functions import Lower

z = Restaurant.objects.annotate(
   city_lower=Lower('city')).values_list(
      'city_lower',flat=True).order_by('city_lower').distinct()

Note: Make sure order_by is set to 'city_lower' and not 'city' to avoid duplicates.


问:
Building C dynamic shared library gives undefined symbol
Why building static library (.a) doesn't give any error and works correctly:

```<code>$(LIBRARY): assertion.o
    $(AR) $(OUTPUT_STATIC_LIB_DIR)/$(LIBRARY) $(OUTPUT_DIR)/assertion.o
</code>```

Simultaneously, when building shared library (.so) gives me such error:

```<code>$(SHARED_LIBRARY): assertion.o
    $(CC) $(CFLAGS) -shared -o $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) $(OUTPUT_DIR)/assertion.o
</code>```

Error message:

```<code>Undefined symbols for architecture x86_64:
  "_float_cmp_func", referenced from:
</code>```

答:
The code of your library does refer to "_float_cmp_func", which needs to be found at run-time.

But static library is not expected to be a sufficient binary module, it is just collection of object code that is designed to be included into a later build/link steps (together with other object code and libraries).

In contrast, shared library is "ready-to-use" binary module, so its dependencies should be resolved at link stage. So in this case you should add into your link step some module(s) where "_float_cmp_func" is implemented

Body:
Why building static library (.a) doesn't give any error and works correctly:

$(LIBRARY): assertion.o
    $(AR) $(OUTPUT_STATIC_LIB_DIR)/$(LIBRARY) $(OUTPUT_DIR)/assertion.o

Simultaneously, when building shared library (.so) gives me such error:

$(SHARED_LIBRARY): assertion.o
    $(CC) $(CFLAGS) -shared -o $(OUTPUT_LIB_DIR)/$(SHARED_LIBRARY) $(OUTPUT_DIR)/assertion.o

Error message:

Undefined symbols for architecture x86_64:
  "_float_cmp_func", referenced from:


问:
Promise.reject() continues with then() instead of catch()
I am making myself a library which retries failed promise "chain-parts" - I collect methods to be called and queue next phase only after previous succeeded.

Conceptually rounded up - my problems are more fundamental. This is where I arrived with debugging:

```<code>this.runningPromise
    .then(function() {
        return Promise.reject();
    })
//;
//this.runningPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this))
    ;
</code>```

Works, promiseRejector kicks in. When I uncomment out the two lines, works not. promiseResolver gets called.

Can't find anywhere anything. Nodejs 6.10.3 with browserify on Windows, Chrome.

答:
this.runningPromise will not change when you chain other callbacks, i.e. the promise referenced by this.runningPromise was never rejected. So you have to assign the new promise to a new reference:

```<code>let something = this.runningPromise
    .then(function() {
        return Promise.reject();
    });

something
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this));
</code>```

Body:
I am making myself a library which retries failed promise "chain-parts" - I collect methods to be called and queue next phase only after previous succeeded.

Conceptually rounded up - my problems are more fundamental. This is where I arrived with debugging:

this.runningPromise
    .then(function() {
        return Promise.reject();
    })
//;
//this.runningPromise
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this))
    ;

Works, promiseRejector kicks in. When I uncomment out the two lines, works not. promiseResolver gets called.

Can't find anywhere anything. Nodejs 6.10.3 with browserify on Windows, Chrome.

Body:
this.runningPromise will not change when you chain other callbacks, i.e. the promise referenced by this.runningPromise was never rejected. So you have to assign the new promise to a new reference:

let something = this.runningPromise
    .then(function() {
        return Promise.reject();
    });

something
    .then(this.promiseResolver.bind(this))
    .catch(this.promiseRejector.bind(this));


问:
Using Flask and Jython under Windows 7
Hello everyone,

So I have been trying to use Jython to connect to an API Rest and retrieve some information. Now I want to use the Flask Framework with it. I have been trying to install the Flask with Jython but it does not seem to work at all. I am working on a Windows 7 machine and the problem for me is also that I can not download directly from the internet. For all other framework I used python wheels and installed these with Jython which worked fine.

I already tried to following commands and got these errors:

First error that I got was that it could not find the 'init.py' file in the flask folder so I changed the path in the file to the total path. But it just continued to give me more errors.

jython -m pip install '*.whl
Screenshot of the command line ouput of the error

pip install '*.whl (same as above)

I am a little stuck here and I hope that someone has an idea on how to solve this problem.

Big thanks already!!

答:
This appears to be a bug with Jython 2.7.0. See this error report in pip and this one in Jython.

The second of those indicates that it is fixed in the 2.7.1 release candidate.

Title: Using Flask and Jython under Windows 7


问:
What indexes are needed for the following scenario
I have a single table holding stock of single-use voucher codes. Each row is a separate code. For simplicity the table looks like this:

```<code>| id (AUTO_INCREMENTING) | owner (VARCHAR) | brand (VARCHAR) | currency (CHAR) | value (INTEGER) | activated_at (TIMESTAMP) | expires_at (DATE) |
|------------------------|-----------------|-----------------|-----------------|-----------------|--------------------------|-------------------|
| 1                      | first-owner     | brand-one       | gbp             | 10              | NULL                     | 2018-06-06        |
| 2                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
| 3                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
</code>```

I know I can normalise the table and extract all the fields into their own tables and have the stock table just contain the ids, however so far that hasn't proven to give a performance gain, and, for the sake of simplicity and user readability I am inclined to leave it as is.

When querying this table, I want to be able to optionally pass the owner, the brand, or both.

What indexes do I need on this table for the following queries and why?

Querying the table without supplying an owner or brand:

```<code>SELECT
    `owner`,
    `brand`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `owner`, `brand`, `currency`, `value`
</code>```

If I run explain I can see that the index is used:

```<code>| select_type | table     | type | possible_keys | key | key_len | ref   | rows   | Extra                                                     |
|-------------|-----------|------|---------------|-----|---------|-------|--------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  |               |     | 766     | const | 416144 | Using where; Using index; Using temporary; Using filesort |
</code>```

When I supply an owner the index is used but it creates a temporary table and uses filesort which I believe isn't good.

```<code>SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `activated_at` IS NULL
AND `expires_at` >= '2017-06-06'
GROUP BY `brand`, `owner`, `currency`, `value`
</code>```

Running explain shows:

```<code>| select_type | table     | type  | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|-------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | index | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 2310    |     | 87   | Using where; Using index; Using temporary; Using filesort |
</code>```

When I also provide a brand I get:

```<code>SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `brand` = 'brand-one'
AND `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `brand`, `owner`, `currency`, `value`
</code>```

Lastly, when I run explain I get:

```<code>| select_type | table     | type | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 1532    |     | 1    | Using where; Using index; Using temporary; Using filesort |
</code>```

As mentioned, I have an index across the brand, owner, currency, value, activated_at, and expires_at fields although this isn't used when I don't include brand in the where part of the query.

答:
I would write this as:

```<code>SELECT brand, owner, currency, value,
       count(*) AS quantity_of_codes, sum(value) AS total_face_value
FROM inventory i
WHERE owner = 'an-owner' AND
      activated_at IS NULL AND
      expires_at >= '2017-06-06'
GROUP BY brand, owner, currency, value;
</code>```

For this query, the best index would be inventory(owner, activated_at, expires_at).  These columns in this order can be used for the WHERE clause.  In MySQL there is not much that you can do about the GROUP BY.

Body:
I have a single table holding stock of single-use voucher codes. Each row is a separate code. For simplicity the table looks like this:

| id (AUTO_INCREMENTING) | owner (VARCHAR) | brand (VARCHAR) | currency (CHAR) | value (INTEGER) | activated_at (TIMESTAMP) | expires_at (DATE) |
|------------------------|-----------------|-----------------|-----------------|-----------------|--------------------------|-------------------|
| 1                      | first-owner     | brand-one       | gbp             | 10              | NULL                     | 2018-06-06        |
| 2                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |
| 3                      | second-owner    | brand-one       | gbp             | 15              | NULL                     | 2018-06-06        |

I know I can normalise the table and extract all the fields into their own tables and have the stock table just contain the ids, however so far that hasn't proven to give a performance gain, and, for the sake of simplicity and user readability I am inclined to leave it as is.

When querying this table, I want to be able to optionally pass the owner, the brand, or both.

What indexes do I need on this table for the following queries and why?

Querying the table without supplying an owner or brand:

SELECT
    `owner`,
    `brand`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `owner`, `brand`, `currency`, `value`

If I run explain I can see that the index is used:

| select_type | table     | type | possible_keys | key | key_len | ref   | rows   | Extra                                                     |
|-------------|-----------|------|---------------|-----|---------|-------|--------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  |               |     | 766     | const | 416144 | Using where; Using index; Using temporary; Using filesort |

When I supply an owner the index is used but it creates a temporary table and uses filesort which I believe isn't good.

SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `activated_at` IS NULL
AND `expires_at` >= '2017-06-06'
GROUP BY `brand`, `owner`, `currency`, `value`

Running explain shows:

| select_type | table     | type  | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|-------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | index | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 2310    |     | 87   | Using where; Using index; Using temporary; Using filesort |

When I also provide a brand I get:

SELECT
    `brand`,
    `owner`,
    `currency`,
    `value`,
    count(*) AS 'quantity_of_codes',
    (count(*) * `value`) AS 'total_face_value'
FROM `inventory`
WHERE `owner` = 'first-owner'
AND `brand` = 'brand-one'
AND `activated_at` IS NULL
AND `expires_at` >= '2018-06-05'
GROUP BY `brand`, `owner`, `currency`, `value`

Lastly, when I run explain I get:

| select_type | table     | type | possible_keys                                            | key                                                      | key_len | ref | rows | Extra                                                     |
|-------------|-----------|------|----------------------------------------------------------|----------------------------------------------------------|---------|-----|------|-----------------------------------------------------------|
| SIMPLE      | inventory | ref  | brand_owner_currency_value_activated_at_expires_at_index | brand_owner_currency_value_activated_at_expires_at_index | 1532    |     | 1    | Using where; Using index; Using temporary; Using filesort |

As mentioned, I have an index across the brand, owner, currency, value, activated_at, and expires_at fields although this isn't used when I don't include brand in the where part of the query.

Body:
I would write this as:

SELECT brand, owner, currency, value,
       count(*) AS quantity_of_codes, sum(value) AS total_face_value
FROM inventory i
WHERE owner = 'an-owner' AND
      activated_at IS NULL AND
      expires_at >= '2017-06-06'
GROUP BY brand, owner, currency, value;

For this query, the best index would be inventory(owner, activated_at, expires_at).  These columns in this order can be used for the WHERE clause.  In MySQL there is not much that you can do about the GROUP BY.


问:
JPA Single Table Inheritance: Not a managed type
I have a Spring Boot application (embedded Tomcat, Thymeleaf template...) using

```<code>spring-boot-starter-data-jpa
</code>```

I use Inheritance strategies with JPA and Hibernate

I have this class:

```<code>@Entity
@Table(name="t_alarm_notification")
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
..
}
</code>```

and this other one:

```<code>   @MappedSuperclass
    public class BookAlarmNotification extends AlarmNotification {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        private Book book;

..
}
</code>```

and this other one

```<code>public interface BookAlarmNotificationRepository extends CrudRepository<BookAlarmNotification, Long> {

}
</code>```

but running an integration test or just starting the String Boot app. I got this error:

```<code> java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookAlarmNotificationService': Unsatisfied dependency expressed through field 'bookAlarmNotificationRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more
</code>```

答:
```<code>@Entity
@Table(name="d_intervenant_tc")
@Inheritance(strategy= InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="Type", discriminatorType=DiscriminatorType.STRING)
public class Intervenant {

}

@Entity
public class Affilie extends Intervenant{
}
</code>```

Body:
I have a Spring Boot application (embedded Tomcat, Thymeleaf template...) using

spring-boot-starter-data-jpa

I use Inheritance strategies with JPA and Hibernate

I have this class:

@Entity
@Table(name="t_alarm_notification")
@Inheritance (strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name= "ALARM_TYPE")
public abstract class AlarmNotification  implements Serializable {
..
}

and this other one:

   @MappedSuperclass
    public class BookAlarmNotification extends AlarmNotification {

        /**
         *
         */
        private static final long serialVersionUID = 1L;

        private Book book;

..
}

and this other one

public interface BookAlarmNotificationRepository extends CrudRepository<BookAlarmNotification, Long> {

}

but running an integration test or just starting the String Boot app. I got this error:

 java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookAlarmNotificationService': Unsatisfied dependency expressed through field 'bookAlarmNotificationRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'bookAlarmNotificationRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 43 more
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.nicinc.persistence.domain.backend.BookAlarmNotification
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:70)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:68)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:153)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:100)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:82)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:199)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:277)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:263)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:101)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
    ... 53 more


问:
Return List of T where T is one of x classes (where x is greater than zero)
Please see the two classes below:

```<code>public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }
</code>```

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

```<code>public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }
</code>```

Can this be done?

答:
Use Interface and implement that in the both class then use that interface in generic method as well</p>

```<code>class Program
{
    static void Main(string[] args)
    {

    }

    public static List<T> BuildList<T>() where T : IPersonModel, new()
    {
        //Populate list of T where T is wither a Person or PersonModel.
        //Return List of T
        // Implement here with any loop
        return null;// you need to return any value
    }
}

public interface IPersonModel
{
    int ID { get; set; }
    string Name { get; set; }
    string Address { get; set; }
}
public class Person : IPersonModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public class PersonModel : IPersonModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}
</code>```

Body:
Please see the two classes below:

public class Person
    {
        int ID;
        string Name;
        string Address;
    }

    public class PersonModel
    {
        int ID;
        string Name;
        string Address;
    }

I am trying to create a function that will return a List of PersonModel or a List of Person depending what parameter is passed to the class:

Here is the client side function:

public static List<T> BuildList<T>()
        {
            //Populate list of T where T is wither a Person or PersonModel.
            //Return List of T
        }

Can this be done?

Body:
Use Interface and implement that in the both class then use that interface in generic method as well

class Program
{
    static void Main(string[] args)
    {

    }

    public static List<T> BuildList<T>() where T : IPersonModel, new()
    {
        //Populate list of T where T is wither a Person or PersonModel.
        //Return List of T
        // Implement here with any loop
        return null;// you need to return any value
    }
}

public interface IPersonModel
{
    int ID { get; set; }
    string Name { get; set; }
    string Address { get; set; }
}
public class Person : IPersonModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}

public class PersonModel : IPersonModel
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
}


答:
How about this?</p>

```<code>With ActiveSheet
  firstCol = 1
  lastCol = .Cells(1, .Cells.Columns.Count).End(xlToLeft).Column
  For i = 1 To lastCol
    If .Cells(1, i) = "" Then GoTo NextCol 'skip blank cell

    If firstCol = 0 And .Cells(1, i) <> "" Then firstCol = i  'set first column

    If .Cells(1, i) = .Cells(1, i + 1) Then
        LastColDup = i  'remember last duplicate column
    Else
        Application.DisplayAlerts = False
        With .Range(Cells(1, firstCol), Cells(1, LastColDup + 1))
            .Merge
            .HorizontalAlignment = xlCenter
        End With
        Application.DisplayAlerts = True
        firstCol = 0
        LastColDup = 0
    End If
NextCol:
  Next i
End With
</code>```

Title: Excel VBA: Merging a range inside a loop

Body:
I want to merge that repeating Chapters into just one cell by Chapter.

Here is how my code does the looping.

        Dim label As Control
        Dim itm As Object
        For ctr = 1 To InfoForm.Chapter.ListCount - 1
            For Each label In InfoForm.Controls
                If TypeName(label) = "Label" Then
                    With ActiveSheet
                        i = i + 1

                        lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
                        lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column

                        If label <> "Chapter" Then
                            .Cells(lastColumn, i).Value = "Chapter " & ctr

                            .Cells(lastRow, i).Value = label.Caption
                        End If
                    End With
                End If
            Next
        Next

I've tried merging it like this

.Range(Cells(1, lastColumn), Cells(1,i)).Merge

But it merges all the repeating chapters into one cell instead

Expected Result:

Body:
How about this?

With ActiveSheet
  firstCol = 1
  lastCol = .Cells(1, .Cells.Columns.Count).End(xlToLeft).Column
  For i = 1 To lastCol
    If .Cells(1, i) = "" Then GoTo NextCol 'skip blank cell

    If firstCol = 0 And .Cells(1, i) <> "" Then firstCol = i  'set first column

    If .Cells(1, i) = .Cells(1, i + 1) Then
        LastColDup = i  'remember last duplicate column
    Else
        Application.DisplayAlerts = False
        With .Range(Cells(1, firstCol), Cells(1, LastColDup + 1))
            .Merge
            .HorizontalAlignment = xlCenter
        End With
        Application.DisplayAlerts = True
        firstCol = 0
        LastColDup = 0
    End If
NextCol:
  Next i
End With


问:
Creating Jars without Main() method
I have downloaded a project from  SVN and have imported the same in my Eclipse IDE.The project have several .java files but none of them have any main() method.

It is required to make some minor changes in one of the file and then create a new version of the jar. And replace the old jar with the new version in the server.

Ours is a big project and the tool is running on Weblogic. But while creating the newer version of the jar through Eclipse ( Export>Jar) it is asking to provide the class which contains main() method or any entry point.

Please let me know how should I proceed to create the jar?

答:
You might be trying to create runnable jar file.

To create a normal jar file please follow the steps:

In eclipse, right click on the project

Select Export Search for JAR file

Select which all the packages needs to be part of JAR file

Choose the path where you want export this JAR file & provide the name to JAR file

Click Finish

Title: Creating Jars without Main() method


问:
display xml feed asp.net C#
This is my xml file:
http://goalserve.com/samples/soccer_inplay.xml

and this is my model:

```<code>[XmlRoot(ElementName = "localteam")]
public class Localteam
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "goals")]
    public string Goals { get; set; }
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
}

this is my controller:

XmlDocument doc = new XmlDocument();

List<Localteam> s = new List<Localteam>();

doc.Load(Server.MapPath("soccer_inplay.xml"));

foreach (XmlNode node in doc.SelectNodes("/scores/category/"))
{
    s.Add(new Localteam
    {
        Name = node["Name"].InnerText
    });
}

return View(s);
</code>```

this is my view:

```<code><table>

    <tr>

        <th>Name</th>

        <th>Goals</th>

    </tr>

    @foreach (WebApplication22.Models.Localteam s in Model)

    {
        <tr>

            <td>@s.Name</td>

            <td>@s.Goals</td>

        </tr>

    }

</table>
</code>```

I want to display this  xml feed but I can't, I have problems with the view

答:
Use xml linq</p>

```<code>using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string URL = "http://goalserve.com/samples/soccer_inplay.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);

            Localteam.teams = doc.Descendants("odd").Select(x => new Localteam()
            {
                Name = (string)x.Attribute("name"),
                games = x.Elements("type").Where(y => y.Attribute("id") != null).Select(y => new Game() {
                    id = (long)y.Attribute("id"),
                    opponent = (string)y.Attribute("name"),
                    suspend = (int)y.Attribute("suspend"),
                    odd = (Single)y.Attribute("odd"),
                    _type = (string)y.Attribute("type")
                }).ToList()
            }).ToList();
        }

    }
    public class Localteam
    {
        public static List<Localteam> teams = new List<Localteam>();

        public string Name { get; set; }
        public List<Game> games { get; set; }
    }
    public class Game
    {
        public string opponent { get; set; }
        public long id { get; set; }
        public int suspend { get; set; }
        public Single odd { get; set; }
        public string _type { get; set; }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: display xml feed asp.net C#

Body:
This is my xml file:
http://goalserve.com/samples/soccer_inplay.xml

and this is my model:

[XmlRoot(ElementName = "localteam")]
public class Localteam
{
    [XmlAttribute(AttributeName = "name")]
    public string Name { get; set; }
    [XmlAttribute(AttributeName = "goals")]
    public string Goals { get; set; }
    [XmlAttribute(AttributeName = "id")]
    public string Id { get; set; }
}

this is my controller:

XmlDocument doc = new XmlDocument();

List<Localteam> s = new List<Localteam>();

doc.Load(Server.MapPath("soccer_inplay.xml"));

foreach (XmlNode node in doc.SelectNodes("/scores/category/"))
{
    s.Add(new Localteam
    {
        Name = node["Name"].InnerText
    });
}

return View(s);

this is my view:

        Name

        Goals

    @foreach (WebApplication22.Models.Localteam s in Model)

    {

            @s.Name

            @s.Goals

    }

I want to display this  xml feed but I can't, I have problems with the view

Body:
Use xml linq

using System.Collections.ObjectModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication57
{
    class Program
    {
        const string URL = "http://goalserve.com/samples/soccer_inplay.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(URL);

            Localteam.teams = doc.Descendants("odd").Select(x => new Localteam()
            {
                Name = (string)x.Attribute("name"),
                games = x.Elements("type").Where(y => y.Attribute("id") != null).Select(y => new Game() {
                    id = (long)y.Attribute("id"),
                    opponent = (string)y.Attribute("name"),
                    suspend = (int)y.Attribute("suspend"),
                    odd = (Single)y.Attribute("odd"),
                    _type = (string)y.Attribute("type")
                }).ToList()
            }).ToList();
        }

    }
    public class Localteam
    {
        public static List<Localteam> teams = new List<Localteam>();

        public string Name { get; set; }
        public List<Game> games { get; set; }
    }
    public class Game
    {
        public string opponent { get; set; }
        public long id { get; set; }
        public int suspend { get; set; }
        public Single odd { get; set; }
        public string _type { get; set; }
    }
}


问:
transform:rotate not working - but works on original mockup
I made a fidget spinner animation which we are using for a Sale.

You can see it working perfectly here: https://jsfiddle.net/e2tt2mao/448/

However when I apply the same/similar code to the "scene" i am currently making I cant get it to spin at all...

See here: https://jsfiddle.net/uzfpqysc/8/

I have tried everything.. I'm not sure why it wont spin in my "second js fiddle link"

Any help is much appreciated!

```<code>    @-webkit-keyframes rotating /* Safari and Chrome */ {
  from {
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes rotating {
  from {
    -ms-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
.rotating {
  -webkit-animation: rotating 2s linear infinite;
  -moz-animation: rotating 2s linear infinite;
  -ms-animation: rotating 2s linear infinite;
  -o-animation: rotating 2s linear infinite;
  animation: rotating 2s linear infinite;
}
</code>```

答:
The issue was that the .rotating span had not width and height because the images inside were absolute positioned. I have defined a width and height for the span and have it a transform origin of transform-origin: 50% 50%;. I have also attempted to centrally position the .rotating span, but you may want to adjust it.

https://jsfiddle.net/WizardCoder/uzfpqysc/11/

EDIT: Here is the responsive version. I had to adjust the styles for .animateVSS very slightly to allow me to properly center the spinner. It will do the same as what your styling was doing just a slightly different approach.

https://jsfiddle.net/WizardCoder/uzfpqysc/12/

Body:
I made a fidget spinner animation which we are using for a Sale.

You can see it working perfectly here: https://jsfiddle.net/e2tt2mao/448/

However when I apply the same/similar code to the "scene" i am currently making I cant get it to spin at all...

See here: https://jsfiddle.net/uzfpqysc/8/

I have tried everything.. I'm not sure why it wont spin in my "second js fiddle link"

Any help is much appreciated!

    @-webkit-keyframes rotating /* Safari and Chrome */ {
  from {
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
@keyframes rotating {
  from {
    -ms-transform: rotate(0deg);
    -moz-transform: rotate(0deg);
    -webkit-transform: rotate(0deg);
    -o-transform: rotate(0deg);
    transform: rotate(0deg);
  }
  to {
    -ms-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    -webkit-transform: rotate(360deg);
    -o-transform: rotate(360deg);
    transform: rotate(360deg);
  }
}
.rotating {
  -webkit-animation: rotating 2s linear infinite;
  -moz-animation: rotating 2s linear infinite;
  -ms-animation: rotating 2s linear infinite;
  -o-animation: rotating 2s linear infinite;
  animation: rotating 2s linear infinite;
}


问:
Access TextBlock Text inside a DataTemplate UWP
I searched all over the internet on this question, but I can't made progress in my UWP application.

I have a ListView with a DataTemplate:

```<code><ListView x:Name="lvEszTmplt" Margin="50,61,0,0" ItemClick="lvEszTmplt_ItemClick_1" SelectionChanged="lvEszTmplt_SelectionChanged_1"   >
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,8" x:Name="spItem" >
                    <TextBlock x:Name="tbAzonosito" >
                                <Run Text="Azonosító: " Foreground="DarkGray"/>
                                <Run Text="{Binding Azonosito}"
                                     Foreground="DarkGray"
                                     />

                    </TextBlock>
                    <TextBlock x:Name="tbMegnevezes" >
                                <Run Text="Megnevezés: " Foreground="DarkGray"/>
                                <Run Text="{Binding Megnevezes}"
                                     Foreground="DarkGray"/>

                    </TextBlock>
                    <TextBlock x:Name="tbSerial" >
                                <Run Text="Serial: " Foreground="DarkGray"/>
                                <Run Text="{Binding Serial}"
                                     Foreground="DarkGray"/>
                    </TextBlock>
                    <TextBlock x:Name="tbSorszam"   >
                                <Run Text="Sorszám: " Foreground="DarkGray"/>
                                <Run Text="{Binding Sorszam}"
                                     Foreground="DarkGray"/>
                    </TextBlock>

                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</code>```

In the ListView, the "Azonosito" is an ID column.
When I click on a Item, it should go to another Frame and take the ID from the ListView, and load the Deatails View with the data from the ID.

How can I do this?

Thank you for helping me out!

答:
Use ItemClickEventArgs.ClickedItem property of the ItemClick event to read the clicked item:

```<code>private void lvEszTmplt_ItemClick_1(object sender, ItemClickEventArgs e)
{
    var item = (ItemModel)e.ClickedItem;
    var id = item.Azonosito;
}
</code>```

Body:
I searched all over the internet on this question, but I can't made progress in my UWP application.

I have a ListView with a DataTemplate:

<ListView x:Name="lvEszTmplt" Margin="50,61,0,0" ItemClick="lvEszTmplt_ItemClick_1" SelectionChanged="lvEszTmplt_SelectionChanged_1"   >
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Margin="0,8" x:Name="spItem" >
                    <TextBlock x:Name="tbAzonosito" >
                                <Run Text="Azonosító: " Foreground="DarkGray"/>
                                <Run Text="{Binding Azonosito}"
                                     Foreground="DarkGray"
                                     />

                    </TextBlock>
                    <TextBlock x:Name="tbMegnevezes" >
                                <Run Text="Megnevezés: " Foreground="DarkGray"/>
                                <Run Text="{Binding Megnevezes}"
                                     Foreground="DarkGray"/>

                    </TextBlock>
                    <TextBlock x:Name="tbSerial" >
                                <Run Text="Serial: " Foreground="DarkGray"/>
                                <Run Text="{Binding Serial}"
                                     Foreground="DarkGray"/>
                    </TextBlock>
                    <TextBlock x:Name="tbSorszam"   >
                                <Run Text="Sorszám: " Foreground="DarkGray"/>
                                <Run Text="{Binding Sorszam}"
                                     Foreground="DarkGray"/>
                    </TextBlock>

                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

In the ListView, the "Azonosito" is an ID column.
When I click on a Item, it should go to another Frame and take the ID from the ListView, and load the Deatails View with the data from the ID.

How can I do this?

Thank you for helping me out!

Body:
Use ItemClickEventArgs.ClickedItem property of the ItemClick event to read the clicked item:

private void lvEszTmplt_ItemClick_1(object sender, ItemClickEventArgs e)
{
    var item = (ItemModel)e.ClickedItem;
    var id = item.Azonosito;
}


问:
Align multiple labels to left of form input
I'm trying to stack two  tags in a form input label. At the moment, they're sitting next to each other, but I'm not sure how to move span.label-sm under the regular span. I've already set it to display: block;.

Desired outcome: http://i.imgur.com/CkOKeWl.jpg.

HTML:

```<code><div id="appraisals-form" class="contact-form">
    <form role="form" method="post" action="contact-form.php">
        <label for="name"><span>Name</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." /></label>
        <label for="email"><span>Email</span><input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." /></label>
        <label for="email"><span>Phone</span><input type="tel" class="input-field" name="phone" required data-errormessage-value-missing="Please enter your phone number." /></label>

        <label for="name"><span>Type of Artwork</span><span class="label-sm">(i.e. sculpture, painting...)</span><input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your item's type of artwork." /></label>

        <label for="message"><span>Message</span><textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea></label>
        <div class="centred-button"><input type="submit" value="" class="submit-button" /></div>
    </form>
</div>
</code>```

CSS:

```<code>.contact-form {
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    max-width: 600px;
    font-family: 'LinotypeUniversW01-Thin_723604', Arial, sans-serif;
    font-size: 20px;
}

.contact-form label {
    display: block;
    margin: 0px 0px 15px 0px;
    text-transform: uppercase; /* New */
}

.contact-form label > span {
    padding-top: 8px;
}

.contact-form label > span, #recaptcha::before {
    width: 100px;
    text-align: right;
    float: left;
    padding-right: 20px;
    content: "";
}

.contact-form input, .contact-form textarea {
    margin-bottom: 15px;
    padding: 10px;
    border: none;
}

.contact-form input.input-field {
    width: 70%;
    height: 20px;
    font-size: 18px;
}

.contact-form .textarea-field {
    height: 250px;
    margin-bottom: 11px;
}

.contact-form .textarea-field, .g-recaptcha {
    width: 70%;
    font-size: 18px;
    display: inline-block;
}

.g-recaptcha {
    height: 78px !important;
}

#recaptcha {
    display: block;
    margin: 0px 0px 24px 0px;
}

textarea {
    resize: none;
}

textarea:focus, input:focus {
    outline: 0;
}

input.submit-button {
    background-image: url("../img/submit-button.jpg");
    width: 225px;
    height: 60px;
    border: none;
}

.appraisals .section-title {
    width: 100%;
}

#appraisals-form {
    width: 100%;
    max-width: 700px;
    top: auto;
    transform: none;
}

#appraisals-form label > span {
    width: 150px;
    font-size: 16px
}

#appraisals-form span.label-sm {
    display: block;
    font-size: 14px;
    text-transform: none;
}

#appraisals-form input, #appraisals-form textarea {
    background-color: #d7d7d7;
}

#appraisals-form textarea {
    height: 100px;
}

#appraisals-form .centred-button {
    text-align: center;
}
</code>```

Fiddle: http://jsfiddle.net/tcap2Lcp/.

Any help would really appreciated!

答:
The easyest way is to add this class to CSS : </p>

```<code>label {float: left; width: 10em; margin-right: 1em; text-align: right;}
</code>```

Body:
I'm trying to stack two  tags in a form input label. At the moment, they're sitting next to each other, but I'm not sure how to move span.label-sm under the regular span. I've already set it to display: block;.

Desired outcome: http://i.imgur.com/CkOKeWl.jpg.

HTML:

    <form role="form" method="post" action="contact-form.php">
        Name<input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your name." />
        Email<input type="email" class="input-field" name="email" required data-errormessage-value-missing="Please enter your email address." />
        Phone<input type="tel" class="input-field" name="phone" required data-errormessage-value-missing="Please enter your phone number." />

        Type of Artwork(i.e. sculpture, painting...)<input type="text" class="input-field" name="name" required data-errormessage-value-missing="Please enter your item's type of artwork." />

        Message<textarea name="message" class="textarea-field" required data-errormessage-value-missing="Please enter your message."></textarea>

<input type="submit" value="" class="submit-button" />

    </form>

CSS:

.contact-form {
    margin: 0 auto;
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    max-width: 600px;
    font-family: 'LinotypeUniversW01-Thin_723604', Arial, sans-serif;
    font-size: 20px;
}

.contact-form label {
    display: block;
    margin: 0px 0px 15px 0px;
    text-transform: uppercase; /* New */
}

.contact-form label > span {
    padding-top: 8px;
}

.contact-form label > span, #recaptcha::before {
    width: 100px;
    text-align: right;
    float: left;
    padding-right: 20px;
    content: "";
}

.contact-form input, .contact-form textarea {
    margin-bottom: 15px;
    padding: 10px;
    border: none;
}

.contact-form input.input-field {
    width: 70%;
    height: 20px;
    font-size: 18px;
}

.contact-form .textarea-field {
    height: 250px;
    margin-bottom: 11px;
}

.contact-form .textarea-field, .g-recaptcha {
    width: 70%;
    font-size: 18px;
    display: inline-block;
}

.g-recaptcha {
    height: 78px !important;
}

#recaptcha {
    display: block;
    margin: 0px 0px 24px 0px;
}

textarea {
    resize: none;
}

textarea:focus, input:focus {
    outline: 0;
}

input.submit-button {
    background-image: url("../img/submit-button.jpg");
    width: 225px;
    height: 60px;
    border: none;
}

.appraisals .section-title {
    width: 100%;
}

#appraisals-form {
    width: 100%;
    max-width: 700px;
    top: auto;
    transform: none;
}

#appraisals-form label > span {
    width: 150px;
    font-size: 16px
}

#appraisals-form span.label-sm {
    display: block;
    font-size: 14px;
    text-transform: none;
}

#appraisals-form input, #appraisals-form textarea {
    background-color: #d7d7d7;
}

#appraisals-form textarea {
    height: 100px;
}

#appraisals-form .centred-button {
    text-align: center;
}

Fiddle: http://jsfiddle.net/tcap2Lcp/.

Any help would really appreciated!

Body:
The easyest way is to add this class to CSS :

label {float: left; width: 10em; margin-right: 1em; text-align: right;}