问:
Get my mainloop to exit once a condition is met Python 3.x Tic Tac Toe
I have a Tic Tac Toe game in tkinter that shows a grid which uses images as the "empty", "X" and "O". I used radio buttons as images with indicatoron set to 0.

I also have a list called board with 9 empty spaces. When you click on one of the empty tiles it changes to the picture to the X or O according to which turn it is and then adds either an X or O to the board list in the appropriate position. Right now,

I am trying to exit the mainloop when the condition is met that a row or column or diagonal has an X or O in all three. I have functions for these conditions and have it return True whenever a condition is met. I would like to have my mainloop exit when one of the two wins and maybe even have a pop-up that reads X Wins! or O wins!

I'm open to suggestions for a different method for determining the winner but my main concern is just getting it to stop once one of the conditions is met.

```<code>from tkinter import *

class TicTacToe():

    def __init__(self):

        window = Tk()
        window.title("Tic-Tac-Toe")

        self.emptyBox = PhotoImage(file = "image/empty.gif")
        self.xBox = PhotoImage(file = "image/x.gif")
        self.oBox = PhotoImage(file = "image/o.gif")
        self.turn = 0
        self.board = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
        self.token = IntVar()

        frame1 = Frame(window, height = 150, width = 150)
        frame1.pack()

        self.label1 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 1, indicatoron = 0, command = self.addImage)
        self.label1.grid(row = 0, column = 0)
        self.label2 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 2, indicatoron = 0, command = self.addImage)
        self.label2.grid(row = 0, column = 1)
        self.label3 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 3, indicatoron = 0, command = self.addImage)
        self.label3.grid(row = 0, column = 2)

        self.label4 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 4, indicatoron = 0, command = self.addImage)
        self.label4.grid(row = 1, column = 0)
        self.label5 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 5, indicatoron = 0, command = self.addImage)
        self.label5.grid(row = 1, column = 1)
        self.label6 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 6, indicatoron = 0, command = self.addImage)
        self.label6.grid(row = 1, column = 2)

        self.label7 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 7, indicatoron = 0, command = self.addImage)
        self.label7.grid(row = 2, column = 0)
        self.label8 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 8, indicatoron = 0, command = self.addImage)
        self.label8.grid(row = 2, column = 1)
        self.label9 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 9, indicatoron = 0, command = self.addImage)
        self.label9.grid(row = 2, column = 2)

        window.mainloop()

    def doesWinX(self):
        #check if X wins
        if self.board[0] == 'X' and self.board[1] == 'X' and self.board[2] == 'X':
            return True
        elif self.board[3] == 'X' and self.board[4] == 'X' and self.board[5] == 'X':
            return True
        elif self.board[6] == 'X' and self.board[7] == 'X' and self.board[8] == 'X':
            return True

        elif self.board[0] == 'X' and self.board[3] == 'X' and self.board[6] == 'X':
            return True
        elif self.board[1] == 'X' and self.board[4] == 'X' and self.board[7] == 'X':
            return True
        elif self.board[2] == 'X' and self.board[5] == 'X' and self.board[8] == 'X':
            return True

        elif self.board[0] == 'X' and self.board[4] == 'X' and self.board[8] == 'X':
            return True
        elif self.board[2] == 'X' and self.board[4] == 'X' and self.board[6] == 'X':
            return True
        else:
            return False

    def doesWinO(self):
        if self.board[0] == 'O' and self.board[1] == 'O' and self.board[2] == 'O':
            return True
        elif self.board[3] == 'O' and self.board[4] == 'O' and self.board[5] == 'O':
            return True
        elif self.board[6] == 'O' and self.board[7] == 'O' and self.board[8] == 'O':
            return True

        elif self.board[0] == 'O' and self.board[3] == 'O' and self.board[6] == 'O':
            return True
        elif self.board[1] == 'O' and self.board[4] == 'O' and self.board[7] == 'O':
            return True
        elif self.board[2] == 'O' and self.board[5] == 'O' and self.board[8] == 'O':
            return True

        elif self.board[0] == 'O' and self.board[4] == 'O' and self.board[8] == 'O':
            return True
        elif self.board[2] == 'O' and self.board[4] == 'O' and self.board[6] == 'O':
            return True
        else:
            return False

    def addImage(self):
        token = self.token.get()
        while self.turn % 2 == 0:
            if token == 1 and self.board[0] == ' ':
                self.label1.config(image = self.xBox)
                self.board.pop(0)
                self.board.insert(0, 'X')
                self.turn += 1
                break
            elif token == 2 and self.board[1] == ' ':
                self.label2.config(image = self.xBox)
                self.board.pop(1)
                self.board.insert(1, 'X')
                self.turn += 1
                break
            elif token == 3 and self.board[2] == ' ':
                self.label3.config(image = self.xBox)
                self.board.pop(2)
                self.board.insert(2, 'X')
                self.turn += 1
                break
            elif token == 4 and self.board[3] == ' ':
                self.label4.config(image = self.xBox)
                self.board.pop(3)
                self.board.insert(3, 'X')
                self.turn += 1
                break
            elif token == 5 and self.board[4] == ' ':
                self.label5.config(image = self.xBox)
                self.board.pop(4)
                self.board.insert(4, 'X')
                self.turn += 1

            elif token == 6 and self.board[5] == ' ':
                self.label6.config(image = self.xBox)
                self.board.pop(5)
                self.board.insert(5, 'X')
                self.turn += 1
            elif token == 7 and self.board[6] == ' ':
                self.label7.config(image = self.xBox)
                self.board.pop(6)
                self.board.insert(6, 'X')
                self.turn += 1
            elif token == 8 and self.board[7] == ' ':
                self.label8.config(image = self.xBox)
                self.board.pop(7)
                self.board.insert(7, 'X')
                self.turn += 1
            elif token == 9 and self.board[8] == ' ':
                self.label9.config(image = self.xBox)
                self.board.pop(8)
                self.board.insert(8, 'X')
                self.turn += 1
            break

        while self.turn % 2 == 1:
            token = self.token.get()
            if token == 1 and self.board[0] == ' ':
                self.label1.config(image = self.oBox)
                self.board.pop(0)
                self.board.insert(0, 'O')
                self.turn += 1
            elif token == 2 and self.board[1] == ' ':
                self.label2.config(image = self.oBox)
                self.board.pop(1)
                self.board.insert(1, 'O')
                self.turn += 1
            elif token == 3 and self.board[2] == ' ':
                self.label3.config(image = self.oBox)
                self.board.pop(2)
                self.board.insert(2, 'O')
                self.turn += 1
            elif token == 4 and self.board[3] == ' ':
                self.label4.config(image = self.oBox)
                self.board.pop(3)
                self.board.insert(3, 'O')
                self.turn += 1
            elif token == 5 and self.board[4] == ' ':
                self.label5.config(image = self.oBox)
                self.board.pop(4)
                self.board.insert(4, 'O')
                self.turn += 1
            elif token == 6 and self.board[5] == ' ':
                self.label6.config(image = self.oBox)
                self.board.pop(5)
                self.board.insert(5, 'O')
                self.turn += 1
            elif token == 7 and self.board[6] == ' ':
                self.label7.config(image = self.oBox)
                self.board.pop(6)
                self.board.insert(6, 'O')
                self.turn += 1
                break
            elif token == 8 and self.board[7] == ' ':
                self.label8.config(image = self.oBox)
                self.board.pop(7)
                self.board.insert(7, 'O')
                self.turn += 1
            elif token == 9 and self.board[8] == ' ':
                self.label9.config(image = self.oBox)
                self.board.pop(8)
                self.board.insert(8, 'O')
                self.turn += 1
            break

TicTacToe()
</code>```

Thanks for the help!

答:
Add a conditional as the very last statement of addImage

```<code>def addImage(self):
    .....
    .....
    if self.doesWinX() or self.doesWinO():
           print('game over!!')
</code>```

To get it to close, create an instance attribute that refers to the window.

```<code>def __init__(self):

    window = Tk()
    window.title("Tic-Tac-Toe")
    # window instance attribute
    self.window = window
    ...
</code>```

Then destroy it in the conditional that was added to addImage

```<code>    if self.doesWinX() or self.doesWinO():
        print('game over!!')
        self.window.destroy()
</code>```

This seems a bit kludgey, I've only written a couple of tkinter apps and can't remember how I kept a reference to the Tk instance.  Maybe someone will edit this answer to make it clearer.

Body:
I have a Tic Tac Toe game in tkinter that shows a grid which uses images as the "empty", "X" and "O". I used radio buttons as images with indicatoron set to 0.

I also have a list called board with 9 empty spaces. When you click on one of the empty tiles it changes to the picture to the X or O according to which turn it is and then adds either an X or O to the board list in the appropriate position. Right now,

I am trying to exit the mainloop when the condition is met that a row or column or diagonal has an X or O in all three. I have functions for these conditions and have it return True whenever a condition is met. I would like to have my mainloop exit when one of the two wins and maybe even have a pop-up that reads X Wins! or O wins!

I'm open to suggestions for a different method for determining the winner but my main concern is just getting it to stop once one of the conditions is met.

from tkinter import *

