问:
I made this code to make a tic-tac-toe game without a GUI in PYTHON
I made this code on tic-tac-toe in python and after iterating it works fine but in between the computer stops giving input. My code involves a user vs computer game. Please help me I know my code doesn't contain comments but I hope you will understand and I am a beginner so please help me!!!

In this code, the computer first asks you a choice to take O or X and then does a toss in which you enter 1 or 0 and compares it to a variable that has a random value between 1 and 0. Then according to toss either the user plays first or the computer.

For computer I used the randint() function so that it chooses the row and column in which it places X or O. In every iteration the code checks whether the random row or column computer gets does not matches with the already filled ones. So this is all about this code!!

import random
row1=None
column1=None
row2 = None
column2 = None
data1=[]
data2=[]
data3=[]
data4=[]
count=0
count2=0
print("Welcome to TIC-TAC-TOE!!")
tic=input("Enter O or X as your choice --> ")
if tic=='O':
    tac='X'
else:
    tac='O'
block=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
i=0
choice=int(input("Enter 1 for Head and 0 for Tail --> "))
x=random.randint(0,1)
if choice==x:
    print("You won the toss you get the first chance : ")
    print("## Enter the row and column you want to put your choice in ##")
    row1=int(input("Row --> "))
    data1.append(row1)
    column1=int(input("Column --> "))
    data2.append(column1)
    block[row1-1][column1-1]=tic
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2!=0:
            print("## A.I ##")
            if row2!=None and column2!=None:
                row2=random.randint(1,3)
                data3.append(row2)
                index1+=1
                length1=len(data3)
                for j in data1:
                    if row2==j:
                        count+=1
                for k in range(0,index1):
                    if row2==data3[k]:
                        count2+=1
                while count>0 or count2>0:
                    row2=random.randint(1,3)
                    for j in data1:
                        if row2 == j:
                            count += 1
                    for k in range(0, index1):
                        if row2 == data3[k]:
                            count2 += 1
                data3[index1]=row2
                column2=random.randint(1,3)
                data4.append(column2)
                index2+=1
                length2=len(data4)
                count=0
                count2=0
                for j in data2:
                    if row2==j:
                        count+=1
                for k in range(0,index2):
                    if column2==data4[k]:
                        count2+=1
                while count>0 or count2>0:
                    column2=random.randint(1,3)
                    for j in data2:
                        if row2 == j:
                            count += 1
                    for k in range(0, index2):
                        if column2 == data4[k]:
                            count2 += 1
                data4[index2]=column2
                block[row2-1][column2-1] = tac
            else:
                row2=random.randint(1,3)
                data3.append(row2)
                index1=0
                for j in data1:
                    if row2==j:
                        count+=1
                while count>0:
                    count=0
                    row2=random.randint(1,3)
                    data3[0]=row2
                    for j in data1:
                        if row2 == j:
                            count += 1
                column2=random.randint(1,3)
                data4.append(column2)
                index2=0
                count = 0
                for j in data2:
                    if row2 == j:
                        count += 1
                while count>0:
                    count=0
                    column2=random.randint(1,3)
                    data4[0]=column2
                    for j in data2:
                        if row2 == j:
                            count += 1
                block[row2 - 1][column2 - 1] = tac
            #block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2==0:
            print('## Your Turn ##')
            row1=int(input("Row --> "))
            data1.append(row1)
            column1=int(input("Column --> "))
            data2.append(column2)
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        else:
            print("Draw!!")
            break
else:
    print("## A.I won the toss ##")
    print("## A.I ##")
    row2=random.randint(1,3)
    data3.append(row2)
    index1=0
    column2=random.randint(1,3)
    data4.append(column2)
    index2=0
    block[row2-1][column2-1]=tac
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2==0:
            print("## A.I ##")
            row2=random.randint(1,3)
            data3.append(row2)
            index1+=1
            length1 = len(data3)
            for j in data1:
                if row2==j:
                    count+=1
            for k in range(0,index1):
                if row2==data3[k]:
                    count2+=1
            while count>0 or count2>0:
                count=0
                count2=0
                row2=random.randint(1,3)
                for j in data1:
                    if row2 == j:
                        count += 1
                for k in range(0,index1):
                    if row2==data3[k]:
                        count2+=1
            data3[index1]=row2
            count=0
            count2=0
            column2=random.randint(1,3)
            data4.append(column2)
            index2+=1
            length2 = len(data4)
            for j in data2:
                if column2==j:
                    count+=1
            for k in range(0,index2):
                if column2==data4[k]:
                    count2+=1
            while count>0 or count2>0:
                count=0
                count2=0
                column2=random.randint(1,3)
                for j in data2:
                    if column2 == j:
                        count += 1
                for k in range(0,index2):
                    if column2==data4[k]:
                        count2+=1
            data4[index2]=column2
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2!=0:
            print("## Your Turn ##")
            row1=int(input("Row --> "))
            data1.append(row1)
            column1=int(input("Column --> "))
            data2.append(column2)
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        else:
            print("Draw!!")
            break
print("Thanks for playing!!")
```

答:
I changed the code a bit and removed the while loops instead i replaced it with another while loop in which it checks whether the  place with that row and column has white space or not if not then the column keeps on changing randomly until a place comes where there is a white space.Now for the row i simply checked whether the whole row is occupied or not if it is then the row keeps on changing randomly.This whole logic was changed for just the computer's turn.and guess what i reduced the code from 300 lines to 188 lines like 50%

Also changed the logic for draw it was rekt basically it just now checks whether all the places are not white spaces if yes then it gives draw

The Improved Code

```<code>import random
row1=None
column1=None
row2 = None
column2 = None
print("Welcome to TIC-TAC-TOE!!")
tic=input("Enter O or X as your choice --> ")
if tic=='O':
    tac='X'
else:
    tac='O'