class TicTacToe():

    def __init__(self):

        window = Tk()
        window.title("Tic-Tac-Toe")

        self.emptyBox = PhotoImage(file = "image/empty.gif")
        self.xBox = PhotoImage(file = "image/x.gif")
        self.oBox = PhotoImage(file = "image/o.gif")
        self.turn = 0
        self.board = [' ',' ',' ',' ',' ',' ',' ',' ',' ']
        self.token = IntVar()

        frame1 = Frame(window, height = 150, width = 150)
        frame1.pack()

        self.label1 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 1, indicatoron = 0, command = self.addImage)
        self.label1.grid(row = 0, column = 0)
        self.label2 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 2, indicatoron = 0, command = self.addImage)
        self.label2.grid(row = 0, column = 1)
        self.label3 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 3, indicatoron = 0, command = self.addImage)
        self.label3.grid(row = 0, column = 2)

        self.label4 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 4, indicatoron = 0, command = self.addImage)
        self.label4.grid(row = 1, column = 0)
        self.label5 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 5, indicatoron = 0, command = self.addImage)
        self.label5.grid(row = 1, column = 1)
        self.label6 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 6, indicatoron = 0, command = self.addImage)
        self.label6.grid(row = 1, column = 2)

        self.label7 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 7, indicatoron = 0, command = self.addImage)
        self.label7.grid(row = 2, column = 0)
        self.label8 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 8, indicatoron = 0, command = self.addImage)
        self.label8.grid(row = 2, column = 1)
        self.label9 = Radiobutton(frame1, image = self.emptyBox, variable = self.token, value = 9, indicatoron = 0, command = self.addImage)
        self.label9.grid(row = 2, column = 2)

        window.mainloop()

    def doesWinX(self):
        #check if X wins
        if self.board[0] == 'X' and self.board[1] == 'X' and self.board[2] == 'X':
            return True
        elif self.board[3] == 'X' and self.board[4] == 'X' and self.board[5] == 'X':
            return True
        elif self.board[6] == 'X' and self.board[7] == 'X' and self.board[8] == 'X':
            return True

        elif self.board[0] == 'X' and self.board[3] == 'X' and self.board[6] == 'X':
            return True
        elif self.board[1] == 'X' and self.board[4] == 'X' and self.board[7] == 'X':
            return True
        elif self.board[2] == 'X' and self.board[5] == 'X' and self.board[8] == 'X':
            return True

        elif self.board[0] == 'X' and self.board[4] == 'X' and self.board[8] == 'X':
            return True
        elif self.board[2] == 'X' and self.board[4] == 'X' and self.board[6] == 'X':
            return True
        else:
            return False

    def doesWinO(self):
        if self.board[0] == 'O' and self.board[1] == 'O' and self.board[2] == 'O':
            return True
        elif self.board[3] == 'O' and self.board[4] == 'O' and self.board[5] == 'O':
            return True
        elif self.board[6] == 'O' and self.board[7] == 'O' and self.board[8] == 'O':
            return True

        elif self.board[0] == 'O' and self.board[3] == 'O' and self.board[6] == 'O':
            return True
        elif self.board[1] == 'O' and self.board[4] == 'O' and self.board[7] == 'O':
            return True
        elif self.board[2] == 'O' and self.board[5] == 'O' and self.board[8] == 'O':
            return True

        elif self.board[0] == 'O' and self.board[4] == 'O' and self.board[8] == 'O':
            return True
        elif self.board[2] == 'O' and self.board[4] == 'O' and self.board[6] == 'O':
            return True
        else:
            return False

    def addImage(self):
        token = self.token.get()
        while self.turn % 2 == 0:
            if token == 1 and self.board[0] == ' ':
                self.label1.config(image = self.xBox)
                self.board.pop(0)
                self.board.insert(0, 'X')
                self.turn += 1
                break
            elif token == 2 and self.board[1] == ' ':
                self.label2.config(image = self.xBox)
                self.board.pop(1)
                self.board.insert(1, 'X')
                self.turn += 1
                break
            elif token == 3 and self.board[2] == ' ':
                self.label3.config(image = self.xBox)
                self.board.pop(2)
                self.board.insert(2, 'X')
                self.turn += 1
                break
            elif token == 4 and self.board[3] == ' ':
                self.label4.config(image = self.xBox)
                self.board.pop(3)
                self.board.insert(3, 'X')
                self.turn += 1
                break
            elif token == 5 and self.board[4] == ' ':
                self.label5.config(image = self.xBox)
                self.board.pop(4)
                self.board.insert(4, 'X')
                self.turn += 1

            elif token == 6 and self.board[5] == ' ':
                self.label6.config(image = self.xBox)
                self.board.pop(5)
                self.board.insert(5, 'X')
                self.turn += 1
            elif token == 7 and self.board[6] == ' ':
                self.label7.config(image = self.xBox)
                self.board.pop(6)
                self.board.insert(6, 'X')
                self.turn += 1
            elif token == 8 and self.board[7] == ' ':
                self.label8.config(image = self.xBox)
                self.board.pop(7)
                self.board.insert(7, 'X')
                self.turn += 1
            elif token == 9 and self.board[8] == ' ':
                self.label9.config(image = self.xBox)
                self.board.pop(8)
                self.board.insert(8, 'X')
                self.turn += 1
            break

        while self.turn % 2 == 1:
            token = self.token.get()
            if token == 1 and self.board[0] == ' ':
                self.label1.config(image = self.oBox)
                self.board.pop(0)
                self.board.insert(0, 'O')
                self.turn += 1
            elif token == 2 and self.board[1] == ' ':
                self.label2.config(image = self.oBox)
                self.board.pop(1)
                self.board.insert(1, 'O')
                self.turn += 1
            elif token == 3 and self.board[2] == ' ':
                self.label3.config(image = self.oBox)
                self.board.pop(2)
                self.board.insert(2, 'O')
                self.turn += 1
            elif token == 4 and self.board[3] == ' ':
                self.label4.config(image = self.oBox)
                self.board.pop(3)
                self.board.insert(3, 'O')
                self.turn += 1
            elif token == 5 and self.board[4] == ' ':
                self.label5.config(image = self.oBox)
                self.board.pop(4)
                self.board.insert(4, 'O')
                self.turn += 1
            elif token == 6 and self.board[5] == ' ':
                self.label6.config(image = self.oBox)
                self.board.pop(5)
                self.board.insert(5, 'O')
                self.turn += 1
            elif token == 7 and self.board[6] == ' ':
                self.label7.config(image = self.oBox)
                self.board.pop(6)
                self.board.insert(6, 'O')
                self.turn += 1
                break
            elif token == 8 and self.board[7] == ' ':
                self.label8.config(image = self.oBox)
                self.board.pop(7)
                self.board.insert(7, 'O')
                self.turn += 1
            elif token == 9 and self.board[8] == ' ':
                self.label9.config(image = self.oBox)
                self.board.pop(8)
                self.board.insert(8, 'O')
                self.turn += 1
            break

TicTacToe()

Thanks for the help!

Body:
Add a conditional as the very last statement of addImage

def addImage(self):
    .....
    .....
    if self.doesWinX() or self.doesWinO():
           print('game over!!')

To get it to close, create an instance attribute that refers to the window.

def __init__(self):

    window = Tk()
    window.title("Tic-Tac-Toe")
    # window instance attribute
    self.window = window
    ...

Then destroy it in the conditional that was added to addImage

    if self.doesWinX() or self.doesWinO():
        print('game over!!')
        self.window.destroy()

This seems a bit kludgey, I've only written a couple of tkinter apps and can't remember how I kept a reference to the Tk instance.  Maybe someone will edit this answer to make it clearer.


来源: stackexchange

问:
When are nested functions generally appropriate in JavaScript?
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

```<code>var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();
</code>```

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

```<code>function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}
</code>```

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

答:
In modern JavaScript you'd put code like that in a module (CommonJS, AMD or ES6). In which case something this would be fine

```<code>const names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];

function dayName(number) {
  return names[number];
}

module.exports = {
  dayName: dayName,
};
</code>```

Otherwise yes, it does make some sense to do it his way. Your way you're recreating the names array every time you execute the function. His way it's only created once and it doesn't pollute the namespace (no one else except dayName can see the names array.

You should really look into using modules of one type or another though.

In answer to the question When are nested functions generally appropriate in JavaScript? the general answer is, when you want a closure.

In the case you posted the inner function is a closure. It closes over the names variable.

Closures are a pretty basic and common feature of JavaScript. They are especially useful with callbacks.

ContentLicense: CC BY-SA 3.0

Body:
I am learning JavaScript through this website. The link is to the specific chapter that I'm reading right now.

In the book, the author talks about keeping the implementation details of a module on a local scope. He achieves it by doing:

var dayName = function() {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return function(number) {
    return names[number];
  };
}();

I understand how this works, but I do not understand why he is doing it this way. Why wouldn't he just do...

function dayName(number) {
  var names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];
  return names[number];
}

...which to me looks like a much cleaner and readable code? Given his goal of keeping names within local scope, creating a nested lambda seems redundant.

Is there any real advantage to using the nested function in this case? Or is he using it just for educational purposes?

Thanks!

Body:
In modern JavaScript you'd put code like that in a module (CommonJS, AMD or ES6). In which case something this would be fine

const names = ["Sunday", "Monday", "Tuesday", "Wednesday",
               "Thursday", "Friday", "Saturday"];

function dayName(number) {
  return names[number];
}

module.exports = {
  dayName: dayName,
};

Otherwise yes, it does make some sense to do it his way. Your way you're recreating the names array every time you execute the function. His way it's only created once and it doesn't pollute the namespace (no one else except dayName can see the names array.