block=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
i=0
choice=int(input("Enter 1 for Head and 0 for Tail --> "))
x=random.randint(0,1)
if choice==x:
    print("You won the toss you get the first chance : ")
    print("## Enter the row and column you want to put your choice in ##")
    row1=int(input("Row --> "))
    column1=int(input("Column --> "))
    block[row1-1][column1-1]=tic
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    index1=0
    index2=0
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2!=0:
            print("## A.I ##")
            if row2!=None and column2!=None:
                row2=random.randint(1,3)
                while block[row2-1][0]!=' ' and block[row2-1][1]!=' ' and block[row2-1][2]!=' ':
                    row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            else:
                row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2==0:
            print('## Your Turn ##')
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
else:
    print("## A.I won the toss ##")
    print("## A.I ##")
    row2=random.randint(1,3)
    column2=random.randint(1,3)
    block[row2-1][column2-1]=tac
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2==0:
            print("## A.I ##")
            row2=random.randint(1,3)
            while block[row2 - 1][0] != ' ' and block[row2 - 1][1] != ' ' and block[row2 - 1][2] != ' ':
                row2 = random.randint(1, 3)
            column2=random.randint(1,3)
            while block[row2-1][column2-1]!=' ':
                column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2!=0:
            print("## Your Turn ##")
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
print("Thanks for playing!!")
</code>```

Body:
I changed the code a bit and removed the while loops instead i replaced it with another while loop in which it checks whether the  place with that row and column has white space or not if not then the column keeps on changing randomly until a place comes where there is a white space.Now for the row i simply checked whether the whole row is occupied or not if it is then the row keeps on changing randomly.This whole logic was changed for just the computer's turn.and guess what i reduced the code from 300 lines to 188 lines like 50%

Also changed the logic for draw it was rekt basically it just now checks whether all the places are not white spaces if yes then it gives draw

The Improved Code

import random
row1=None
column1=None
row2 = None
column2 = None
print("Welcome to TIC-TAC-TOE!!")
tic=input("Enter O or X as your choice --> ")
if tic=='O':
    tac='X'
else:
    tac='O'
block=[[' ',' ',' '],[' ',' ',' '],[' ',' ',' ']]
i=0
choice=int(input("Enter 1 for Head and 0 for Tail --> "))
x=random.randint(0,1)
if choice==x:
    print("You won the toss you get the first chance : ")
    print("## Enter the row and column you want to put your choice in ##")
    row1=int(input("Row --> "))
    column1=int(input("Column --> "))
    block[row1-1][column1-1]=tic
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    index1=0
    index2=0
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2!=0:
            print("## A.I ##")
            if row2!=None and column2!=None:
                row2=random.randint(1,3)
                while block[row2-1][0]!=' ' and block[row2-1][1]!=' ' and block[row2-1][2]!=' ':
                    row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            else:
                row2=random.randint(1,3)
                column2=random.randint(1,3)
                while block[row2-1][column2-1]!=' ':
                    column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2==0:
            print('## Your Turn ##')
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
else:
    print("## A.I won the toss ##")
    print("## A.I ##")
    row2=random.randint(1,3)
    column2=random.randint(1,3)
    block[row2-1][column2-1]=tac
    print(block[0][0],"|",block[0][1],"|",block[0][2])
    print(block[1][0],"|",block[1][1],"|",block[1][2])
    print(block[2][0],"|",block[2][1],"|",block[2][2])
    while True:
        i+=1
        if block[0][0]==block[0][1] and block[0][1]==block[0][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[1][0]==block[1][1] and block[1][1]==block[1][2] and block[1][0]!=' ':
            if block[1][0]==tic:
                print("You Win!!")
            else:
                print('you Lose!!')
            break
        elif block[2][0]==block[2][1] and block[2][1]==block[2][2] and block[2][0]!=' ':
            if block[2][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][0] and block[1][0]==block[2][0] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][1]==block[1][1] and block[1][1]==block[2][1] and block[0][1]!=' ':
            if block[0][1]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][2] and block[1][2]==block[2][2] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][0]==block[1][1] and block[1][1]==block[2][2] and block[0][0]!=' ':
            if block[0][0]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif block[0][2]==block[1][1] and block[1][1]==block[2][0] and block[0][2]!=' ':
            if block[0][2]==tic:
                print("You Win!!")
            else:
                print("You Lose!!")
            break
        elif i%2==0:
            print("## A.I ##")
            row2=random.randint(1,3)
            while block[row2 - 1][0] != ' ' and block[row2 - 1][1] != ' ' and block[row2 - 1][2] != ' ':
                row2 = random.randint(1, 3)
            column2=random.randint(1,3)
            while block[row2-1][column2-1]!=' ':
                column2=random.randint(1,3)
            block[row2-1][column2-1]=tac
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        elif i%2!=0:
            print("## Your Turn ##")
            row1=int(input("Row --> "))
            column1=int(input("Column --> "))
            block[row1-1][column1-1]=tic
            print(block[0][0],"|",block[0][1],"|",block[0][2])
            print(block[1][0],"|",block[1][1],"|",block[1][2])
            print(block[2][0],"|",block[2][1],"|",block[2][2])
        if block[0][0]!=' ' and block[0][1]!=' ' and block[0][2]!=' ' and block[1][0]!=' ' and block[1][1]!=' ' and block[1][2]!=' 'and block[2][0]!=' ' and block[2][1]!=' 'and block[2][2]!=' ':
            print("Draw!!")
            break
print("Thanks for playing!!")


来源: stackexchange

问:
Symfony authentification form does not run
I have the form type :

```<code>class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ->add('email')
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}
</code>```

The entity User :

```<code>    class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=2, minMessage="Nom trop petit")
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=4, minMessage="Mot de passe trop petit")
     */
    private $password;

    /**
     * @Assert\EqualTo(propertyPath="password", message="Le mot de passe ne correspond pas")
     */
    public $confirm_password;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;
        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return ["ROLE_USER"];
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }
}
</code>```

The controller :

```<code>/**
 * @Route("/login", name="login")
 */
public function login()
{
    // the identification is done thanks Symfony security configuration

    return $this->render("security/login.html.twig", [
        "form" => $this->createForm(UserType::class )->createView()
    ]);
}
</code>```

The security firewall configuration file :

```<code>firewalls:
    main:
        anonymous: lazy
        provider: in_database
        form_login:
            login_path: security_login
            check_path: security_login
        logout:
            path: security_logout
            target: home