You should really look into using modules of one type or another though.

In answer to the question When are nested functions generally appropriate in JavaScript? the general answer is, when you want a closure.

In the case you posted the inner function is a closure. It closes over the names variable.

Closures are a pretty basic and common feature of JavaScript. They are especially useful with callbacks.


问:
how to write a single sql query based on combobox selection?
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

```<code>if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}
</code>```

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

答:
It is important to parameterize as well:

```<code>private const string _select = "select * from country";

void DoSomething()
{
     string sql = string.Empty;
     if (combobox1.SelectedIndex > -1)
     {
         command.Parameters.AddWithValue("@1",  (string)combobox1.SelectedValue);
         sql = " where city_name = @1";
     }
     sql = _select + sql;
     command.CommandText = sql;
     command.Execute...
}
</code>```

@un-lucky asked me how would I deal with many conditions - here is one way

```<code>var conditions = new List<string>();
if (/* condition 1*/)
{
    command.Parameters.AddWithValue("@2",  (string)cboN.SelectedItem);
    conditions.Add("col1 = @2");
}
if (/* condition 2*/)
{
    command.Parameters.AddWithValue("@3",  textBoxN.Text);
    conditions.Add("col2 = @3");
}

if (conditions.Count > 0)
    sql = _select + " where " + string.Join(" AND ", conditions.ToArray());
</code>```

Body:
I have a winform in which user input values through a combobox. I am assigning combobox value to search db. If there is no selection then the SQL server query should not use that column to filter.

example -

if (string.IsNullOrEmpty(combobox1.text)) {
  .....Select * from country
}
else if (combobox1.selectedindex > -1) {
   ....Select * from country where city_name = combobox.text
}

Is there a way to write a single query instead of using this multiple 'IF' conditions in case where user selects or doesn't select a value from combobox.

Body:
It is important to parameterize as well:

private const string _select = "select * from country";

void DoSomething()
{
     string sql = string.Empty;
     if (combobox1.SelectedIndex > -1)
     {
         command.Parameters.AddWithValue("@1",  (string)combobox1.SelectedValue);
         sql = " where city_name = @1";
     }
     sql = _select + sql;
     command.CommandText = sql;
     command.Execute...
}

@un-lucky asked me how would I deal with many conditions - here is one way

var conditions = new List<string>();
if (/* condition 1*/)
{
    command.Parameters.AddWithValue("@2",  (string)cboN.SelectedItem);
    conditions.Add("col1 = @2");
}
if (/* condition 2*/)
{
    command.Parameters.AddWithValue("@3",  textBoxN.Text);
    conditions.Add("col2 = @3");
}

if (conditions.Count > 0)
    sql = _select + " where " + string.Join(" AND ", conditions.ToArray());


问:
How to dynamically generate ng-option in angularjs
Here, from the json it will show the quantity. Based on quantity value, select option needs to generate dynamically as below.</p>

答:
you can use limitTo with ng-options to dynamically show options of select element

Wish I have got what you want.

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.selectedItem = 1;
  $scope.list = [1, 2, 3, 4];
  $scope.quantity = 1;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <select ng-model="quantity" ng-options="value as value for value in list"></select>
  <br>
  <select class="classname" ng-options="value as value for value in list | limitTo:quantity:0" ng-model="selectedItem">
    <!--<option ng-repeat="item in list | limitTo:quantity:0">{{item}}</option> -->
  </select>
  {{selectedItem}}
</div></code>```

Body:
you can use limitTo with ng-options to dynamically show options of select element

Wish I have got what you want.

angular.module("app", []).controller("myCtrl", function($scope) {
  $scope.selectedItem = 1;
  $scope.list = [1, 2, 3, 4];
  $scope.quantity = 1;
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <select ng-model="quantity" ng-options="value as value for value in list"></select>
  <br>
  <select class="classname" ng-options="value as value for value in list | limitTo:quantity:0" ng-model="selectedItem">
    <!--<option ng-repeat="item in list | limitTo:quantity:0">{{item}}</option> -->
  </select>
  {{selectedItem}}
</div>


问:
Count greater elements on right side of a current element in an array
I am trying to count the number of elements greater than the element on the right side of the array. Here my function goes.

```<code>int* SurpassersKing(int input1_size, int* input1,int* output_size)
    {
        int i,k;
        int count[input1_size];
        for  (i = 0; i < input1_size; i++)
            count[i] = 0;

        for ( i = 0; i < input1_size; i++)
        {
            for ( k = i + 1; k <input1_size; k++)
                {
                        if (input1[i] < input1[k]) {
                                 count[i]++;
                        }
                }
        }

        return count;
    }
</code>```

This is my function where I am counting greater elements in an array.

So in this following code snippet i have wriiten the main function , declaring all the veriable like output_size,counting array ,i ,k as an index for the arrays and printing the stuff , and calling counting function .

```<code>int main() {
    int output_size;
    int* output;

    int ip1_size = 0;
    int ip1_i;
    scanf("%d\n", &ip1_size);
    int ip1[ip1_size];
    for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
        int ip1_item;
        scanf("%d", &ip1_item);

        ip1[ip1_i] = ip1_item;
    }
    output = SurpassersKing(ip1_size,ip1,&output_size);
    int output_i;
    for(output_i=0; output_i < output_size; output_i++) {

        printf("%d\n", output[output_i]);

    }
    return 0;
}
</code>```

but i am not getting the output required so what can i do to improve this.

答:
Oso your code has a few errors i found when i tried to compile.

This is  a c code so use #include

Inside the function SurpassersKing you are trying to return array count which is not allowed. Never return local variables unless it is dynamically created.

The output_size never gets initilized.

This is the final code:

```<code>#include <stdio.h>
#include<stdlib.h>

int* SurpassersKing(int input1_size, int* input1)
{
    int i,k;
    int * count = (int*)malloc(input1_size*sizeof(int));
    for  (i = 0; i < input1_size; i++)
        *(count + i) = 0;

    for ( i = 0; i < input1_size; i++)
    {
        for ( k = i + 1; k <input1_size; k++)
            {
                    if (input1[i] < input1[k]) {
                             count[i]++;
                    }
            }
    }

    return count;
}

int main() {
// your code goes here
int output_size;
int* output;

int ip1_size = 0;
int ip1_i;
int output_i;

printf("Enter the size:\n");
scanf("%d",&ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
    scanf("%d",%ip1[ip1_i]);
}
output = SurpassersKing(ip1_size,ip1);
output_size = ip1_size;

for(output_i=0; output_i < output_size; output_i++) {

    printf("%d\n",output[output_i]");

}
return 0;
}
</code>```

Body:
I am trying to count the number of elements greater than the element on the right side of the array. Here my function goes.

int* SurpassersKing(int input1_size, int* input1,int* output_size)
    {
        int i,k;
        int count[input1_size];
        for  (i = 0; i < input1_size; i++)
            count[i] = 0;

        for ( i = 0; i < input1_size; i++)
        {
            for ( k = i + 1; k <input1_size; k++)
                {
                        if (input1[i] < input1[k]) {
                                 count[i]++;
                        }
                }
        }

        return count;
    }

This is my function where I am counting greater elements in an array.

So in this following code snippet i have wriiten the main function , declaring all the veriable like output_size,counting array ,i ,k as an index for the arrays and printing the stuff , and calling counting function .

int main() {
    int output_size;
    int* output;

    int ip1_size = 0;
    int ip1_i;
    scanf("%d\n", &ip1_size);
    int ip1[ip1_size];
    for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
        int ip1_item;
        scanf("%d", &ip1_item);

        ip1[ip1_i] = ip1_item;
    }
    output = SurpassersKing(ip1_size,ip1,&output_size);
    int output_i;
    for(output_i=0; output_i < output_size; output_i++) {

        printf("%d\n", output[output_i]);

    }
    return 0;
}

but i am not getting the output required so what can i do to improve this.

Body:
Oso your code has a few errors i found when i tried to compile.

This is  a c code so use #include

Inside the function SurpassersKing you are trying to return array count which is not allowed. Never return local variables unless it is dynamically created.

The output_size never gets initilized.

This is the final code:

#include <stdio.h>
#include<stdlib.h>

int* SurpassersKing(int input1_size, int* input1)
{
    int i,k;
    int * count = (int*)malloc(input1_size*sizeof(int));
    for  (i = 0; i < input1_size; i++)
        *(count + i) = 0;

    for ( i = 0; i < input1_size; i++)
    {
        for ( k = i + 1; k <input1_size; k++)
            {
                    if (input1[i] < input1[k]) {
                             count[i]++;
                    }
            }
    }

    return count;
}

int main() {
// your code goes here
int output_size;
int* output;

int ip1_size = 0;
int ip1_i;
int output_i;

printf("Enter the size:\n");
scanf("%d",&ip1_size);
int ip1[ip1_size];
for(ip1_i = 0; ip1_i < ip1_size; ip1_i++) {
    scanf("%d",%ip1[ip1_i]);
}
output = SurpassersKing(ip1_size,ip1);
output_size = ip1_size;

for(output_i=0; output_i < output_size; output_i++) {

    printf("%d\n",output[output_i]");

}
return 0;
}


问:
Needing to pass array values into an ms-access query
I have a form in Access 2010 where I have check boxes of insurance carriers.  Once the user clicks the "next" button my vba is looking to see what is checked and passing those into an array that does a preserve redim to keep it only as large as the number of carriers that were selected.  I then do a join on my array so that it will say (for example when put out to a message box) "AIG, Arch, Travelers, Zurich"

I want to take this array (called Carriers) and pass it into a query as the criteria for that query.  How would I pass this?

答: You can't pass an array as a parameter to a query, but you can perform the VBA.Join on the array in VBA, and then pass the delimited string to the query.


问:
how to get response(or responsebody) using restTempate.excute when another server send me "503 status"
(This is blueprint of our service)

```<code>webpage <-> proxy-server <-> api-server <-> datebase
[-------- my work ---------][------- not mine -------]
</code>```

I send request from proxy-server to api-server using "RestTemplate.exchange".

```<code>@Override
    public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
            throws RestClientException {

        Assert.notNull(requestEntity, "'requestEntity' must not be null");

        Type type = responseType.getType();
        RequestCallback requestCallback = httpEntityCallback(requestEntity, type);
        ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
        return execute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor);
    }