</code>```

And the view :

```<code>{% extends 'base.html.twig' %}
{% block title %}Hello SecurityController!{% endblock %}
{% block body %}
    <h1>Login</h1>
    <form action="{{ path('security_login') }}" method="post">
        <div class="form-group">
            <input type="text" class="form-control" placeholder="Nom" required name="_username">
        </div>
        <div class="form-group">
            <input type="password" class="form-control" placeholder="Mot de passe" required name="_password">
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-success">Connexion</button>
        </div>
    </form>
{% endblock %}
</code>```

With this code the identication runs.

Now, I want use the Twig form tags in the Twig file as follows:

```<code>{{ form_start(form) }}
{{ form_row(form.username, {"attr": {"placeholder": "Nom", "name": "_username", "required": "required"}, "label": "Nom" }) }}
{{ form_row(form.password, {"attr": {"placeholder": "Mot de passe", "name": "_password", "required": "required"}, "label": "Mot de passe" }) }}
<button type="submit" class="btn btn-success">Valider</button>
{{ form_end(form) }}
</code>```

But when I use this code, I obtain the error message :

The key "_username" must be a string, "NULL" given.

Normally, my forms run correctly. Why, here, doesn't the form work?

Thank for yours answers.

答:
Your authentication logic is not good. Follow this doc ...
https://symfony.com/doc/current/security/form_login_setup.html</p>

ContentLicense: CC BY-SA 4.0

Body:
I have the form type :

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // ->add('email')
            ->add('username', TextType::class)
            ->add('password', PasswordType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

The entity User :

    class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Email()
     */
    private $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=2, minMessage="Nom trop petit")
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\Length(min=4, minMessage="Mot de passe trop petit")
     */
    private $password;

    /**
     * @Assert\EqualTo(propertyPath="password", message="Le mot de passe ne correspond pas")
     */
    public $confirm_password;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;
        return $this;
    }

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;
        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        return $this;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return ["ROLE_USER"];
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        // TODO: Implement getSalt() method.
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
        // TODO: Implement eraseCredentials() method.
    }
}

The controller :

/**
 * @Route("/login", name="login")
 */
public function login()
{
    // the identification is done thanks Symfony security configuration

    return $this->render("security/login.html.twig", [
        "form" => $this->createForm(UserType::class )->createView()
    ]);
}

The security firewall configuration file :

firewalls:
    main:
        anonymous: lazy
        provider: in_database
        form_login:
            login_path: security_login
            check_path: security_login
        logout:
            path: security_logout
            target: home

And the view :

{% extends 'base.html.twig' %}
{% block title %}Hello SecurityController!{% endblock %}
{% block body %}

Login

    <form action="{{ path('security_login') }}" method="post">

            <input type="text" class="form-control" placeholder="Nom" required name="_username">

            <input type="password" class="form-control" placeholder="Mot de passe" required name="_password">

            <button type="submit" class="btn btn-success">Connexion</button>

    </form>
{% endblock %}

With this code the identication runs.

Now, I want use the Twig form tags in the Twig file as follows:

{{ form_start(form) }}
{{ form_row(form.username, {"attr": {"placeholder": "Nom", "name": "_username", "required": "required"}, "label": "Nom" }) }}
{{ form_row(form.password, {"attr": {"placeholder": "Mot de passe", "name": "_password", "required": "required"}, "label": "Mot de passe" }) }}
<button type="submit" class="btn btn-success">Valider</button>
{{ form_end(form) }}

But when I use this code, I obtain the error message :

The key "_username" must be a string, "NULL" given.

Normally, my forms run correctly. Why, here, doesn't the form work?

Thank for yours answers.


问:
storing time in PHP
data stored in table1 is with time stamp. syntax used to store time stamp is NOW(). stored time format is in 2011-05-17 00:46:19. my question is how do I access latest data by time and how do I display time say "the data stored 10 minutes ago" or 5 seconds ago or 1 day etc. I am using MySQL and PHP.

答:
```<code>SELECT * FROM table1
WHERE table1.TimePosted BETWEEN NOW() AND DATE_SUB(NOW(),INTERVAL 10 MIN);
</code>```

Link: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

ContentLicense: CC BY-SA 3.0

Title: storing time in PHP

Body:
SELECT * FROM table1
WHERE table1.TimePosted BETWEEN NOW() AND DATE_SUB(NOW(),INTERVAL 10 MIN);

Link: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add


问:
How to remove username field in the register form on django admin?
using the rest-framework and the django-allauth settings flags for removing the username as required for both login and register:

```<code>#settings.py
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
</code>```

but i still see the username field in the registration form in the administrator and the username field in the user list (empty users those without username).

how can i remove it?

答:
In my case, I simply put 'username = None' there. Then it's gone.
Full code:

```<code>from django.utils.translation import gettext_lazy as _
class LectureUser(AbstractUser):
  username = None
  identifier = models.IntegerField(primary_key=True)
  email = models.EmailField(_('email address'))
  USERNAME_FIELD = 'identifier' # Set to the unique identifier we define.
  objects = CustomUserManager()
</code>```

Hope this helps :-)

Body:
using the rest-framework and the django-allauth settings flags for removing the username as required for both login and register:

#settings.py
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False

but i still see the username field in the registration form in the administrator and the username field in the user list (empty users those without username).

how can i remove it?

Body:
In my case, I simply put 'username = None' there. Then it's gone.
Full code:

from django.utils.translation import gettext_lazy as _
class LectureUser(AbstractUser):
  username = None
  identifier = models.IntegerField(primary_key=True)
  email = models.EmailField(_('email address'))
  USERNAME_FIELD = 'identifier' # Set to the unique identifier we define.
  objects = CustomUserManager()

Hope this helps :-)


问:
Best practice of Receiving bulk of data [laravel Restfult API]
I have a case of receiving bulk of data to handle it in APIs

what's the best practice of receiving it

First approach => create multiple array each hold the data of each field

```<code>$names = ['SAM','John','Vardy'];

$ages = ['19','20','22'];
</code>```

or
Second approach => create one array each index has it own object

```<code>$data = [
   {
     'name':'SAM',
     'age':'19'
   },
   {
     'name':'John',
     'age':'20'
   },
   {
     'name':'Vardy',
     'age':'22'
   },
];
</code>```

what's the best one of them ???

答:
"Better" is a subjective term and on this site we deal with objective criteria. So, first, let's define what "better" is in this case:

reusable

easy-to-maintain

understandable

reliable

Now, if you create many arrays with n elements each and the nth item of all will be interrelated, then you will always have to deal with some specific arrays, so this will not really be reusable. You can write some functions which ease some of the burden, but this does not change the fact that you will always have some specific columns to work with. If you have an array where each element represents a set of field-name field-value pairs, then as an idea this is reusable. You will just need to keep track of the column names and values, rather than creating an array of each column name.

The first approach is difficult to maintain, because whenever you need new fields, or field name changes, or removing some fields, then you will have to re-read entire code chunks. In the second approach you will just handle some fields.

The first is difficult to understand. An index is a number and tells you nothing and in order to understand an entity you will have to glue together nth elements of all arrays of an entity, something which comes as a free feature with the second approach.

The first approach is very unreliable. If an item is removed from an array, but not from the other, due to a bug, then your code will have the impression that some items are interrelated with the wrong pairs.

So, let's have an array with field-name field-value pairs, you can implement some helper functions as well, in order to validate, add, remove or update items.

Body:
I have a case of receiving bulk of data to handle it in APIs

what's the best practice of receiving it

First approach => create multiple array each hold the data of each field

$names = ['SAM','John','Vardy'];

$ages = ['19','20','22'];

or
Second approach => create one array each index has it own object

$data = [
   {
     'name':'SAM',
     'age':'19'
   },
   {
     'name':'John',
     'age':'20'
   },
   {
     'name':'Vardy',
     'age':'22'
   },
];

what's the best one of them ???


问:
How to invoke default template functional argument in C++?
I want my template function

```<code>template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}
</code>```

to be able to receive pointers to functions and invoke this function later. This excerpt is correct and the compiler does not complain on errors. Let's consider the such program

```<code>#include <iostream>
#include <string>

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

int main()
{
    std::cout << probe([](int a,int b){ return a-b;});
}
</code>```

The program outputs what I've expected: zero. However, I explicitly denoted for this call what a function I am passing - I mean about this lambda-expression in the parentheses [](int a,int b){ return a-b;}. That's fine until I pass nothing - the call std::cout << probe(); is incorrect, however I've expected that the function will use default function function call = [] (int a, int b) { return a+b; }. So, how do I call the function that instance of this function will use default lambda-expression in the declaration?

答:
Default function arguments don't contribute to template argument deduction. The compiler can't deduce function when no function argument is given explicitly, and so the call site cannot be matched to any function to call.

One pretty straightforward way to get your example to work, is to overload instead.

```<code>template<class function>
int probe(function call)
{
    return call(10, 10);
}

inline int probe()
{
     return probe([] (int a, int b) { return a+b; });
}
</code>```

Body:
I want my template function

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

to be able to receive pointers to functions and invoke this function later. This excerpt is correct and the compiler does not complain on errors. Let's consider the such program

#include <iostream>
#include <string>

template<class function>
int probe(function call = [] (int a, int b) { return a+b; })
{
    return call(10, 10);
}

int main()
{
    std::cout << probe([](int a,int b){ return a-b;});
}

The program outputs what I've expected: zero. However, I explicitly denoted for this call what a function I am passing - I mean about this lambda-expression in the parentheses [](int a,int b){ return a-b;}. That's fine until I pass nothing - the call std::cout << probe(); is incorrect, however I've expected that the function will use default function function call = [] (int a, int b) { return a+b; }. So, how do I call the function that instance of this function will use default lambda-expression in the declaration?

Body:
Default function arguments don't contribute to template argument deduction. The compiler can't deduce function when no function argument is given explicitly, and so the call site cannot be matched to any function to call.

One pretty straightforward way to get your example to work, is to overload instead.

template<class function>
int probe(function call)
{
    return call(10, 10);
}

inline int probe()
{
     return probe([] (int a, int b) { return a+b; });
}


问:
Java Hash Map(several values for 1 key)
how can I add several values to one key in Hash Map?

```<code>HashMap<String, ArrayList<String>> phonebook = new HashMap<>();
</code>```

For example, I want to phonebook.put("Mike","123") phonebook.put("Mike","321")
And then I want to get all the values for key Mike.

答:
You don't have to reinvent the wheel.

Java's built-in MultivaluedHashMap

Spring's LinkedMultiValueMap

Apache's MultivaluedHashMap

Title: Java Hash Map(several values for 1 key)

Body:
how can I add several values to one key in Hash Map?

HashMap<String, ArrayList<String>> phonebook = new HashMap<>();

For example, I want to phonebook.put("Mike","123") phonebook.put("Mike","321")
And then I want to get all the values for key Mike.


问:
Undefined reference to POSIX functions when they're imported
I'm just creating a thread with a timer. Even if I import all the libraries I need. It keeps telling that there's no reference to the functions.

Exactly it says that timer_create(...) and timer_settime(...) are unreferenced.

These are my imports:

```<code>#include <stdio.h>
#include <stddef.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
</code>```

And this is the thread where I use those functions:

```<code>void *Turismo(){
    const struct timespec periodo = {per_turismos_sec,per_turismos_nsec};
    struct sigevent event;
    timer_t timer;
    struct itimerspec its;
    sigset_t sigset;
    int signum;

    event.sigev_notify = SIGEV_SIGNAL;
    event.sigev_signo = SIGRTMAX;
    event.sigev_value.sival_ptr = &timer;

    if(timer_create(CLOCK_MONOTONIC,&event,&timer)!=0) error();

    its.it_interval = periodo;
    its.it_value.tv_sec = 0;
    its.it_value.tv_nsec = 1;

    if(timer_settime(timer,0,&its,NULL)<0) error();
    if(sigemptyset(&sigset)<0) error();
    if(sigaddset(&sigset,SIGRTMAX)<0) error();

    while(1){
        sigwait(&sigset,&signum);
        // ESPECIFICACION DE LA TAREA

    }

    if(timer_delete(timer)<0) error();
    return NULL;
}
</code>```

The code is not complete to make easir the correction.

For the compilation I'm using the next command:

```<code>gcc -o ejer1 ejer1.c -lpthread
</code>```

I would appreciate some help. Thanks!

答:
There are two stages to build the program

Compilation

Linkage

At the compilation stage, you need to know declaration of the functions and structures to build .o files.

At the linkage stage, you need actual implementation of the functions.

Undefined reference error tells you that the linker can not find the implementation of the functions.

Because you use third party library, you need to link that library with -l key.

To check if library has symbol, you can execute

```<code>$ nm -gD /usr/lib/x86_64-linux-gnu/librt.so | grep timer_create
0000000000004520 T timer_create
00000000000042a0 T timer_create
</code>```

In your case, you need to link rt library with -lrt key.

Body:
I'm just creating a thread with a timer. Even if I import all the libraries I need. It keeps telling that there's no reference to the functions.

Exactly it says that timer_create(...) and timer_settime(...) are unreferenced.

These are my imports:

#include <stdio.h>
#include <stddef.h>
#include <sched.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>

And this is the thread where I use those functions:

void *Turismo(){
    const struct timespec periodo = {per_turismos_sec,per_turismos_nsec};
    struct sigevent event;
    timer_t timer;
    struct itimerspec its;
    sigset_t sigset;
    int signum;

    event.sigev_notify = SIGEV_SIGNAL;
    event.sigev_signo = SIGRTMAX;
    event.sigev_value.sival_ptr = &timer;

    if(timer_create(CLOCK_MONOTONIC,&event,&timer)!=0) error();

    its.it_interval = periodo;
    its.it_value.tv_sec = 0;
    its.it_value.tv_nsec = 1;

    if(timer_settime(timer,0,&its,NULL)<0) error();
    if(sigemptyset(&sigset)<0) error();
    if(sigaddset(&sigset,SIGRTMAX)<0) error();

    while(1){
        sigwait(&sigset,&signum);
        // ESPECIFICACION DE LA TAREA

    }

    if(timer_delete(timer)<0) error();
    return NULL;
}

The code is not complete to make easir the correction.

For the compilation I'm using the next command:

gcc -o ejer1 ejer1.c -lpthread

I would appreciate some help. Thanks!

Body:
There are two stages to build the program

Compilation

Linkage

At the compilation stage, you need to know declaration of the functions and structures to build .o files.

At the linkage stage, you need actual implementation of the functions.

Undefined reference error tells you that the linker can not find the implementation of the functions.

Because you use third party library, you need to link that library with -l key.

To check if library has symbol, you can execute

$ nm -gD /usr/lib/x86_64-linux-gnu/librt.so | grep timer_create
0000000000004520 T timer_create
00000000000042a0 T timer_create

In your case, you need to link rt library with -lrt key.


问:
Char or String -> Unicode value in Scala?
So I'm working through a few of the exercises in "Scala for the Impatient" and one of them is:

Write a for loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 9415087488 L.

The next problem is to do the same, but without a for loop - it hints that we should check StringOps in Scaladoc.

I checked the RichChar and StringOps section in Scaladoc, and perhaps I'm misreading or looking in the wrong places, but I can't find anything that gets me to match their output. I've thus far tried:

```<code>scala> x.foldLeft(1)(_ * _.toInt)
res0: Int = 825152896

scala> x.foldLeft(1)(_ * _.getNumericValue)
res5: Int = 2518992

scala> x.foldLeft(1)(_ * _.intValue())
res6: Int = 825152896

scala> var x = 1
x: Int = 1

scala> for (c <- "Hello") x *= c.toInt