</code>```

And this is my question.

Api server make 503 error with ?VO.
They send me like this.

```<code>{
  "result": {
    "responseCode": "..."
  },
  "data": {
    "time": ...,
  }
}
</code>```

But when this response is arrived at restTemplate, restTemplate send it to errorHandler and catch exception.

```<code>(in RestTemplate.java)
protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        ResponseErrorHandler errorHandler = getErrorHandler();
        boolean hasError = errorHandler.hasError(response); // -> hasError:true!
        ...
}
</code>```

And I can't get response outside of function.
How I get this response?

答:
You need to catch HttpStatusCodeException exception for this. And you will get http status code by calling getStatusCode() and the body by calling getResponseBodyAsString() method of the exception.

Example:

```<code>try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException e) {
    return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
}
</code>```

Body:
(This is blueprint of our service)

webpage <-> proxy-server <-> api-server <-> datebase
[-------- my work ---------][------- not mine -------]

I send request from proxy-server to api-server using "RestTemplate.exchange".

@Override
    public <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType)
            throws RestClientException {

        Assert.notNull(requestEntity, "'requestEntity' must not be null");

        Type type = responseType.getType();
        RequestCallback requestCallback = httpEntityCallback(requestEntity, type);
        ResponseExtractor<ResponseEntity<T>> responseExtractor = responseEntityExtractor(type);
        return execute(requestEntity.getUrl(), requestEntity.getMethod(), requestCallback, responseExtractor);
    }

And this is my question.

Api server make 503 error with ?VO.
They send me like this.

{
  "result": {
    "responseCode": "..."
  },
  "data": {
    "time": ...,
  }
}

But when this response is arrived at restTemplate, restTemplate send it to errorHandler and catch exception.

(in RestTemplate.java)
protected void handleResponse(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
        ResponseErrorHandler errorHandler = getErrorHandler();
        boolean hasError = errorHandler.hasError(response); // -> hasError:true!
        ...
}

And I can't get response outside of function.
How I get this response?

Body:
You need to catch HttpStatusCodeException exception for this. And you will get http status code by calling getStatusCode() and the body by calling getResponseBodyAsString() method of the exception.

Example:

try {
    restTemplate.exchange(...);
} catch (HttpStatusCodeException e) {
    return new ResponseEntity<>(e.getResponseBodyAsString(), e.getStatusCode());
}


问:
Count how many months has passed since
I'm using numerals for each month. If I want to know how many months have passed since 5 (last May), how would I go about that?

```<code>$current_month = date('m');
$other_month = 5;
$months_since = ?;
</code>```

So some results would be like:

Example 1:

```<code>$current_month = 3
$other_month = 1
$months_since = 3
</code>```

Example 2:

```<code>$current_month = 3
$other_month = 9
$months_since = 7
</code>```

答:
Are you looking for this?

PHP code demo

```<code>$current_month = 3;
$other_month = 10;
if($current_month>=$other_month)
{
    echo $current_month-$other_month+1;
}
else
{
    echo (12-$other_month)+$current_month+1;
}
</code>```

Title: Count how many months has passed since

Body:
I'm using numerals for each month. If I want to know how many months have passed since 5 (last May), how would I go about that?

$current_month = date('m');
$other_month = 5;
$months_since = ?;

So some results would be like:

Example 1:

$current_month = 3
$other_month = 1
$months_since = 3

Example 2:

$current_month = 3
$other_month = 9
$months_since = 7

Body:
Are you looking for this?

PHP code demo

$current_month = 3;
$other_month = 10;
if($current_month>=$other_month)
{
    echo $current_month-$other_month+1;
}
else
{
    echo (12-$other_month)+$current_month+1;
}


问:
JavaScript Iterating through Objects
I just started using Firebase and I am having trouble iterating through database objects (i.e in JSON).

Here is a sample data

```<code>const _ = require ('underscore');
var data ={
  "posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    },
    "-JRHTHaKuITFIhnj02kE": {
      "author": "alanisawesome",
      "title": "The Turing Machine"
    }
  }
}
</code>```

I am trying to display it in a table eg:

```<code>return <table>
    <tr>
        <td>author</td>
        <td>title</td>
    </tr>
    {data.map(k=>{
    return <tr key={k}>
        <td>{k.author}</td>
        <td>{k.title}</td>
    </tr>
    }).bind(this)}
</table>
</code>```

Previously i used a completely different architecture (psql + python) and objects were being returned in a different way eg:

```<code>const _ = require ('underscore');
var data ={
  0: {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    },
    1: {
      "author": "alanisawesome",
      "title": "The Turing Machine"
    }
  }
}
</code>```

And the code worked. However the Object.map doesnot seem to work with a text value.

I would like to know best way to iterate through these data. I have tried to  used underscore's mapObject feature, forEach, each and i am having difficutly finding proper documentation to iterate these kind of datas. Any suggestion to appreciate this will be highly appreciated.

答:
map is an Array method; what you have is an object. You can use Object.values(data) to get the values of the object as an array, so you can then do Object.values(data).map.

If you can't use Object.values due to browser compatibility issues, you can also use Object.keys(data) to get an array of keys. You can then do a map to retrieve each value, something like Object.keys(data).map(key => data[key]) and you will end up with the array of values you want.

Title: JavaScript Iterating through Objects

Body:
I just started using Firebase and I am having trouble iterating through database objects (i.e in JSON).

Here is a sample data

const _ = require ('underscore');
var data ={
  "posts": {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    },
    "-JRHTHaKuITFIhnj02kE": {
      "author": "alanisawesome",
      "title": "The Turing Machine"
    }
  }
}

I am trying to display it in a table eg:

return

        author
        title

    {data.map(k=>{
    return

        {k.author}
        {k.title}

    }).bind(this)}

Previously i used a completely different architecture (psql + python) and objects were being returned in a different way eg:

const _ = require ('underscore');
var data ={
  0: {
    "-JRHTHaIs-jNPLXOQivY": {
      "author": "gracehop",
      "title": "Announcing COBOL, a New Programming Language"
    },
    1: {
      "author": "alanisawesome",
      "title": "The Turing Machine"
    }
  }
}

And the code worked. However the Object.map doesnot seem to work with a text value.

I would like to know best way to iterate through these data. I have tried to  used underscore's mapObject feature, forEach, each and i am having difficutly finding proper documentation to iterate these kind of datas. Any suggestion to appreciate this will be highly appreciated.


问:
Calling a class bool function
I have defined a public bool function in a class.  When I create an object instance of this class and type a dot after it, a list of class functions appears, so I select the bool function I want.  But when I define a bool variable and make it equal to the return of the bool function, the compiler complains about an unused variable.

My question is, where is the error?

Note: when I create the class, there wasn't any error in either class.h or class.cpp.

The user program.cpp is as follows:

答:
It is a warning, not an error.

It is warning you that you have defined a variable bool insert that you are not using for anything after the assignment (See your second picture).

Title: Calling a class bool function


问:
Comparing floating-point numbers (floats or doubles) for min/max
How to compare two different floats, to a certain degree of accuracy. I know that there are very slight imprecisions while using floats or doubles in any programming language, but which may however, be enough to cause this comparison of floats a < b to return a different value than it actually should.

I was solving a problem from the UVa Online Judge which gave me a Wrong Answer many times. It took few float values as input, albeit, to 2 decimal places. I figured out the makeshift solution, which was by splitting the input and converting it to ints, but I wouldn't prefer to use that always.

So my question is, what's the best way to compare whether a float a is lesser (or greater) than a float b, provided that the inputs of a and b are given correct to n decimal places, in this case, 2?

The language I prefer is C++.

答:
Just use math: </p>

```<code>#define PREC 0.01                 //(1/pow(10,n)), n = 2
float c = a-b;
if (abs(c) < PREC) {
    printf("a equals b");
} else if(c < 0){
    printf("b is grater than a");
} else
    printf("a is grater than b");
}
</code>```

Body:
Just use math:

#define PREC 0.01                 //(1/pow(10,n)), n = 2
float c = a-b;
if (abs(c) < PREC) {
    printf("a equals b");
} else if(c < 0){
    printf("b is grater than a");
} else
    printf("a is grater than b");
}


问:
I am trying to connect to JMX with authentication using jconsole, but I am not able to do so. But I am able to connect it without authentication
I have set this as java_opts

```<code>JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=$JMX_PORT -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.password.file=$TOMCAT_DIR/conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=$TOMCAT_DIR/conf/jmxremote.access  -Djava.rmi.server.hostname=$APP_SERVER_HOSTNAME"
</code>```

in tomcat.

I am able to connect using jconsole without any authentication, if Dcom.sun.management.jmxremote.authenticate is set as false. But, with authentication as true, I am not able to connect.

答:
Did you edit jmxremote.access and jmxremote.password?

For example:

```<code>$ vi $TOMCAT_DIR/conf/jmxremote.access
# Add "admin" account permission as follows:
admin         readwrite \
              create javax.management.monitor.*,javax.management.timer.* \
              unregister