scala> x
res12: Int = 825152896
</code>```

Which does not match their output.

How do I do this, in both the for and non-for way?

Thanks!

答:
So here we have in bunch together :)</p>

```<code>    // one way
    val longs = for (c <- str) yield c.toLong
    println(longs.product)

    // 2nd way
    println(str.foldLeft(1L)(_ * _.toInt))

    // 3rd way
    var x = 1L
    for (c <- str) yield x *= c.toInt
    println(x)

    // 4th way
    var product = 1L
    for (c <- str) {
      product *= c.toInt
    }
    println(product)

    // 5th way
    println(str.map(_.toLong).product)

    // 6th way
    println(str.foldLeft(1L)(_ * _))

    // 7th way
    println(str.map(_.toLong).reduceLeft(_ * _)) // my IDE warns `Replace reduce with product`

    // 8th way
    println(str.map(_.toLong).scanLeft(1L)(_ * _).last)

    // 9th way
    println(str.map(_.toLong).reduce((x, y) => (x * y))) // my IDE warns `Replace reduce with product`

   // using recursion
   def exercise9(str: String): Long = {
    var product = str.head.toLong
    if (str.tail.length > 0) {
        product *= exercise9(str.tail)
    }
    product
  }
</code>```

Body:
So I'm working through a few of the exercises in "Scala for the Impatient" and one of them is:

Write a for loop for computing the product of the Unicode codes of all letters in a string. For example, the product of the characters in "Hello" is 9415087488 L.

The next problem is to do the same, but without a for loop - it hints that we should check StringOps in Scaladoc.

I checked the RichChar and StringOps section in Scaladoc, and perhaps I'm misreading or looking in the wrong places, but I can't find anything that gets me to match their output. I've thus far tried:

scala> x.foldLeft(1)(_ * _.toInt)
res0: Int = 825152896

scala> x.foldLeft(1)(_ * _.getNumericValue)
res5: Int = 2518992

scala> x.foldLeft(1)(_ * _.intValue())
res6: Int = 825152896

scala> var x = 1
x: Int = 1

scala> for (c <- "Hello") x *= c.toInt

scala> x
res12: Int = 825152896

Which does not match their output.

How do I do this, in both the for and non-for way?

Thanks!

Body:
So here we have in bunch together :)

    // one way
    val longs = for (c <- str) yield c.toLong
    println(longs.product)

    // 2nd way
    println(str.foldLeft(1L)(_ * _.toInt))

    // 3rd way
    var x = 1L
    for (c <- str) yield x *= c.toInt
    println(x)

    // 4th way
    var product = 1L
    for (c <- str) {
      product *= c.toInt
    }
    println(product)

    // 5th way
    println(str.map(_.toLong).product)

    // 6th way
    println(str.foldLeft(1L)(_ * _))

    // 7th way
    println(str.map(_.toLong).reduceLeft(_ * _)) // my IDE warns `Replace reduce with product`

    // 8th way
    println(str.map(_.toLong).scanLeft(1L)(_ * _).last)

    // 9th way
    println(str.map(_.toLong).reduce((x, y) => (x * y))) // my IDE warns `Replace reduce with product`

   // using recursion
   def exercise9(str: String): Long = {
    var product = str.head.toLong
    if (str.tail.length > 0) {
        product *= exercise9(str.tail)
    }
    product
  }


问:
Dynamically load a JavaScript file
How can you reliably and dynamically load a JavaScript file?  This will can be used to implement a module or component that when 'initialized' the component will dynamically load all needed JavaScript library scripts on demand.

The client that uses the component isn't required to load all the library script files (and manually insert

答:
For those of you, who love one-liners:

```<code>import('./myscript.js');
</code>```

Chances are you might get an error, like:

Access to script at 'http://..../myscript.js' from origin
  'http://127.0.0.1' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

In which case, you can fallback to:

```<code>fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());
</code>```

OwnerDisplayName: Adam

Title: Dynamically load a JavaScript file

LastEditorDisplayName: Adam

Body:
For those of you, who love one-liners:

import('./myscript.js');

Chances are you might get an error, like:

Access to script at 'http://..../myscript.js' from origin
  'http://127.0.0.1' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

In which case, you can fallback to:

fetch('myscript.js').then(r => r.text()).then(t => new Function(t)());


问:
Create a table of contents from a pdf file
I'm using quartz to display pdf content, and I need to create a table of contents to navigate through the pdf. From reading Apple's documentation I think I am supposed to use CGPDFDocumentGetCatalog, but I can't find any examples on how to use this anywhere. Any ideas?

Update: Still haven't found a solution for this. I tired Alex' solution but the output I get looks like this:

```<code>2011-07-27 09:16:19.359 LDS Scriptures App-iPad[624:707] key: Pages
2011-07-27 09:16:19.361 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.362 LDS Scriptures App-iPad[624:707] pdf integer value: 238
2011-07-27 09:16:19.363 LDS Scriptures App-iPad[624:707] key: Kids
2011-07-27 09:16:19.366 LDS Scriptures App-iPad[624:707] key: Type
2011-07-27 09:16:19.368 LDS Scriptures App-iPad[624:707] key: Outlines
2011-07-27 09:16:19.370 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.371 LDS Scriptures App-iPad[624:707] pdf integer value: 7
2011-07-27 09:16:19.372 LDS Scriptures App-iPad[624:707] key: First
2011-07-27 09:16:19.374 LDS Scriptures App-iPad[624:707] key: Parent
2011-07-27 09:16:19.375 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.376 LDS Scriptures App-iPad[624:707] pdf integer value: 7
</code>```

No idea yet how to turn that into a usable table of contents. Ideally I would like to get to an array of NSDictionary objects with a title and matching page number.

答:
You create a Table of Contents (AKA Outlines, Bookmarks) using PDFKit's PDFOutline object. You can also read existing Outlines within a PDF.

CGPDFDocumentGetCatalog is a method for getting the Catalog of PDF data in the file, which is at a much lower-level than human concepts of 'Contents'.

In the absence of existing Outlines, I'm not sure there's a way to get meaningful data from the PDF stream itself, e.g. trying to grok Chapter headings just from the PDF data.

Body:
I'm using quartz to display pdf content, and I need to create a table of contents to navigate through the pdf. From reading Apple's documentation I think I am supposed to use CGPDFDocumentGetCatalog, but I can't find any examples on how to use this anywhere. Any ideas?

Update: Still haven't found a solution for this. I tired Alex' solution but the output I get looks like this:

2011-07-27 09:16:19.359 LDS Scriptures App-iPad[624:707] key: Pages
2011-07-27 09:16:19.361 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.362 LDS Scriptures App-iPad[624:707] pdf integer value: 238
2011-07-27 09:16:19.363 LDS Scriptures App-iPad[624:707] key: Kids
2011-07-27 09:16:19.366 LDS Scriptures App-iPad[624:707] key: Type
2011-07-27 09:16:19.368 LDS Scriptures App-iPad[624:707] key: Outlines
2011-07-27 09:16:19.370 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.371 LDS Scriptures App-iPad[624:707] pdf integer value: 7
2011-07-27 09:16:19.372 LDS Scriptures App-iPad[624:707] key: First
2011-07-27 09:16:19.374 LDS Scriptures App-iPad[624:707] key: Parent
2011-07-27 09:16:19.375 LDS Scriptures App-iPad[624:707] key: Count
2011-07-27 09:16:19.376 LDS Scriptures App-iPad[624:707] pdf integer value: 7

No idea yet how to turn that into a usable table of contents. Ideally I would like to get to an array of NSDictionary objects with a title and matching page number.


问:
How to split a list into pages in Vue.js?
I connect to the API, and get a large list of items that are rendered like this:

```<code><template>
    <div>
        <Item v-for="story in stories" :key="story.data.id" :story="story"></Item>
    </div>
</template>
</code>```

There is more 200 items in list and loading takes a time. How I can divide the list into pages of 10-20 items that will be loaded when the user goes to the page

答: The vuetify v-data-table component has an automatic rows-per-page option

Body:
I connect to the API, and get a large list of items that are rendered like this:

<template>

        <Item v-for="story in stories" :key="story.data.id" :story="story"></Item>

</template>

There is more 200 items in list and loading takes a time. How I can divide the list into pages of 10-20 items that will be loaded when the user goes to the page


问:
Reset default values of widgets without triggering their value-change listeners in Vaadin Flow 14 web app
I have several widgets for controlling the filtering of a list of items in a Grid. Each widget has a value-change listener, so when the user uses one of the widgets, filters on the data provider behind the Grid are configured, resulting in the Grid object displaying a subset of its items.

```<code>    strength = new RadioButtonGroup <>();  // Backed with enum named `Strength`.
    strength.setLabel( "Strength:" );
    strength.setItems( Strength.values() );
    strength.setValue( Strength.ANY );
    strength.setRenderer( new TextRenderer <>( Strength :: getDisplayName ) );
    strength.addValueChangeListener( event -> {
        configureFilters();
    } );
</code>```

This works well.

I also have Reset button to put those filter controls back to their default status.

```<code>    reset = new Button( "Reset" );
    reset.addClickListener( event -> {
        this.resetCriteria();
        this.configureFilters();
    } );
</code>```

The resetCriteria method makes a series of these calls:

```<code>this.strength.setValue( Strength.ANY );
</code>```

This causes problems. Resetting those widgets causes the value-change events to fire, and listeners the execute. This interrupt my series of setValue( … ) calls. So some of the filter control widgets are not reset.

➥ Is there a way to suspend the value-change events from firing, or the listeners from listening, during the brief interlude when I reset all the widget values back to defaults?

Or is there an entirely different approach I should take to resetting widgets? I suppose I could discard the entire layout of widgets and recreate from scratch, but that seems like overkill, like there should be a more elegant approach.

答:
Like in Vaadin version 8, there is a way to determine if the (value change) event has its origin from the user or is "synthetic" (generated by code).

See the method com.vaadin.flow.component.ComponentEvent#isFromClient

Class ComponentEvent<T extends Component>

public boolean isFromClient()

Checks if this event originated from the client side.

Returns:

true if the event originated from the client side,  false otherwise

So you would check in your value change listener, if the given event
isFromClient and only do your logic then. Add if ( event.isFromClient() ) to your code.

```<code>    strength.addValueChangeListener( event -> {
        if ( event.isFromClient() ) { this.configureFilters(); }
    } );
</code>```

Otherwise there are (to my knowledge) no ways to silence the listeners
beside doing it yourself.  E.g.

Remember the Registration from registering each listener, close them before, and re-add the listener again after you are done with changing the values.

Build your own killswitch the listeners check, whether actions must be taken.

Body:
I have several widgets for controlling the filtering of a list of items in a Grid. Each widget has a value-change listener, so when the user uses one of the widgets, filters on the data provider behind the Grid are configured, resulting in the Grid object displaying a subset of its items.

    strength = new RadioButtonGroup <>();  // Backed with enum named `Strength`.
    strength.setLabel( "Strength:" );
    strength.setItems( Strength.values() );
    strength.setValue( Strength.ANY );
    strength.setRenderer( new TextRenderer <>( Strength :: getDisplayName ) );
    strength.addValueChangeListener( event -> {
        configureFilters();
    } );

This works well.

I also have Reset button to put those filter controls back to their default status.

    reset = new Button( "Reset" );
    reset.addClickListener( event -> {
        this.resetCriteria();
        this.configureFilters();
    } );

The resetCriteria method makes a series of these calls:

this.strength.setValue( Strength.ANY );

This causes problems. Resetting those widgets causes the value-change events to fire, and listeners the execute. This interrupt my series of setValue( … ) calls. So some of the filter control widgets are not reset.

➥ Is there a way to suspend the value-change events from firing, or the listeners from listening, during the brief interlude when I reset all the widget values back to defaults?

Or is there an entirely different approach I should take to resetting widgets? I suppose I could discard the entire layout of widgets and recreate from scratch, but that seems like overkill, like there should be a more elegant approach.

Body:
Like in Vaadin version 8, there is a way to determine if the (value change) event has its origin from the user or is "synthetic" (generated by code).

See the method com.vaadin.flow.component.ComponentEvent#isFromClient

Class ComponentEvent<T extends Component>

public boolean isFromClient()

Checks if this event originated from the client side.

Returns:

true if the event originated from the client side,  false otherwise

So you would check in your value change listener, if the given event
isFromClient and only do your logic then. Add if ( event.isFromClient() ) to your code.

    strength.addValueChangeListener( event -> {
        if ( event.isFromClient() ) { this.configureFilters(); }
    } );

Otherwise there are (to my knowledge) no ways to silence the listeners
beside doing it yourself.  E.g.

Remember the Registration from registering each listener, close them before, and re-add the listener again after you are done with changing the values.

Build your own killswitch the listeners check, whether actions must be taken.


问:
WordPress admin menu: custom logout link shows as submenu item instead of menu item
I added a custom logout link to my WP admin menu, but instead of appearing as a top-level menu item, it is displayed as a submenu item (smaller font size, left padding). The link itself works perfectly though. Any ideas how the code can be changed? Thanks!

current admin menu

The code I use is from this thread.

```<code>add_action('admin_init', 'text_domain_logout_link');