$ vi $TOMCAT_DIR/conf/jmxremote.password
# Add "admin" account password as follows:
admin password
</code>```

Body:
I have set this as java_opts

JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=$JMX_PORT -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=true -Dcom.sun.management.jmxremote.password.file=$TOMCAT_DIR/conf/jmxremote.password -Dcom.sun.management.jmxremote.access.file=$TOMCAT_DIR/conf/jmxremote.access  -Djava.rmi.server.hostname=$APP_SERVER_HOSTNAME"

in tomcat.

I am able to connect using jconsole without any authentication, if Dcom.sun.management.jmxremote.authenticate is set as false. But, with authentication as true, I am not able to connect.

Body:
Did you edit jmxremote.access and jmxremote.password?

For example:

$ vi $TOMCAT_DIR/conf/jmxremote.access
# Add "admin" account permission as follows:
admin         readwrite \
              create javax.management.monitor.*,javax.management.timer.* \
              unregister

$ vi $TOMCAT_DIR/conf/jmxremote.password
# Add "admin" account password as follows:
admin password


问:
ordering a list of string according to name (month)
I have a list of figures and I want to create a text file (using python) with their names listed in a specific order (for a movie creation with mencoder). In particular here, the figure names include months (April, August...). I want the one for Januray first, then February and so on.

I know I could do it in an ugly way, but I am interested in a solution which would be both elegant (=pythonic?) and eventually more general.

My files are, in natural order:

cld_for_April_EISopt_1000.png

cld_for_August_EISopt_1000.png

cld_for_December_EISopt_1000.png

cld_for_February_EISopt_1000.png

cld_for_January_EISopt_1000.png

cld_for_July_EISopt_1000.png

cld_for_June_EISopt_1000.png

cld_for_March_EISopt_1000.png

cld_for_May_EISopt_1000.png

cld_for_November_EISopt_1000.png

cld_for_October_EISopt_1000.png

cld_for_September_EISopt_1000.png

And I want to have a text file with this inside:

cld_for_January_EISopt_1000.png

cld_for_February_EISopt_1000.png

cld_for_March_EISopt_1000.png

cld_for_April_EISopt_1000.png

cld_for_May_EISopt_1000.png

cld_for_June_EISopt_1000.png

cld_for_July_EISopt_1000.png

cld_for_August_EISopt_1000.png

cld_for_September_EISopt_1000.png

cld_for_October_EISopt_1000.png

cld_for_November_EISopt_1000.png

cld_for_December_EISopt_1000.png

Or more generally, if I have a list or an array or a dictionnay like:

{'pattern1': rank_in_output_list_1, ..., 'pattern12': rank_in_output_list_12}

how should I do to use it to order my file names?

So far I have played with: os.listdir, os.path.isfile, numpyp.ma.array, .compressed() or .compress() ; but I haven't been so successful.

Thanks a lot.

Christophe.

答:
Longer, but more flexible answer for ordering sequences:

```<code>import collections

def rearrange(seq, order, keyfunc):
    if not isinstance(order, collections.Mapping):
        order = {v: i for i,v in enumerate(order)}
    return sorted(seq, key=lambda x: order[keyfunc(x)])

if __name__ == '__main__':
    filenames = """
        cld_for_April_EISopt_1000.png    cld_for_August_EISopt_1000.png
        cld_for_December_EISopt_1000.png cld_for_February_EISopt_1000.png
        cld_for_January_EISopt_1000.png  cld_for_July_EISopt_1000.png
        cld_for_June_EISopt_1000.png     cld_for_March_EISopt_1000.png
        cld_for_May_EISopt_1000.png      cld_for_November_EISopt_1000.png
        cld_for_October_EISopt_1000.png  cld_for_September_EISopt_1000.png
    """.split()

    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']

    def get_month_name(filename):
        return filename.split('_')[2]

    for filename in rearrange(filenames, months, get_month_name):
        print(filename)
</code>```

Output:

cld_for_January_EISopt_1000.png
cld_for_February_EISopt_1000.png
cld_for_March_EISopt_1000.png
cld_for_April_EISopt_1000.png
  ...
```

ContentLicense: CC BY-SA 2.5

Body:
Longer, but more flexible answer for ordering sequences:

import collections

def rearrange(seq, order, keyfunc):
    if not isinstance(order, collections.Mapping):
        order = {v: i for i,v in enumerate(order)}
    return sorted(seq, key=lambda x: order[keyfunc(x)])

if __name__ == '__main__':
    filenames = """
        cld_for_April_EISopt_1000.png    cld_for_August_EISopt_1000.png
        cld_for_December_EISopt_1000.png cld_for_February_EISopt_1000.png
        cld_for_January_EISopt_1000.png  cld_for_July_EISopt_1000.png
        cld_for_June_EISopt_1000.png     cld_for_March_EISopt_1000.png
        cld_for_May_EISopt_1000.png      cld_for_November_EISopt_1000.png
        cld_for_October_EISopt_1000.png  cld_for_September_EISopt_1000.png
    """.split()

    months = ['January', 'February', 'March', 'April', 'May', 'June', 'July',
              'August', 'September', 'October', 'November', 'December']

    def get_month_name(filename):
        return filename.split('_')[2]

    for filename in rearrange(filenames, months, get_month_name):
        print(filename)

Output:

cld_for_January_EISopt_1000.png
cld_for_February_EISopt_1000.png
cld_for_March_EISopt_1000.png
cld_for_April_EISopt_1000.png
  ...