function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());
}
</code>```

答:
Can you try this?:

```<code>add_action('admin_menu', 'text_domain_logout_link');
function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());
}
</code>```

Tested and works on my wordpress

Updated:
If you want to show it to top-level then use this code:

```<code>add_action('admin_menu', 'text_domain_logout_link');
function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());

    // add class
    $menu[9999][4] =  "menu-top toplevel_page_menu";

    // Add Icon
    $menu[9999][6] =  "dashicons-update";

}
</code>```

So it will look like this:

Body:
I added a custom logout link to my WP admin menu, but instead of appearing as a top-level menu item, it is displayed as a submenu item (smaller font size, left padding). The link itself works perfectly though. Any ideas how the code can be changed? Thanks!

current admin menu

The code I use is from this thread.

add_action('admin_init', 'text_domain_logout_link');

function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());
}

Body:
Can you try this?:

add_action('admin_menu', 'text_domain_logout_link');
function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());
}

Tested and works on my wordpress

Updated:
If you want to show it to top-level then use this code:

add_action('admin_menu', 'text_domain_logout_link');
function text_domain_logout_link() {
    global $menu;
    $menu[9999] = array(__('Logout'), 'manage_options', wp_logout_url());

    // add class
    $menu[9999][4] =  "menu-top toplevel_page_menu";

    // Add Icon
    $menu[9999][6] =  "dashicons-update";

}

So it will look like this:


问:
No response from web service on localhost
I'm using NuSOAP and PHP to connect to a web service (WSDL) and I can't get any response or error while trying locally. Once I move it to our server everything works fine, but I'm not sure what I need to configure locally to get things rolling.

I'm using WAMP on Windows 7.

答:
You do not get an error because your PHP.INI is probably hide setup to hide the errors.

Put in your php.ini:

```<code>display_errors = on
</code>```

restart your WAMP server and try again.

Body:
You do not get an error because your PHP.INI is probably hide setup to hide the errors.

Put in your php.ini:

display_errors = on

restart your WAMP server and try again.


问:
How can I add custom props to an Option using React Select?
My goal is to add a tooltip when the user expands the  menu and hovers over the items listed. To do this, I need to add data-tip and data-for to the menu items.

The options I'm passing to React Select looks like this:

```<code>  [
    { value: 1, label: 'Onw' },
    { value: 2, label: 'Two' },]
</code>```

I'd like to just add the prop info there but I don't think there's a way. Do I need to customize the rendering of each option? Any tips on how to do this would be appreciated. Thanks.

答:
You can simply wrap your custom Option inside a function then assign custom props for it

```<code>components={{ Option: (optionProps) => <Option {...optionProps} onEditItem={onEditItem}
    onDeleteItem={onDeleteItem} />  }}
</code>```

Body:
My goal is to add a tooltip when the user expands the  menu and hovers over the items listed. To do this, I need to add data-tip and data-for to the menu items.

The options I'm passing to React Select looks like this:

  [
    { value: 1, label: 'Onw' },
    { value: 2, label: 'Two' },]

I'd like to just add the prop info there but I don't think there's a way. Do I need to customize the rendering of each option? Any tips on how to do this would be appreciated. Thanks.

Body:
You can simply wrap your custom Option inside a function then assign custom props for it

components={{ Option: (optionProps) => <Option {...optionProps} onEditItem={onEditItem}
    onDeleteItem={onDeleteItem} />  }}


问:
Axios 'put' request passing array as empty value
This is my 'PUT' request using Axios.

The problem is: the data array inside the variable userdata is passing as an empty value to the backend.
but the console.log just before the api call shows the correct value.

```<code>let userdata = {
  "epoch_time": "1581850307",
  "auth_key": "b22dfe2f8d93445c26f5c261f6a426d2",
  "user_mode": " driver",
  "action": "location",
  "data": [{
    "lat": 20.123657,
    "lon": 80.12453
  }, {
    "lat": 20.123654,
    "lon": 80.12456
  }]
}
</code>```

This is the api call..

```<code>export const locationTrackingApi = (userdata) => {
  console.log("locationTrackingApi data", userdata);
  return dispatch => {
    axios({
      method: 'PUT',
      url: BASEURL,
      data: userdata
    })
      .then(function (response) {
        console.log("locationTrackingApi response", response);
      }).catch(function (error) {
        dispatch(apiLoadingIndicator(false));
        console.log(error);
      })
  };

}
</code>```

答:
Try this</p>

```<code> axios("URL", {
    method: "PUT",
    headers: {
      "content-type": "application/json"
    },
    data: loanData
  })
    .then(response => {
      console.log("Successfully Updated !");

    })
    .catch(err => {
      console.log(err.response);

    });
</code>```

Body:
This is my 'PUT' request using Axios.

The problem is: the data array inside the variable userdata is passing as an empty value to the backend.
but the console.log just before the api call shows the correct value.

let userdata = {
  "epoch_time": "1581850307",
  "auth_key": "b22dfe2f8d93445c26f5c261f6a426d2",
  "user_mode": " driver",
  "action": "location",
  "data": [{
    "lat": 20.123657,
    "lon": 80.12453
  }, {
    "lat": 20.123654,
    "lon": 80.12456
  }]
}

This is the api call..

export const locationTrackingApi = (userdata) => {
  console.log("locationTrackingApi data", userdata);
  return dispatch => {
    axios({
      method: 'PUT',
      url: BASEURL,
      data: userdata
    })
      .then(function (response) {
        console.log("locationTrackingApi response", response);
      }).catch(function (error) {
        dispatch(apiLoadingIndicator(false));
        console.log(error);
      })
  };

}

Body:
Try this

 axios("URL", {
    method: "PUT",
    headers: {
      "content-type": "application/json"
    },
    data: loanData
  })
    .then(response => {
      console.log("Successfully Updated !");

    })
    .catch(err => {
      console.log(err.response);

    });


问:
Why can't I run APK files on Windows?
I have read book as below because of programming studying

"When you install the Java Virtual Machine (JVM) on your operating system, programs written in Java will work exactly the same on any computer. Virtual machines are built for each operating system so that they run exactly the same."

I know just window is x86, Andoroid is ARM system.
But APK file is made by Java language. And maybe there is JVM on my window computer.
Why I cannot run on my window PC?

(Android system does not use JVM. it uses Android Runtime (VM) . this is root cause?)

答:
An APK is basically a zip package containing an application compiled for the Android Runtime, not for a JVM running on Windows. You need to use an Android emulator to be able to run Android apps on Windows. Genymotion is one of them:

https://www.genymotion.com

But there are many available if you search on Google.

Title: Why can't I run APK files on Windows?


问:
DriverManager cant be found, underlines red and prompts me to create class DriverManager
```<code>protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
    //define the fields
    String username = "root";
    String password = "Otiwah0771";
    String jdbcURL = "jdbc:mysql://localhost:3306/employeedirectory";
    String driver = "com.mysql.jdbc.Driver";

    try
    {

    //Get the Print Writer object
    PrintWriter out = response.getWriter();
    out.println("Connecting to databace"+jdbcURL);

    //load the Driver
    Class.forName(driver);

    //Get the connection
    Connection connection = DriverManager.getConnection(jdbcURL,username,password);

    //Close the connection
    connection.close();
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}
</code>```

** Using Netbeans 11.2 **

I have added mysql connector jar and yet the issue persists (DriverManager symbol cant be found)

答:
Your problem of not being able to import DriverManager can be explained if you have created a modular project, and did not explicitly require the java.sql module.  If you don't explicitly require java.sql, you don't get access to the JDBC API, even though it is included with Java.

To fix this, edit module-info.java in the default package (or: the root of your source packages) and add the following line to the body of the module:

```<code>requires java.sql;
</code>```

For example

```<code>module examplemodule {
    requires java.sql;
}
</code>```

You should now be able to import java.sql.DriverManager.

Alternatively, don't use a modular project (ie use a project without module-info.java).

As an aside, your code seems to be a servlet, it is generally a bad practice to use DriverManager directly in a web application. Instead use a javax.sql.DataSource backed by a connection pool to create and reuse connections.

Body:
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
    //define the fields
    String username = "root";
    String password = "Otiwah0771";
    String jdbcURL = "jdbc:mysql://localhost:3306/employeedirectory";
    String driver = "com.mysql.jdbc.Driver";

    try
    {

    //Get the Print Writer object
    PrintWriter out = response.getWriter();
    out.println("Connecting to databace"+jdbcURL);

    //load the Driver
    Class.forName(driver);

    //Get the connection
    Connection connection = DriverManager.getConnection(jdbcURL,username,password);

    //Close the connection
    connection.close();
    }catch(Exception e)
    {
        e.printStackTrace();
    }
}

** Using Netbeans 11.2 **

I have added mysql connector jar and yet the issue persists (DriverManager symbol cant be found)

Body:
Your problem of not being able to import DriverManager can be explained if you have created a modular project, and did not explicitly require the java.sql module.  If you don't explicitly require java.sql, you don't get access to the JDBC API, even though it is included with Java.

To fix this, edit module-info.java in the default package (or: the root of your source packages) and add the following line to the body of the module:

requires java.sql;

For example

module examplemodule {
    requires java.sql;
}

You should now be able to import java.sql.DriverManager.

Alternatively, don't use a modular project (ie use a project without module-info.java).

As an aside, your code seems to be a servlet, it is generally a bad practice to use DriverManager directly in a web application. Instead use a javax.sql.DataSource backed by a connection pool to create and reuse connections.


问:
"Inverse SFINAE" to avoid ambiguous overload
How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined)

```<code>template<typename T>
auto zero() ->decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero() ->decltype(T::zero()) {
    return T::zero();
}
</code>```

答:
Without enable_if, relying on built-in rules of integer conversion ranks (conversion of 0 -> int is better than 0 -> char, which makes the former a first choice candidate, and the latter a viable second choice candidate):

```<code>template <typename T>
auto zero_helper(char) -> decltype(static_cast<T>(0))
{
    return static_cast<T>(0);
}