答:
As for mu understanding of the question you can create a custom filter to filter out options based on the quantity.

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.obj =  {
    "list": [
        {
    "quantity": [
            2,
            3,
            4
          ]}
    ]}
})
.filter('cust',function(){
  return function(item){
    var arr  = []
    for(var i =1; i<= parseInt(item); i++){
     arr.push(i)
    }

    return arr

  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div ng-repeat="q in obj.list">
 <div ng-repeat="i in q.quantity">
  <select ng-init="q.selectval[i] = i" class="classname" ng-model="q.selectval[i]" ng-options="value as value for (key,value) in i | cust" >

  </select>
  {{q.selectval[i]}}
</div>
</div>
</div></code>```

Title: How to dynamically generate ng-option in angularjs

Body: Here, from the json it will show the quantity. Based on quantity value, select option needs to generate dynamically as below.

Body:
As for mu understanding of the question you can create a custom filter to filter out options based on the quantity.

angular.module("app",[])
.controller("ctrl",function($scope){

$scope.obj =  {
    "list": [
        {
    "quantity": [
            2,
            3,
            4
          ]}
    ]}
})
.filter('cust',function(){
  return function(item){
    var arr  = []
    for(var i =1; i<= parseInt(item); i++){
     arr.push(i)
    }

    return arr

  }
})

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <div ng-repeat="q in obj.list">
 <div ng-repeat="i in q.quantity">
  <select ng-init="q.selectval[i] = i" class="classname" ng-model="q.selectval[i]" ng-options="value as value for (key,value) in i | cust" >

  </select>
  {{q.selectval[i]}}
</div>
</div>
</div>


答: Use the setprecison() operator. The number you put in between the parentheses will determine how many numbers pass the decimal will be included in the output. Be sure to include the iomanip library. </p>

Title: Comparing floating-point numbers (floats or doubles) for min/max

Body:
How to compare two different floats, to a certain degree of accuracy. I know that there are very slight imprecisions while using floats or doubles in any programming language, but which may however, be enough to cause this comparison of floats a < b to return a different value than it actually should.

I was solving a problem from the UVa Online Judge which gave me a Wrong Answer many times. It took few float values as input, albeit, to 2 decimal places. I figured out the makeshift solution, which was by splitting the input and converting it to ints, but I wouldn't prefer to use that always.

So my question is, what's the best way to compare whether a float a is lesser (or greater) than a float b, provided that the inputs of a and b are given correct to n decimal places, in this case, 2?

The language I prefer is C++.


问:
Mocking mongo queries
I want to mock my queries to a mongo collection and confirm that the right parameters are being set in the query.

The code being tested is

```<code>Bson query = eq("name",name);
if (version!=null) {
    query = and(query,eq("version",version));
}
Document retrievedDoc =  collection.find(query).sort(descending("version")).first();
</code>```

and the test I want to write is

```<code>Bson query = and(eq("name","test.TestClass"),eq("version",1));
when(collection.find(<some matcher>).thenReturn(result);
</code>```

however Bson doesn't implement equals and it doesn't have any obvious methods to get any of it's contents to write a custom matcher with or to test a captured Bson with.

I'm using mockito although I don't think it matters.

Is there any nice way to assert anything more about the query than it's class?

答:
I had the same question, too.
Since Bson doesn't implement equals, I just use org.bson.Document instead of Bson.

Here how I do it:

```<code>Document query = new Document("name",name);
if (version!=null) {
    query = new Document("$and", asList(query, new Document("version",version)));
}
Document retrievedDoc =  collection.find(query).sort(descending("version")).first();
</code>```

and the test should be like:

```<code>Document query = new Document("$and", asList(new Document("name","test.TestClass"), new Document("version",1)));
when(collection.find(query).thenReturn(result);
</code>```

Title: Mocking mongo queries

Body:
I want to mock my queries to a mongo collection and confirm that the right parameters are being set in the query.

The code being tested is

Bson query = eq("name",name);
if (version!=null) {
    query = and(query,eq("version",version));
}
Document retrievedDoc =  collection.find(query).sort(descending("version")).first();

and the test I want to write is

Bson query = and(eq("name","test.TestClass"),eq("version",1));
when(collection.find(<some matcher>).thenReturn(result);

however Bson doesn't implement equals and it doesn't have any obvious methods to get any of it's contents to write a custom matcher with or to test a captured Bson with.

I'm using mockito although I don't think it matters.

Is there any nice way to assert anything more about the query than it's class?

Body:
I had the same question, too.
Since Bson doesn't implement equals, I just use org.bson.Document instead of Bson.

Here how I do it:

Document query = new Document("name",name);
if (version!=null) {
    query = new Document("$and", asList(query, new Document("version",version)));
}
Document retrievedDoc =  collection.find(query).sort(descending("version")).first();

and the test should be like:

Document query = new Document("$and", asList(new Document("name","test.TestClass"), new Document("version",1)));
when(collection.find(query).thenReturn(result);


问:
MASM assembly: How do I make a Procedure?
I need to make a procedure that uses the built-in directive invoke instead of the instruction call.

So I need to know where I can place my prototype, my definition, and how I can call it?

答:
I'm not aware of a way to use proto and invoke with fast call (other than this is default for 64 bit mode). Example 32 bit flat model stand alone asm code using C library:

```<code>;       include C library
        if              @Version EQ 611 ;if ml 6.11
        includelib      libc
        else                            ;else ml 7.0 or later
        includelib      msvcrtd
        includelib      oldnames
        endif

        .586p
        .model  flat,c
        .data           ;  initialized data
var1    dd      012345678h
var2    dd      087654321h
        .data?          ;uninitialized data
        .stack  4096
        .code

example proto   near c,arg1:dword,arg2:dword

main    proc    near
        invoke  example,var1,var2
        xor     eax,eax
        ret
main    endp

;       argument names don't have to match proto
example proc    near c,a1:dword,a2:dword
        mov     eax,a1
        add     eax,a2
        ret
example endp

        end
</code>```

Microsoft example with variable number of arguments (vararg):

https://support.microsoft.com/en-us/help/73407/using-proto-and-invoke-to-call-a-c-function-from-masm

Body:
I'm not aware of a way to use proto and invoke with fast call (other than this is default for 64 bit mode). Example 32 bit flat model stand alone asm code using C library:

;       include C library
        if              @Version EQ 611 ;if ml 6.11
        includelib      libc
        else                            ;else ml 7.0 or later
        includelib      msvcrtd
        includelib      oldnames
        endif

        .586p
        .model  flat,c
        .data           ;  initialized data
var1    dd      012345678h
var2    dd      087654321h
        .data?          ;uninitialized data
        .stack  4096
        .code

example proto   near c,arg1:dword,arg2:dword

main    proc    near
        invoke  example,var1,var2
        xor     eax,eax
        ret
main    endp

;       argument names don't have to match proto
example proc    near c,a1:dword,a2:dword
        mov     eax,a1
        add     eax,a2
        ret
example endp

        end

Microsoft example with variable number of arguments (vararg):

https://support.microsoft.com/en-us/help/73407/using-proto-and-invoke-to-call-a-c-function-from-masm


问:
bootstrap button shows blue outline when clicked
I added this but still the blue outline appear when the button is clicked.

```<code>.btn:focus {
  outline: none;
}
</code>```

how to remove that ugly thingy?

答:
This may help if someone still has this question unresolved.

(function() {
  $('button').on('click', function() {
    $("#action").html("button was clicked");
    console.log("the button was clicked");
  });
})();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-clear {
  background-color: transparent !important;
  border-style: none !important;
  cursor: pointer;
}

.btn-clear:active,
.btn-clear:focus {
  outline-style: none !important;
  outline-color: transparent;
}</code>```

<button>Action</button>

<button class="btn-clear">Action</button>

```

Body:
I added this but still the blue outline appear when the button is clicked.

.btn:focus {
  outline: none;
}

how to remove that ugly thingy?

Body:
This may help if someone still has this question unresolved.

(function() {
  $('button').on('click', function() {
    $("#action").html("button was clicked");
    console.log("the button was clicked");
  });
})();

.btn-clear {
  background-color: transparent !important;
  border-style: none !important;
  cursor: pointer;
}

.btn-clear:active,
.btn-clear:focus {
  outline-style: none !important;
  outline-color: transparent;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- this button has default style -->
<button>Action</button>
<!-- this button is clear of style -->
<button class="btn-clear">Action</button>

<label id="action"></label>


问:
python: is there a disadvantage to from package import * besides namespace collision
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

```<code>from package import *
</code>```

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

```<code>for name in [namespace,namespace]:
    from package import name
</code>```

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.

答:
you can import like from PIL import Image, ImageDraw

what is imported by from x import * is limited to the list __all__ in x if it exists

importing at runtime if the module name isn't know or fixed in the code must be done with __import__ but you shouldn't have to do that

Body:
I'm creating a class to extend a package, and prior to class instantiation I don't know which subset of the package's namespace I need.  I've been careful about avoiding namespace conflicts in my code, so, does

from package import *

create problems besides name conflicts?

Is it better to examine the class's input and import only the names I need (at runtime) in the __init__ ??

Can python import from a set [] ?

does

for name in [namespace,namespace]:
    from package import name

make any sense?

I hope this question doesn't seem like unnecessary hand-ringing, i'm just super new to python and don't want to do the one thing every 'beginnger's guide' says not to do (from pkg import * ) unless I'm sure there's no alternative.

thoughts, advice welcome.


问:
Angularjs - Single Page Application Not Rendering Page Templates
So I was trying to make a SPA using angular but when I try to open my page on a localhost the navbar displays but none of the content I have in separate HTML documents loads. I feel as if I'm missing something but I'm not sure what.

HTML

```<code><html lang="en" ng-app="App"><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!--External Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <!-- Internal Styles -->
    <link rel="stylesheet" href="css/style.css">

    <!-- External Scripts -->
    <script src="js/angular.min.js"></script>
    <script src="js/angular-route.min.js"></script>
    <script src="js/anime.min.js"></script>
    <script src="js/anime.js"></script>

    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>
    <script src="https://use.fontawesome.com/a1dcc6967b.js"></script>

    <!-- Internal Scripts -->
    <script type="text/javascript" src="js/script.js"></script>
    <script type="text/javascript">

        var CSStransforms = anime({
            targets: '#CSStransforms .el',
            translateX: 250,
            scale: 2,
            rotate: '1turn'
        });

    </script>

    <title>Bootsrap Shell With Navabar</title>

</head><body ng-controller="mainController">
      <nav class="navbar navbar-toggleable-md navbar-inverse bg-inverse fixed-top">

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
        </button>
        <a class="navbar-brand" href="/">Navbar</a>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item ">
                    <a class="nav-link active" href="#/">Home<span class="sr-only">(current)</span></a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#/about">About</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="#/Page-Name">Page</a>
                </li>
                <!-- Dropdown - Delete from this comment to the next if you don't want it -->
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown</a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#">Action</a>
                        <a class="dropdown-item" href="#">Another action</a>
                        <a class="dropdown-item" href="#">Something else here</a>
                        <div class="dropdown-divider"></div>
                        <a class="dropdown-item" href="#">Separted</a>
                    </div>
                </li>
            </ul>
            <ul class="navbar-nav ml-auto">
                <li class="nav-item dropdown user">

                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Signed in as </a>
                    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" href="#"><i class="fa fa-user-circle" aria-hidden="true"></i> Edit Profile</a>
                        <a class="dropdown-item" href="/logout.php"><i class="fa fa-sign-out" aria-hidden="true"></i> Log Out</a>
                    </div>

                    <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">User</a>
                    <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                        <a class="dropdown-item" data-toggle="modal" data-target="#register-modal" href="#"><i class="fa fa-user-circle" aria-hidden="true"></i> Register</a>
                        <a class="dropdown-item" data-toggle="modal" data-target="#login-modal" href="#"><i class="fa fa-sign-in" aria-hidden="true"></i> Login</a>
                    </div>

                </li>
            </ul>
        </div>

    </nav>

    <div id="login-modal" class="modal fade" aria-labelledby="myModalLabel" aria-hidden="true" tabindex="-1" role="dialog">
        <div class="modal-dialog">
            <div class="login-modal-container">
                <form id="login-form" role="form">
                    <div class="modal-body">
                        <h2 class="modal-text">Login To Your Account </h2>
                        <div id="err-msg"></div>
                        <div class="form-group">
                            <input type="text" id="username" name="username" placeholder="Your Username" class="form-control input-lg" />
                        </div>
                        <div class="form-group">
                            <input type="password" id="password" name="password" placeholder="Password" class="form-control input-lg" />
                        </div>
                        <div class="form-group">
                            <div id="captcha"></div>
                        </div>
                        <div class="form-group">
                            <input type="submit" id="login" name="login" value="Log In" class="btn btn-primary btn-block btn-lg" data-toggle="tooltip" data-placement="bottom" title="Press To Sign In" />
                        </div>
                    </div>
                    <div class="modal-footer modal-text">
                        Don't have an account? <a data-toggle="modal" data-target="#register-modal" href="#" data-dismiss="modal">Sign Up here</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div id="main">

        <div ng-view></div>

    </div>

</body>

</html>
</code>```

JavaScript

```<code>var App = angular.module('App', ['ngRoute']);

// configure our routes
App.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        })

        .otherwise({redirectTo: '/'});
});

// create the controller and inject Angular's $scope
App.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

App.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

App.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
});
</code>```

Edit

Bower was used to get angular

```<code>{"name": "site","authors": ["Luculent"],"description": "","main":"index.php","license": "MIT","homepage": "/","ignore": ["**/.*","node_modules","bower_components","test","tests"]}
</code>```

Edit 2

got angular 1.6.3 but still does not work

Edit 3

when I launch the page it generates the following exception:

```<code>Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=App&p1=Error%3A%20%…%20%20%20at%20eb%20(http%3A%2F%2Flocalhost%2Fjs%2Fangular.min.js%3A46%3A44)
at angular.min.js:6
at angular.min.js:42
at p (angular.min.js:7)
at g (angular.min.js:41)
at eb (angular.min.js:46)
at c (angular.min.js:21)
at Pc (angular.min.js:22)
at ue (angular.min.js:20)
at angular.min.js:332
at HTMLDocument.b (angular.min.js:38)
</code>```

But as you can see above I have both angular.js and angular-route.

答:
did you include angular route

Its no longer included into angularjs by default

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js" type="text/javascript"></script>
</code>```

Body:
So I was trying to make a SPA using angular but when I try to open my page on a localhost the navbar displays but none of the content I have in separate HTML documents loads. I feel as if I'm missing something but I'm not sure what.

HTML

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

    <link rel="stylesheet" href="css/style.css">

    <title>Bootsrap Shell With Navabar</title>

        <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

        </button>
        Navbar

                    Home(current)

                    About

                    Page

                    Dropdown

                        Action
                        Another action
                        Something else here

                        Separted

                    Signed in as

                         Edit Profile
                         Log Out

                    User

                         Register
                         Login

                <form id="login-form" role="form">

Login To Your Account

                            <input type="text" id="username" name="username" placeholder="Your Username" class="form-control input-lg" />

                            <input type="password" id="password" name="password" placeholder="Password" class="form-control input-lg" />

                            <input type="submit" id="login" name="login" value="Log In" class="btn btn-primary btn-block btn-lg" data-toggle="tooltip" data-placement="bottom" title="Press To Sign In" />

                        Don't have an account? Sign Up here

                </form>

JavaScript

var App = angular.module('App', ['ngRoute']);

// configure our routes
App.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        })

        .otherwise({redirectTo: '/'});
});

// create the controller and inject Angular's $scope
App.controller('mainController', function($scope) {
    // create a message to display in our view
    $scope.message = 'Everyone come and see how good I look!';
});

App.controller('aboutController', function($scope) {
    $scope.message = 'Look! I am an about page.';
});

App.controller('contactController', function($scope) {
    $scope.message = 'Contact us! JK. This is just a demo.';
});

Edit

Bower was used to get angular

{"name": "site","authors": ["Luculent"],"description": "","main":"index.php","license": "MIT","homepage": "/","ignore": ["**/.*","node_modules","bower_components","test","tests"]}

Edit 2

got angular 1.6.3 but still does not work

Edit 3

when I launch the page it generates the following exception:

Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.6.3/$injector/modulerr?p0=App&p1=Error%3A%20%…%20%20%20at%20eb%20(http%3A%2F%2Flocalhost%2Fjs%2Fangular.min.js%3A46%3A44)
at angular.min.js:6
at angular.min.js:42
at p (angular.min.js:7)
at g (angular.min.js:41)
at eb (angular.min.js:46)
at c (angular.min.js:21)
at Pc (angular.min.js:22)
at ue (angular.min.js:20)
at angular.min.js:332
at HTMLDocument.b (angular.min.js:38)

But as you can see above I have both angular.js and angular-route.

Body:
did you include angular route

Its no longer included into angularjs by default

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular-route.js" type="text/javascript"></script>


问:
java -eclipse-Resource leak: 'appContext' is never closed
I create a small bean class in Eclipse. It is working in NetBeans but in Eclipse it says

Resource leak: 'appContext' is never closed.

I closed it like this appContext.close();
but it is not working.

//class drawingapplication

```<code>import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class drawingapplication {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
        Triangle triangle =(Triangle) appContext.getBean("triangle");
        triangle.draw();
    }
}
</code>```

// class Triangle

```<code>package org.spring.javabeans;

public class Triangle {
    public void draw(){
        System.out.println("triangle drawan");
    }
}
</code>```

//spring.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN""http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="triangle" class="org.spring.javabeans.Triangle"/>
</beans>
</code>```

答:
```<code>package org.spring.javabeans ;

import  org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApplication {

public static void main(String[] args) {
    ClassPathXmlApplicationContext appContext= new ClassPathXmlApplicationContext("Spring.xml");
    Triangle triangle= (Triangle) appContext.getBean("triangle");
    appContext.close();
    triangle.draw();

}
</code>```

<p>}</p>

Body:
I create a small bean class in Eclipse. It is working in NetBeans but in Eclipse it says

Resource leak: 'appContext' is never closed.

I closed it like this appContext.close();
but it is not working.

//class drawingapplication

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class drawingapplication {

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");
        Triangle triangle =(Triangle) appContext.getBean("triangle");
        triangle.draw();
    }
}

// class Triangle

package org.spring.javabeans;

public class Triangle {
    public void draw(){
        System.out.println("triangle drawan");
    }
}

//spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN""http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
    <bean id="triangle" class="org.spring.javabeans.Triangle"/>
</beans>

Body:
package org.spring.javabeans ;

import  org.springframework.context.support.ClassPathXmlApplicationContext;

public class DrawingApplication {

public static void main(String[] args) {
    ClassPathXmlApplicationContext appContext= new ClassPathXmlApplicationContext("Spring.xml");
    Triangle triangle= (Triangle) appContext.getBean("triangle");
    appContext.close();
    triangle.draw();

}

}


问:
Can I set offset position on Storyboard?
Can I write like the code below on Storyboard?</p>

```<code>let button = UIButton()
button.titleLabel.center = CGPoint(x:button.titleLabel.center.x, y:button.titleLabel.center.y + 30)
</code>```

答:
Look into UIEdgeInsets and the UIButton property titleEdgeInsets.

```<code>button.titleLabelInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 30)
</code>```

Depending on your exact needs and code, this should do what you need. (FYI - there is a imageEdgeInsets also.)

Body:
Can I write like the code below on Storyboard?

let button = UIButton()
button.titleLabel.center = CGPoint(x:button.titleLabel.center.x, y:button.titleLabel.center.y + 30)

Body:
Look into UIEdgeInsets and the UIButton property titleEdgeInsets.

button.titleLabelInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 30)

Depending on your exact needs and code, this should do what you need. (FYI - there is a imageEdgeInsets also.)


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
The most glaring error I can see is that an IList is definitely different from an IList<T>. An IList is non-generic (e.g., ArrayList).

So your method signature should be:

```<code>public static IList<T> LoadObjectListAll()
</code>```

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

Body:
The most glaring error I can see is that an IList is definitely different from an IList<T>. An IList is non-generic (e.g., ArrayList).

So your method signature should be:

public static IList<T> LoadObjectListAll()

OwnerDisplayName: Jon Limjap

LastEditorDisplayName: Orion Edwards


问:
How to decide where to handle an exception - in scope of function it been thrown or in global one?
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

```<code>
class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}
</code>```

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

答:
The basic rule is that you only catch exceptions in that part of the code, where you can actually handle it.  By handling it I mean that you can take some action based upon the exception thrown, for instance trying to create the socket another time, or trying to use a different configuration.

Additionally, exceptions which cross library-boundaries need to be reviewed.  Depending on the context you may want to catch them and rethrow a different type of exception, for instance to hide implementation details from the library client.

Body:
I`m writing client-server app for windows using WinSock and I have class for server.

while initialising server I have such code:

class Server {
    static const int MaxClients = 10;
    std::vector connections;
    CRITICAL_SECTION cs;
    int port;
    SOCKET ServerSocket;
    sockaddr_in ServerAddress;
    void init();
public:
    Server(int Port);
    void addConnection(const Client& newClient);
    void closeConnection(int index);
    void Listen();
    int size();
    /*virtual void ClientService();
    virtual void SendMsg(const std::string& msg);*/
    virtual ~Server();
};

void Server::init() {
    WSADATA wsaData;
    if(WSAStartup(MAKEWORD(2, 2), &wsaData))
        throw Exception("WinSock init failed");
    ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (ServerSocket == INVALID_SOCKET)
        throw Exception("Socket failed to create!");
    ServerAddress.sin_family = AF_INET;
    ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
    ServerAddress.sin_port = htons(port);
    if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
    {
        throw Exception("Binding failed");
        closesocket(ServerSocket);
    }
}

where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on?

OwnerDisplayName: gimpf