template <typename T>
auto zero_helper(int) -> decltype(T::zero())
{
    return T::zero();
}

template <typename T>
auto zero() -> decltype(auto)
{
    return zero_helper<T>(0);
}
</code>```

DEMO

With your own enable_if predicate (similar to the std::void_t technique):

```<code>#include <type_traits>

template <typename...>
struct voider { using type = void; };

template <typename... Ts>
using void_t = typename voider<Ts...>::type;

template <typename T, typename = void_t<>>
struct has_zero : std::false_type {};

template <typename T>
struct has_zero<T, void_t<decltype(T::zero())>> : std::true_type {};

template <typename T>
auto zero()
    -> typename std::enable_if<has_zero<T>::value, decltype(T::zero())>::type
{
    return T::zero();
}

template <typename T>
auto zero()
    -> typename std::enable_if<!has_zero<T>::value, T>::type
{
    return static_cast<T>(0);
}
</code>```

DEMO 2

Body:
How can I prevent the first template below from instantiating if the second template instantiates? (i.e. if both static_cast<T>(0) and T::zero() are defined)

template<typename T>
auto zero() ->decltype(static_cast<T>(0)) {
    return static_cast<T>(0);
}

template<typename T>
auto zero() ->decltype(T::zero()) {
    return T::zero();
}

Body:
Without enable_if, relying on built-in rules of integer conversion ranks (conversion of 0 -> int is better than 0 -> char, which makes the former a first choice candidate, and the latter a viable second choice candidate):

template <typename T>
auto zero_helper(char) -> decltype(static_cast<T>(0))
{
    return static_cast<T>(0);
}

template <typename T>
auto zero_helper(int) -> decltype(T::zero())
{
    return T::zero();
}

template <typename T>
auto zero() -> decltype(auto)
{
    return zero_helper<T>(0);
}

DEMO

With your own enable_if predicate (similar to the std::void_t technique):

#include <type_traits>

template <typename...>
struct voider { using type = void; };

template <typename... Ts>
using void_t = typename voider<Ts...>::type;

template <typename T, typename = void_t<>>
struct has_zero : std::false_type {};

template <typename T>
struct has_zero<T, void_t<decltype(T::zero())>> : std::true_type {};

template <typename T>
auto zero()
    -> typename std::enable_if<has_zero<T>::value, decltype(T::zero())>::type
{
    return T::zero();
}

template <typename T>
auto zero()
    -> typename std::enable_if<!has_zero<T>::value, T>::type
{
    return static_cast<T>(0);
}

DEMO 2


问:
Angular Material Datepicker with Range Selection
I'm using angular 8 and I wanted implement a datepicker with daterage highlighted:
enter image description here
I was looking for some package like this one:  https://www.npmjs.com/package/saturn-datepicker
Unfortunately it has been deprecated and currently I cannot find others like that.
Do you know something for my purpose? Thank you.  </p>

答:
In material date picker you can define max and min values.

For example:

example.hml
  <input matInput [min]="minValue" [max]="maxValue" [matDatepicker]="picker"
             formControlName="name"/>
           <mat-datepicker #voltageToDatePiker [startAt]="tomorrow"></mat-datepicker>

example.ts
  minValue = new Date();
     maxValue = new Date();


问:
When and why do I need to use cin.ignore() in C++?
I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

```<code>cin.ignore(256, '\n');
</code>```

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

Here is the program I wrote:

```<code>#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}
</code>```

答:
As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

```<code>#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}
</code>```

So, You get the point that it will ignore those unwanted inputs and will get the job done.

Body:
I wrote a very basic program in C++ which asked the user to input a number and then a string. To my surprise, when running the program it never stopped to ask for the string. It just skipped over it. After doing some reading on StackOverflow, I found out that I needed to add a line that said:

cin.ignore(256, '\n');

before the line that gets the string input. Adding that fixed the problem and made the program work. My question is why does C++ need this cin.ignore() line and how can I predict when I will need to use cin.ignore()?

Here is the program I wrote:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num;
    string mystr;

    cout << "Please enter a number: " << "\n";
    cin >> num;
    cout << "Your number is: " << num << "\n";
    cin.ignore(256, '\n'); // Why do I need this line?
    cout << "Please enter your name: \n";
    getline (cin, mystr);
    cout << "So your name is " << mystr << "?\n";
    cout << "Have a nice day. \n";

}

Body:
As pointed right by many other users. It's because there may be whitespace or a newline character.

Consider the following code, it removes all the duplicate characters from a given string.

#include <bits/stdc++.h>
using namespace std;

int main() {
    int t;
    cin>>t;
    cin.ignore(); //Notice that this cin.ignore() is really crucial for any extra whitespace or newline character
    while(t--){
        vector<int> v(256,0);
        string s;
        getline(cin,s);
        string s2;
        for(int i=0;i<s.size();i++){
            if (v[s[i]]) continue;
            else{
                s2.push_back(s[i]);
                v[s[i]]++;
            }
        }
        cout<<s2<<endl;
    }
    return 0;
}

So, You get the point that it will ignore those unwanted inputs and will get the job done.