问:
not malicious hidden link
hey i'm using a jquery plugin Fancybox, which is a Lightbox type plugin.

This plugin can only be triggered by clicking a link. I want to show the plugin on PostBack.

 I have no problem doing this programmatically.
My concerns are purely from an SEO perspective. How can I add a hidden link that wouldn't be identified as trying to cheat Google and other search engines.

答:
I don't believe there is a sure fire way to do this (otherwise it would be exploited and then become bad practise again). Having said that it appears to be quite rare that this happens. I use hidden elements fairly frequently to ensure accessibility and I've not had a problem before.

Check out this post and comments for some additional thoughts.

Title: not malicious hidden link


问:
I can't figure out why there are extra parenthesis in my console
I'm learning the basics of programming and I can't seem to understand why my console is displaying extra parenthesis with the following code:

```<code>// My Constants Dictionary!

let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50

// Game Stats

func playerOneStats() {
    let playerOneScore = (numberTwoScore) + (numberThreeScore) + (numberOneScore)
    print ("Player one has scored \(playerOneScore) points.")
        }

func playerTwoStats() {
    let playerTwoScore = (numberFiveScore) + (numberOneScore) + (numberOneScore)
    print ("Player two has scored \(playerTwoScore) points.")
        }

func showStats() {
    print(playerOneStats())
    print(playerTwoStats())
        }

showStats()
</code>```

My console shows this:

```<code>Player one has scored 60 points.
()
Player two has scored 70 points.
()
</code>```

And my question is, why are those extra parenthesis being printed on console at the end of each player's score?

答:
I already changed it and figured it out!

```<code>// My Constants Dictionary!
let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50
let initialScore = 150
let missedDart = 0

// Game Stats
func playerOneStats() {
    var playerOneScore = initialScore - numberTwoScore
    playerOneScore = playerOneScore - numberThreeScore
    playerOneScore = playerOneScore - numberOneScore
    print ("Player one has a final score of \(playerOneScore) points.")
        }
func playerTwoStats() {
    var playerTwoScore = initialScore - numberFiveScore
    playerTwoScore = playerTwoScore - missedDart
    playerTwoScore = playerTwoScore - numberOneScore
    print("Player two has a final score of \(playerTwoScore) points.")
        }

playerOneStats()
playerTwoStats()
</code>```

This was my first post on Stack, thank you all guys for your rapid responses! :D

Body:
I'm learning the basics of programming and I can't seem to understand why my console is displaying extra parenthesis with the following code:

// My Constants Dictionary!

let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50

// Game Stats

func playerOneStats() {
    let playerOneScore = (numberTwoScore) + (numberThreeScore) + (numberOneScore)
    print ("Player one has scored \(playerOneScore) points.")
        }

func playerTwoStats() {
    let playerTwoScore = (numberFiveScore) + (numberOneScore) + (numberOneScore)
    print ("Player two has scored \(playerTwoScore) points.")
        }

func showStats() {
    print(playerOneStats())
    print(playerTwoStats())
        }

showStats()

My console shows this:

Player one has scored 60 points.
()
Player two has scored 70 points.
()

And my question is, why are those extra parenthesis being printed on console at the end of each player's score?

Body:
I already changed it and figured it out!

// My Constants Dictionary!
let numberOneScore = 10
let numberTwoScore = 20
let numberThreeScore = 30
let numberFourScore = 40
let numberFiveScore = 50
let initialScore = 150
let missedDart = 0

// Game Stats
func playerOneStats() {
    var playerOneScore = initialScore - numberTwoScore
    playerOneScore = playerOneScore - numberThreeScore
    playerOneScore = playerOneScore - numberOneScore
    print ("Player one has a final score of \(playerOneScore) points.")
        }
func playerTwoStats() {
    var playerTwoScore = initialScore - numberFiveScore
    playerTwoScore = playerTwoScore - missedDart
    playerTwoScore = playerTwoScore - numberOneScore
    print("Player two has a final score of \(playerTwoScore) points.")
        }

playerOneStats()
playerTwoStats()

This was my first post on Stack, thank you all guys for your rapid responses! :D


问:
While loop in bash script breaks systemd service
I'm on Debian and I have a systemd service that calls a bash script.

The script contains an infinite while loop, as I need it to check something every X seconds infinitely.

The systemd service crashes once it hits the "while true; do" line.

The script runs fine if I execute it manually.
Why doesn't systemd like it? What do I do?

Here are the service and the script. As I've indicated, an echo statement before the "while true; do" prints. The echo statement after the "while true; do" line does not print.

/etc/systemd/system/stream.service:

```<code>[Service]
WorkingDirectory=/home/pi/
ExecStart=/home/pi/joi_main.sh
Restart=no
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=stream_service
User=pi
Group=pi
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target
</code>```

/home/pi/joi_main.sh:

```<code>#!/bin/bash -e

today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2

#Wait 120s for system to finish booting
sleep 120

#Initial config
export AUDIODEV=mic_mono
export AUDIODRIVER=alsa
sudo sysctl fs.pipe-max-size=1048576

echo "This line prints"

# Check if video buffer is full every minute. if full, the stream needs to restart
while true; do
    echo "This line doesn't"
    if grep "100% full" /home/pi/video_buffer_usage.txt; then
        echo "Buffer is full!"
    # Kill existing processes
        pkill -f “raspivid|rec|buffer|ffmpeg”
    # Wait 10s
         sleep 10
         ./joi_stream.sh &
    fi
    sleep 60
done
</code>```

Journalctl seems completely unhelpful, but here it is. No errors. Why is "session closed"?

```<code>Mar 31 02:13:41 raspberrypi sudo[1369]: pi : TTY=unknown ; PWD=/home/pi ; USER=root ; COMMAND=/sbin/sysctl fs.pipe-max-size=1048576
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session opened for user root by (uid=0)
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session closed for user root
</code>```

(Please don't tell me to start yet another systemd service for just this while loop. I want it to be part of this main script because it needs to run after everything else, and if I turn off the main service I don't want the while loop running either, so maintaining two systemd services would only add troube.)

答: FYI, everything works if I call /home/pi/joi_main.sh from /etc/rc.local instead of using a systemd service. I'll use rc.local and kill the service.</p>

Body:
I'm on Debian and I have a systemd service that calls a bash script.

The script contains an infinite while loop, as I need it to check something every X seconds infinitely.

The systemd service crashes once it hits the "while true; do" line.

The script runs fine if I execute it manually.
Why doesn't systemd like it? What do I do?

Here are the service and the script. As I've indicated, an echo statement before the "while true; do" prints. The echo statement after the "while true; do" line does not print.

/etc/systemd/system/stream.service:

[Service]
WorkingDirectory=/home/pi/
ExecStart=/home/pi/joi_main.sh
Restart=no
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=stream_service
User=pi
Group=pi
Environment=NODE_ENV=production
[Install]
WantedBy=multi-user.target

/home/pi/joi_main.sh:

#!/bin/bash -e

today=`/bin/date '+%Y_%m_%d__%H_%M_%S'`
exec 2> "/home/pi/stream_logs/$today.$RANDOM.log"
exec 1>&2

#Wait 120s for system to finish booting
sleep 120

#Initial config
export AUDIODEV=mic_mono
export AUDIODRIVER=alsa
sudo sysctl fs.pipe-max-size=1048576

echo "This line prints"

# Check if video buffer is full every minute. if full, the stream needs to restart
while true; do
    echo "This line doesn't"
    if grep "100% full" /home/pi/video_buffer_usage.txt; then
        echo "Buffer is full!"
    # Kill existing processes
        pkill -f “raspivid|rec|buffer|ffmpeg”
    # Wait 10s
         sleep 10
         ./joi_stream.sh &
    fi
    sleep 60
done

Journalctl seems completely unhelpful, but here it is. No errors. Why is "session closed"?

Mar 31 02:13:41 raspberrypi sudo[1369]: pi : TTY=unknown ; PWD=/home/pi ; USER=root ; COMMAND=/sbin/sysctl fs.pipe-max-size=1048576
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session opened for user root by (uid=0)
Mar 31 02:13:41 raspberrypi sudo[1369]: pam_unix(sudo:session): session closed for user root

(Please don't tell me to start yet another systemd service for just this while loop. I want it to be part of this main script because it needs to run after everything else, and if I turn off the main service I don't want the while loop running either, so maintaining two systemd services would only add troube.)


问:
PHP/MySQL alternatives to WordPress?
I'm having a hard time believing there isn't already a good question with solid answers/discussion about this, but I didn't have any luck searching one up. Please link+close if you know of one. Certainly no hard feelings...

that being said,

I'm looking for a PHP+MySQL blog framework that's not named WordPress, and I have the following basic requirements:

relatively "light" aka easily edited/hacked/augmented (clean code, good structure, etc)

solid image support (upload, resize, etc)

solid comments system (including some sort of human verification)

Not too bad, right?

Normally I just hop over to Wikipedia for this sort of thing, but their List of CMS is uncharacteristically lacking in cross-comparison details.

Picking through that will take me awhile. Is there anyone out there who has been down the same road as I and would like to toss out some suggestions while I peruse Wikipedia's list?

Thank you!

EDIT - I finally found a similar question, by the masterly Pekka

答:
If you don't like Worpdress, may be you can use Joomla, It's not only designed for blogging but can be used for this purpose.

Joomla passes the HTML validator.

Title: PHP/MySQL alternatives to WordPress?