How to announce a draw in tictactoe game?

Question: I am a beginner in Python, I know the code for TicTacToe is already available in the Internet but I would like to understand why it's not working the way I have written.
Please find the code below, the program works the problem is I am not sure how to announce if the game is Draw and if the box is already picked up by a player the other player should not use the same box by mistake, currently it can be overwritten.
import sys

def game_on():
    """User input to play the Game to stop"""
    game = False
    while game == False:
        user_request = input("Enter 'Y' to start the game, 'N' to stop: ").upper()
        if user_request == 'Y':
            return True
        elif user_request == 'N':
            print("Thanks for Playing... Good Bye...")
            game = True
        else:
            print("Wrong choice! Select either Y or N")
            game = False

test_board = ['0','1','2','3','4','5','6','7','8','9']
def display_board(board):
    """Tic_Tac_Toe board to play, it will be displayed with numbers which user can select to replace the box in the board"""
    print(board[1]+'|'+board[2]+'|'+board[3])
    print('-----')
    print(board[4]+'|'+board[5]+'|'+board[6])
    print('-----')
    print(board[7]+'|'+board[8]+'|'+board[9])

def player_1():
    """Player_1 input to select the specific box"""
    choice = 'Wrong'
    while choice.isdigit() == False:
        choice = input("Player_1 enter a number between 1 to 9: ")
        if choice.isdigit() == False:
            print("Enter the given number in the range 1 to 9: ")
    return int(choice)

def player_2():
    """Player_2 input to select the specific box"""
    choice = 'Wrong'
    while choice.isdigit() == False:
        choice = input("Player_2 enter a number between 1 to 9: ")
        if choice.isdigit() == False:
            print("Enter a given number in the range 1 to 9")
    return int(choice)

def update_user_input_player_1(test_board,position):
    """Player_1 input will be replaced with X """
    # replacement = input("If it's player 1 enter X, if it's player 2 enter O: ")
    test_board[position] = 'X'
    return test_board

def update_user_input_player_2(test_board,position):
    """Player_1 input will be replaced with Y """
    # replacement = input("If it's player 1 enter X, if it's player 2 enter O: ")
    test_board[position] = 'Y'
    return test_board

###Still don't know how to put a draw if the list still has numbers
def winner_announcement(test_board):
    """Winner will be analysed and established"""
    validate = True
    # print(validate)
    while validate == True:
        if ('X' in test_board[1] and 'X' in test_board[2] and 'X' in test_board[3]) or ('X' in test_board[4] and 'X' in test_board[5] and 'X' in test_board[6]) or ('X' in test_board[7] and 'X' in test_board[8] and 'X' in test_board[9]) or ('X' in test_board[1] and 'X' in test_board[5] and 'X' in test_board[9]) or ('X' in test_board[3] and 'X' in test_board[5] and 'X' in test_board[7]):
            print("Player 1 is the winner")
            sys.exit()
        elif ('Y' in test_board[1] and 'Y' in test_board[2] and 'Y' in test_board[3]) or ('Y' in test_board[4] and 'Y' in test_board[5] and 'Y' in test_board[6]) or ('Y' in test_board[7] and 'Y' in test_board[8] and 'Y' in test_board[9]) or ('Y' in test_board[1] and 'Y' in test_board[5] and 'Y' in test_board[9]) or ('Y' in test_board[3] and 'Y' in test_board[5] and 'Y' in test_board[7]):
            print("Player 2 is the winner")
            sys.exit()
        else:
            validate = False

###Function call
play = game_on()
while play == True:
    display_board(test_board)
    player__1_result = player_1()
    update_user_input_player_1(test_board,player__1_result)
    winner_announcement(test_board)
    display_board(test_board)
    player_2_result = player_2()
    update_user_input_player_2(test_board,player_2_result)
    winner_announcement(test_board)```

For the Draw, I though if I can write a condition outside the current if statement, it should work but it's simply hanging doing nothing.

```def winner_announcement(test_board):
    """Winner will be analysed and established"""
    validate = True
    # print(validate)
    while validate == True:
        if ('X' in test_board[1] and 'X' in test_board[2] and 'X' in test_board[3]) or ('X' in test_board[4] and 'X' in test_board[5] and 'X' in test_board[6]) or ('X' in test_board[7] and 'X' in test_board[8] and 'X' in test_board[9]) or ('X' in test_board[1] and 'X' in test_board[5] and 'X' in test_board[9]) or ('X' in test_board[3] and 'X' in test_board[5] and 'X' in test_board[7]):
            print("Player 1 is the winner")
            sys.exit()
        elif ('Y' in test_board[1] and 'Y' in test_board[2] and 'Y' in test_board[3]) or ('Y' in test_board[4] and 'Y' in test_board[5] and 'Y' in test_board[6]) or ('Y' in test_board[7] and 'Y' in test_board[8] and 'Y' in test_board[9]) or ('Y' in test_board[1] and 'Y' in test_board[5] and 'Y' in test_board[9]) or ('Y' in test_board[3] and 'Y' in test_board[5] and 'Y' in test_board[7]):
            print("Player 2 is the winner")
            sys.exit()
    else:
        print("Game Draw")
        validate = False```

Comment: Stack Overflow is not a place to have research, design or coding work done for you. That said, here's some hints: You will need to check the current contents of the board to do both of the things you're asking about. i.e. To see if a box is already picked up (by either player) and to determine whether the board is in a state that represents a draw. The game is a draw if, after all board positions have been occupied, neither player has three in a row (which you can probably determine even _before_ all the board positions are occupied).
Answer: Here I have modified many parts of your given code, added a few more conditions to check for occupancy and valid range input. Also added "draw" condition and made code more cleaner:
import sys
import numpy as np

def game_on():
    """User input to play the Game to stop"""
    game = False
    while not game:  # "while not False" ==> "while True"
        user_request = input("Enter 'Y' to start the game, 'N' to stop: ").upper()
        if user_request == 'Y':
            return True
        elif user_request == 'N':
            print("Thanks for Playing... Good Bye...")
            break
        else:
            print("Wrong choice! Select either Y or N")

test_board = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
draw_check = test_board[:]
draw_check[0] = '1'

def display_board(board):
    """Tic_Tac_Toe board to play, it will be displayed with numbers which user can select to replace the box in the board"""
    print(board[1] + '|' + board[2] + '|' + board[3])
    print('-----')
    print(board[4] + '|' + board[5] + '|' + board[6])
    print('-----')
    print(board[7] + '|' + board[8] + '|' + board[9])

def player_1():
    """Player_1 input to select the specific box"""
    choice = input("Player_1 enter a number between 1 to 9: ")
    while not choice.isdigit() or int(choice) > 9:
        choice = input("Player_1 enter a number between 1 to 9: ")
    return int(choice)

def player_2():
    """Player_2 input to select the specific box"""
    choice = input("Player_2 enter a number between 1 to 9: ")
    while not choice.isdigit() or int(choice) > 9:
        choice = input("Player_2 enter a number between 1 to 9: ")
    return int(choice)

def update_user_input_player_1(test_board, position):
    """Player_1 input will be replaced with X """
    # replacement = input("If it's player 1 enter X, if it's player 2 enter O: ")
    while not test_board[position].isdigit():
        print('Location is occupied!')
        position = player_1()
    test_board[position] = 'X'
    return test_board

def update_user_input_player_2(test_board, position):
    """Player_1 input will be replaced with Y """
    # replacement = input("If it's player 1 enter X, if it's player 2 enter O: ")
    while not test_board[position].isdigit():
        print('Location is occupied!')
        position = player_2()
    test_board[position] = 'Y'
    return test_board

###Still don't know how to put a draw if the list still has numbers
def winner_announcement(test_board):
    """Winner will be analysed and established"""
    validate = True
    # print(validate)
    while validate:  # "while True"
        if ('X' in test_board[1] and 'X' in test_board[2] and 'X' in test_board[3]) or (
                'X' in test_board[4] and 'X' in test_board[5] and 'X' in test_board[6]) or (
                'X' in test_board[7] and 'X' in test_board[8] and 'X' in test_board[9]) or (
                'X' in test_board[1] and 'X' in test_board[5] and 'X' in test_board[9]) or (
                'X' in test_board[3] and 'X' in test_board[5] and 'X' in test_board[7]):
            print("Player 1 is the winner")
            sys.exit()
        elif ('Y' in test_board[1] and 'Y' in test_board[2] and 'Y' in test_board[3]) or (
                'Y' in test_board[4] and 'Y' in test_board[5] and 'Y' in test_board[6]) or (
                'Y' in test_board[7] and 'Y' in test_board[8] and 'Y' in test_board[9]) or (
                'Y' in test_board[1] and 'Y' in test_board[5] and 'Y' in test_board[9]) or (
                'Y' in test_board[3] and 'Y' in test_board[5] and 'Y' in test_board[7]):
            print("Player 2 is the winner")
            sys.exit()
        elif not (np.array(draw_check) == test_board).any():
            print("It's a Draw!")
            sys.exit()
        else:
            validate = False

###Function call
play = game_on()

while play == True:
    display_board(test_board)
    player__1_result = player_1()
    update_user_input_player_1(test_board, player__1_result)
    winner_announcement(test_board)
    display_board(test_board)
    player_2_result = player_2()
    update_user_input_player_2(test_board, player_2_result)
    winner_announcement(test_board)


How to remove substring from list in python

Question: Assume that we have list like this  l = ['ab','bc','cd','ef','abcd','efi']  . In that l[0] = 'ab' and l[1] = bc are in l[4] = 'abcd' similarly l[3] = 'ef' also located in l[5] = 'efi'. so i  want to remove l[0],l[1],l[3]and need to return l = ['cd','abcd','efi'].Can any one solve this problem using python
Comment: it's not  clear , what do you want to remove exactly ? , and what did you try ?
Comment: In your example, do you want to remove `l[0]`, `l[1]`, and `l[3]`? Or do you want to remove `l[4]` and `l[5]`? Or do you want to do something else entirely?
Comment: Keep in mind that `str` values are immutable. You can't remove a substring from a string; you can only replace the string with a *new* string that does not contain the substring.
Comment: how efficient you need it to be? would an O(n2) brute force algorithm suffice or you need something smarter? How big is your list and your strings?
Answer: This is somewhat of a brute-force approach, but for each element, you can go over the list and check if it's contained in any other element:
result = [x for x  in l if not any(x != y and x in y for y in l)]


Redis cluster RTT

Question: We are currently using Redis as our data store. I am making a new section where we need to rank and paginate users. So i am thinking to use Sorted set for keeping rank and userid. And Hash for keeping user's profile data. It was brought to my attention by a colleague that we ll need to make many requests to redis to fetch users profile data using HGET. so Round trip time is going to be an issue. I was planning to use HMGET but After doing some research i found it may cause issues when Redis is clustered because Keys are stored in different redis nodes. I am using phpredis it has client side-sharding (I am having trouble understanding what that is).
i was thinking to do like this:
rank
zadd userRank 1 5
zadd userRank 2 2
zadd userRank 3 4
zadd userRank 4 3

userProfile
hset userProfile user:5 "{'userId':'5','name':'usera'}"
hset userProfile user:4 "{'userId':'4','name':'userb'}"
hset userProfile user:3 "{'userId':'3','name':'userc'}"
hset userProfile user:2 "{'userId':'2','name':'userb'}"

1) Will HMGET work normally in clustered Redis?
2) if not what can i do?
3) is there any better way to implement this?
Comment: What method are you using to cluster - the client-side sharding, Redis Cluster, or something else?
Comment: @ShaneMadden we are using client-side sharding
Answer:
HMGET should work in clustered Redis because it's only related to a single key. Each HMGET will be forwarded to the node that contains the key
/
It's not a good idea to store every serialized user in a hash you'll loose the ability to request/inc/dec some fiels.

Prefer:
hmset user:5 userId 5 name usera
hmset user:4 userId 4 name userb
hmset user:3 userId 3 name userc
hmset user:2 userId 2 name userb

Your ranking schema is ok. To retrieve & paginate between the top ranked users, just do a ZREVRANGEBYSCORE and then request each users.
Note: clustering is not the same as sharding.

Redis cluster RTT


Express $\lim_\limits{h\to 0} {f(x+2h) - f(x-h)\over h}$ in terms of $f'(x)$

Question: Given $f$ is differentiable on $\Bbb R$ and $f'$ is continuous on $\Bbb R$, use $f'(x)$ to express the following:
$$\lim_{h\to 0} {f(x+2h) - f(x-h)\over h}$$
Comment: kindly include your attempt.
Comment: $f(x+2h)-f(x)+f(x)-f(x-h)$
Comment: Hint: $$f'(x):=\lim_{h\to 0}\frac{f(x+h)-f(x)}{h}$$
Comment: It should be $3f'(x)$
Comment: Thank you very much. ${ 3 f'(x)}$ is what I got too. There is just one middle step that needs to be proved.
Comment: Or that we use $\lim_{h \to 0} \dfrac{f(x+2h)-f(x-h)}{(x+2h)-(x-h)} = f'(x)$
Answer: Hint
Why not to use Taylor expansion
$$f(x+k h)=f(x)+h k f'(x)+\frac{1}{2} h^2 k^2 f''(x)+O\left(h^3\right)$$ which will show the limit and how it is approached.

Express $\lim_\limits{h\to 0} {f(x+2h) - f(x-h)\over h}$ in terms of $f’(x)$


Exercises to internalise bass clef?

Question: I can read the treble clef because I learned it as a kid for guitar and school music lessons, but I've only been introduced to bass clef as an adult singing tenor and trying to pick up piano and bass. While I know how it works intellectually and can fake knowing it (two letters different) I can't seem to get it engrained.
I'm sure with time it'll happen naturally, I don't use bass clef that often. Are there any specific exercises you can recommend to get it burnt into my brain so it's natural?
Comment: From the way you describe your question, part of the problem lies in thinking about bass clef in terms of treble clef; you're "transposing" in order to make it work. Advice: One method is to accept bass clef on it's own terms as a separate thing. Use flashcards. Write the names of notes in your music until you don't need it. Exposure = internalization
Comment: I just wind up saying 'ace G' quite a lot.
Comment: @jjmusicnotes you are exactly right, I view it in terms of treble and am trying to get the transposition engrained. Rather than learning it in its own right, as I think you're saying
Comment: @AJFaraday - All Cows Eat Grass...
Comment: @Tim that one's new to me. Good one!
Answer: It's the same advice (of course) I give and adopt for most things. Lots of practice. Play or sing lots of music using bass clef. I still don't read the alto and tenor clefs (not to mention the soprano clef) that well. However, when composing music for viola, I always leave in the C clefs to force myself to read these. None of these are too hard. The G clefs wrap around G, the F clef(s) wrap (couple of dots in modern versions) around F, and the C clefs center on C. Usually this helps. I have found that I don't "transpose" to the clefs, I just read them directly.
It's easy to get used to the bass clef by playing lots of piano music. It need not be difficult music, just something that can be sightread.
Comment: I think when playing, you can easily do so without actually learning it... your hands might map to the keyboard but your brain doesn't.
Answer: You could try thinking of it in this way.  Concentrate on middle C.  In the treble clef it is of course on the first leger line below the stave.  Imagine handing over the same note to the bass clef, so it's now on the first leger line above the stave.  The bass clef is just a continuation of the treble clef in this way.  Once you understand that concept, you can fan out and learn the next note, B, etc.  I hope that might help.
Comment: Here's a picture showing the C note being shared by bass and treble clefs https://music.stackexchange.com/a/81926/51766
Comment: This is the logic way to understand the bass clef. I had the same problem like OP because I tried to transpose a third, this was not purposeful!
Answer: A method I employed was to start with what I would call "anchor notes." Based on what @Jomiddnz suggested, perhaps begin with C, as middle C is the first ledger line above the staff (when the F-clef is notated), and know that the second space from the bottom of the staff is also C.
From C, I used perfect intervals because they were approximately in the middle of octaves of C. I remembered that the perfect fourth above was an F, and the perfect fifth above was G. Using those pitch classes as reference points, I could determine the pitches between those points. Eventually, through practice and exposure, I "filled in the gaps" and could identify other pitches (E, B, etc.).
Answer: The method that I used was simple. To start with I just practiced reading the notes the same way I practiced reading words when I was in first grade at school. I didn't worry about playing them or singing them, just reading them for a few minutes each day until I could recognize them on sight without having to analyze their position. Once I could do that, the singing and playing came much easier for me. I used the same process when it came to recognizing Chords on sight, but that took a little longer for me to accomplish. The more I do it the quicker I get.
Answer: In part the problem may be about think that learning to read bass clef means memorizing the letters for the lines and spaces.
That may seem the obvious way that a clef is read, but another way to read is by the relative movements. Consider a melody starting on F3 - the F on which the bass clef is centered. Instead of reading something like F C E G, read like start on F, P4 down M3 up m3 up....
Combine that with reciting the letters ascending and descending in thirds (B D F... and B G E...) and in fifths (B F C... and B E A...). Reciting letters through triad inversion (A C E, C E A, E A C...) is a good method too. This is the thing to memorize as fixed and concrete. This should be internalized.
Putting both together, if a clef tells you the middle line is C and the next note ascends a fourth the next note is F. Knowing the specific letter comes from the internalize knowledge of the letter sequence of descending fifths.
In a way, you don't need to know the letters of the notes provided your move the correct interval distances. Again that may sound odd, but if your music reading starts to involve lots of different clefs or transposing on the fly, you start to develop a much more fluid sense of what the letters of the staff are.
After gaining experience reading bass clef you will end up memorizing lines and spaces. Like the bottom space is A, the middle line is D, etc. But it's probably better to let that come naturally instead of through rote memorization or mnemonics.

I don't use bass clef that often... Are there any specific exercises...

One way to look for material is get vocal or contrapuntal music where the bass part will have greater melodic quality that homophonic bass. Cut to the chase and get Bach's 371 Harmonized Chorales and just play the bass parts.
Answer: You need to practice, but you have to do it the right way. If you keep practicing by "transposing" the treble key, you'd be slowing down your progress severely, and strengthening a bad habit.
So, start with a few notes, and read them without having the treble key in mind at all. That first line is G, and first space is A. Period. Assign a note to that figure, without needing reference to anything else.
Probably, you are much slower while reading the bass clef because you are constantly referencing the treble clef, which takes more processing power from your head. And you probably made a habit out of it.

Exercises to internalise bass clef?


What is the SQLDump file for?

Question: One of our Windows 2003 servers that has WSUS is full on hdd space. Doing a search for files I find this SQLDump10000.txt file that is over 25gigs. I have done some googling and it says it's read write errors plus the query or what was in memory. Can someone give me a straight explaination of what is going on here?
Comment: That's not normal. Anything interesting in the log file?
Comment: The disk is full so transaction log writes failing at an astonishing rate. Thinking about wiping.
Answer: These dump files are created under two circumstances:

A SQL Server 'crash' occurs - either an A/V, assert or some other uncaught code error. In this case the file is a memory dump, the size and contents of which are dependent on the problem that occured.
You're signed up for Watson error reporting and DBCC CHECKDB found corruptions in a database. In this case, the contents are the list of corruptions that were found and a dump of corrupt disk pages from memory

Can you look in the SQL error log to see an indication of something going wrong, with a timestamp in the error log around the same time as the creation time of the dump file?
As far as your transaction log being full - I would copy off the dump file somewhere else as it sounds like it's messing up your log management. Don't do anything like deleting the log file or anything like that, or you're guaranteed to cause corruption.
Hope this helps
Answer: The easy answer comes by reading the file. It's a text file, not binary, so you should be able to glean what it is by just opening it up in Wordpad (Notepad can't open such large files).
More than likely it's a complete dump of all the data in the database, in one big SQL query. It's as large as it is because it's in text format, which doesn't use any compression at all.
Of course, the real problem comes when attempting to open a 25 Gig text file... I highly doubt you've got enough memory on that machine. I don't know if there's a windows version of head or tail, but they would come in mighty handy in this case.
Comment: I wonder if notepad will open a 25 GB file
Comment: I don't think it will even open anything larger than 12 Megabytes. there's some hard limit that I can't remember, but it's pretty small.

A program that reads a small part of the file at a time is what you need, unless you happen to have 25 GB of RAM. The unix programs "head" and "tail" can do that, but I don't really know of any Windows programs that do the same.

What is the SQLDump file for?


Requesting header by name angular

Question: I have an asp.net application that I'm attempting convert the front end to Angular. Getting header information is important to the view. I'm used to getting the header information like so in C#:
httpContext.Request.Headers["USERID"]

How can I do the same thing in an angular controller?
Answer: In asp.net each request runs in its own independent context and hence the header access as you have shown in your code make sense.
This does not hold good for angular or in fact any client side framework. You can always get the headers for any request or response made using angular $http but the question is which request? During the lifetime of the app you would make many such requests.
Let's say you want to get the current userid, you can create a service that returns the logged in user. There are two ways to implement such a sevice

create a method on server to return this data. Invoke this method from service and cache results
on the client side assuming there is a login request made through angular, implement a success callback method which can update the service with the logged user id.

You can look at $http documentation here to understand how to access headers.

Requesting header by name angular


If $\lim f(x)$ can theoretically be anywhere on the interval $0$ up to and including $\infty$, is the interval written $(0,\infty]$?

Question: Let's take $f(x)=a^x+b$ where $a\in\mathbb R$ and $b\in\mathbb R^+$. clearly $L=\lim_{x\to\infty}f(x)>0$, but is the interval written $L\in(0,\infty)$ because limits only approach infinity or is $L\in(0,\infty]$ because infinity is one of the values $L$ can take? I can't find an example of this one way or another.
Comment: You mean starting from $0$ (including it) to $\infty$ ?
Comment: @Spectre, I didn't really pay attention to the $0$ side, I'm more worried about whether $\infty$ is able to be expressed as explicitly a part of the interval without having to write it elsewhere.
Comment: Look at @BrianMoehring's answer.
Comment: What he said is true.
Answer: If you want to be able to write $L = \lim_{x\to\infty} f(x) = \infty$, then it would be false to state $L \in (0,\infty)$.
You would need to be able to write $L \in (0,\infty]$, but we also need to keep in mind that $L = \infty$ isn't a real number, so this only makes sense in the context of the extended real number line.
Comment: Thanks for helping me learn, sir !
Answer: Technically the answer is neither.
When we say $x \in (0, \infty)$, that notation is only valid when $x$ is a number.
When we say $\lim_{x\to\infty} = \infty$, that does not mean the limit is the number $\infty$. It means $\forall N> 0: \exists M> 0:$ if $x > M,$ then $f(x) > N$.
However you could extend the definition of the bracket $[a,b]$ notation to allow for such limits that do not take any value.


radical of an ideal: $\sqrt{IJ}$ $=$ $\sqrt{I}\sqrt{J}$ $=$ $\sqrt{I}\cap\sqrt{J}$ $=$ $\sqrt{I\cap J}$?

Question: Let $R$ be a commutative ring with $1$ and let $I,J\!\unlhd\!R$. The radical of an ideal $I$ is defined as $$\mathrm{rad}(I):=\sqrt{I}:=\{r\!\in\!R;\;\exists n\!\in\!\mathbb{N}: r^n\!\in\!I\}=\bigcap\{P;\; P\text{ is a prime ideal with }I\!\subseteq\!P\}.$$
I've managed to show that there holds$$\sqrt{I}\sqrt{J}\subseteq\sqrt{IJ}=\sqrt{I\cap J}=\sqrt{I}\cap\sqrt{J}.$$
How can I prove the first $\supseteq$?
NOTE: I guess there has been made a mistake in Ralf Froberg's An Introduction to Grabner Bases, page 19:
Answer: The result you wish to prove is false. For example, take $R=\mathbb{Z}$ and $I=J=(4)$. Then $\sqrt{I}\sqrt{J}=\sqrt{(4)}\sqrt{(4)}=(2)(2)=(4)$, while $\sqrt{IJ}=\sqrt{(4)(4)}=\sqrt{(16)}=(2)$.
Comment: Yes - we can similarly consider $I=J=(x_1^2)$, so that $\sqrt{I}\sqrt{J}=\sqrt{(x_1^2)}\sqrt{(x_1^2)}=(x_1)(x_1)=(x_1^2)$, while $\sqrt{IJ}=\sqrt{(x_1^4)}=(x_1)$.
Comment: Uf. Thanks. Is the result still false in $K[x_1,\ldots,x_n]$?
Comment: Thanks, Zev. I guess I should have tried more to find a counterexample, instead of trying to prove it.
Answer: If you assume that $I,J$ are relatively prime, then the claim is true.
For, by what you found, $\sqrt{I}\sqrt{J}\subseteq \sqrt{I}\cap\sqrt{J}$, and the intersection equals the product if they are coprime.


Async Clipboard API - clipboardchange event not fired

Question: Has anyone been able to hook the clipboardchange event of the new Async Clipboard API? I am trying this:
navigator.clipboard.addEventListener('clipboardchange', function (e) {
                console.log("navigator clipboardchange");
            });

But it never fires.
Comment: because `addEventListener` doesn't exist. If you type `navigator.clipboard` into the console and look at the `__proto__` you won't see it.
Comment: document.addEventListener for clipboardchange is also not working. but document.addEventListener for copy, cut, paste event is working. Could be a bug?
Comment: my guess is it is not implemented yet in any browser, although the other parts of the async clipboard specs work.
https://www.w3.org/TR/clipboard-apis/#clipboard-event-clipboardchange
Answer: At least for chrome this isn't implemented, see this bug for more details.
Reading the comments, there does seem to be some pressure to implement it, otherwise you'll have to poll
Answer: I know it doesn't really answer the question but this is a hack that will do the same :
async startClipboardPoll () {
  try {
    let clipboardContent;

    // Comment the following line
    // if you want to run  when clipboard change from other pages
    // (when the user focus back on your app)
    window.onfocus = async function () { clipboardContent = await navigator.clipboard.readText() }

    while (true) {
      await new Promise(r => setTimeout(r, 500)) // wait
      const previousContent = clipboardContent
      try {
        clipboardContent = await navigator.clipboard.readText()
      } catch (e) {
        // This function may fail if you focus another webpage
        // just ignoring and continuing.
        continue
      }
      if (previousContent == undefined) {
        continue
      }
      if (clipboardContent !== previousContent) {
        /*******************
         * Clipboard changed !
         *  here
         * `clipboardContent` is the clipboard content
         ******************/
      }
    }
  } catch (e) {
    console.warn('something went wrong');
    // maybe warn the user here this functionality is not available
  }
}

Then call this function somewhere in your code.


data-add-back-btn does not show a back button

Question: I have a simple jQuery mobile site with three pages in it.
In every page's div I've added
data-add-back-btn="true"

Still on none of the pages (not even on the sub-pages) a back button appears.
Is there some trick to this?
Comment: Are you using JQM 1.4? If yes, add it to header div not page. Edit: pages should have header div even if you're using earlier version. Without a header div the button won't be generated.
Answer: As of jQuery Mobile 1.4, data-add-back-btn="true" should be added to header div not page div.

Header


Why to pass function reference instead of method in onClick event of button in ReactJS?

Question: Whenever I pass function parentheses in onClick of button, it automatically calls when page loads even without clicking on button.
But when I don't pass function parentheses in onClick of button, it calls only when button is clicked.
With passing parentheses in function call
<button onClick={this.handleButtonClick()}>Increment</button>

Without passing parentheses in function call
<button onClick={this.handleButtonClick}>Increment</button>

Why function called automatically on page load whenever I pass parentheses to function even-though it is written inside onClick of button ?
Comment: you can still do method if you bind it (you can easily achieve it now using arrow binding): `onClick={() => this.handleButtonClick()}`, then it will not calls automatically when page loads
Answer: There's a difference between a function call and a function.
When a component renders, all statements are executed and expressions are evaluated. It's plain javascript, that's how javascript works.
this.handleButtonClick() is a function call, and therefore the function will be called once the component renders. I assume that handleButtonClick() returns undefined which will cause the button to render as <Button onClick={undefined} />. Now, if onClick is undefined, nothing will happen when the click actually happens as there is no function to be called.
this.handleButtonClick is just a reference to a function, it doesn't invoke it. You need to pass the function reference to onClick prop so that it can be called later by React, once the click actually happens.
Answer: It automatically calls because you are invoking it immediately by:
this.handleButtonClick()
"onClick" does not work like that, if you want to manually invoke the function you can use:
onClick={() => this.handleButtonClick()}
This is done automatically if you use function reference. Hence, you don't need to invoke it or use a callback function. Actually, using function reference is better since that function isn't recreated in every render.
Comment: Using function reference instead of an inline arrow function is better*.

Furthermore, In functional components you should use `useCallback` to prevent the function reference from changing.
In class components, functions should be methods of a class, like the OP has already done.
Comment: @AnteGulin, well, yes. I tried to explain it in my last paragraph with the reason (recreated in every render) :) "...you should use useCallback" Maybe not always? :) https://kentcdodds.com/blog/usememo-and-usecallback
Comment: You can still have a reference to a function that is created in the render method, it's still a reference, but the one that will change in every render too, hence why I commented to clarify further.
Comment: Oh, totally misunderstood. Yes, you are right about that. Using reference doesn't matter in functional components. Since OP uses `this` I explained it as they use class components and thought that you are giving extra information about functional components by saying "should use useCallback" as a general manner.
Answer: There is a difference between function reference and function invoking.
When you set the dynamic value like:
this.handleButtonClick()
that means you're invoking the function as soon as the component renders to the page.
But when you just pass the reference of the function like
this.handleButtonClick
that means React will call this function only when the user clicks on it.
Answer: JS will execute the function On each Render when you do OnClick(Func(params))
because you are calling a function instead of passing it.
Do this instead :
OnClick ( ()=> {Func(params) } )

Comment: I think you missed `}`. Can you check your syntax?
Answer: In react functional components, if we pass any function to onclick this way..  onClick={func()} this func will be called right away when the page is loaded, that for sure we don't want.
So we have two ways to make it work right.
one, pass it as a reference like this- onClick={()=> func()} (this means only pass reference to that function when page loads, but call that func() if component is clicked over.)
second, just pass the name of the function- onClick={func} (this means both pass reference and call on Call).
these both things work the same way. second one is more easy however the former one is used the most.


Why is Gödel's Second Incompleteness Theorem important?

Question: Given that the consistency of a system can be proven outside of the given formal system, Gödel says,

It must be noted that proposition XI... represents no contradiction to the formalities viewpoint of Hilbert....

Why do others disagree?
Who cares whether a system cannot prove its own consistency? Why would we expect such a thing?
Is it possible that a theory without multiplication, but with some other axiom or axioms (i.e., weaker in one sense but stronger in another) could prove P consistent and itself consistent?
Comment: "Given that the consistency of a system can be proven outside of the given formal system."

This is your problem. The the proof of consistency of your theory must be from a stronger theory, but, if you are wondering whether a theory is consistent, shouldn't you be worried about using a stronger theory?
Comment: Are you asking who cares if a theory is consistent, or are you taking as given that the consistency of mathematical theories is important?
Comment: You have to think about what a proof of consistency is: It is a claim that there is no sequence of sentences in your base language $L$, that satisfies certain conditions, and ends in $x \neq x$. So, to prove consistency, you need to be able to reason about the sentences in the language *or* be able to talk about things that have properties resembling sentences (e.g. Godel numbering). Thus, a proof of the consistency of $T$ from some $S$ requires that $S$ has the resources interpret the syntax of $T$.
Edit: This is how the Godel proof goes, consistency proofs in set theory are more involved.
Comment: "finitary proof" is a philosophical notion, so, it depends on precisely what you mean.
Comment: Who cares if a theory can prove itself consistent, if it can be proven using some other method?
Comment: Systems don't prove themselves undecidable. That requires metamath.
Comment: @James but Is it possible that a theory without multiplication, but with some other axiom or axioms (ie weaker in one sense but stronger in another) could prove P consistent and itself consistent?
Comment: @James so you are saying that godel was wrong when he wrote "it is conceivable that there exist finitary proofs that cannot be expressed in the formalism of P"?
Comment: @James I thought by finitary he meant basically recursive (he wouldnt use that word because he has already used it in a technical sense) or computable. For example, he constructed a recursive function Con(c), so his proof of the second theorem  is finitary.
Comment: @James wouldn't the existence of any proof outside of P contradict what you wrote in your comment?
Answer: You asked in a comment:

Who cares if a theory can prove itself consistent, if it can be proven using some other method?

Let us first observe that inconsistent theories are entirely worthless.  You want to know if $X$ is true, and then you prove that it is a consequence of theory $T$, so you now go around  believing $X$.  If you later  find that $T$ is inconsistent, then $T$ cannot lend any support whatever to $X$.  You might as well be flipping coins to decide what theorems are true.  $T$ is worthless; you will have to find some other reason to believe $X$.
So you would like to find some theory $T$ for which you have good reason to believe $T$ is consistent.  One plausible-seeming method is to choose axioms that are as simple as possible and which seem intuitively true.  But the crisis of set theory around 1905 shows that this method does not always work.  The comprehension axiom of naïve set theory is as simple and intuitively plausible as anything, and it is false.  The discovery that it was false precipitated the formalist programs of Hilbert and Whitehead & Russell, and was the direct motivation for Gödel's work.
So you might like a proof that theory $T$ is consistent.  Unfortunately, Gödel's theorem shows that $T$ cannot do it and neither can any theory strictly weaker than $T$.  So if you want to show that $T$ is not completely worthless, you need a theory, say $T'$, that is stronger in at least one aspect.  So suppose you show that $T$ is consistent, using $T'$.
If $T'$ is chosen to be strictly stronger than $T$, so that $T'$ shows as much as $T$ does and also shows that $T$ is consistent, then now you are in a very stupid position. If you weren't sure that $T$ was consistent, $T'$ cannot help you, because if $T$ is inconsistent, then so is $T'$.  So you didn't trust $T$, but you have even less reason to trust $T'$.  Suppose Shady Joe offers to sell you the Empire State Building for $5.  You are not sure, and suspect that Joe is trying to scam you.  Joe insists that he is honest, and suggests his Uncle Louie as a character witness.  So you go up to the state prison where Uncle Louie is serving a fifteen-year sentence for fraud, and, from his prison cell, Louie assures you that Shady Joe is offering you a fair deal.
But this is exactly the position we are in.  We would like to prove things about numbers, say the twin prime conjecture.  We have the Peano axioms, which we believe capture how numbers work.  But how do we know that from these axioms there is not some  proof, perhaps a very long one, that  $4923 = 4925$?  This would not show that $4923$ actually equals $4925$; it would only show that PA was broken.  We would have to throw away PA and use something else instead, as we did with naïve set theory.  If we knew that PA was consistent, we would know that there was no such proof.  And there is a proof of the consistency of PA using ZF set theory!  But this is like asking Uncle Louie if Shady Joe is telling the truth, because if PA is inconsistent, then so is ZFC; if PA was inconsistent, then ZFC would prove that PA was consistent anyway.
Comment: Dammit, so Shady Joe was scamming me all that time?! And to think I trusted Louie! >:(
Comment: Dude, you've devoted your *life* to trusting Louie.
Comment: I don't know the answer, but it's not easy to see how  a theory could be useful for proving things about mathematics if it can't even *express* the well-known claim that $2\times 2 = 4$.
Comment: @MadScientist I suppose if you believe that true and false are not a strict dichotomy, then it might make sense to have multiple theories that give opposing results. Of course, at that point, you've thrown the notion of consistency out the window.
Comment: Sure, trusting $T$ because $T'$ says it's consistent is not epistemologically sound, but is trusting $T$ just because it can prove itself consistent any better? Is that not some form of circular reasoning? Self-proving consistency has the advantage of being amenable to a precise mathematical definition, but that doesn't necessarily make it philosophically useful...
Comment: Is it completely impossible that a theory without multiplication, but with some other axiom or axioms (ie weaker in one sense but stronger in another) could prove it consistent and itself consistent. That is how I interpreted godel.
Comment: @MadScientist That's the situation this answer describes, though. They aren't really two separate theories, then, either. They form a single, larger theory together. One which, as a whole, still cannot be proven to be self consistent.
Comment: @MJD although your answer has the most votes it seems wrong given what ive read in this wikipedia article. http://en.m.wikipedia.org/wiki/Gentzen%27s_consistency_proof
Comment: So....Is my last comment so wrong headed that it doesn't merit a response?
Comment: Just because I trust Louie does not mean that Shady Joe haven't sold me the Empire State building for real. Maybe he's the original owner! Maybe he's one of those descendants of the original owners of the Manhattan island.
Comment: Maybe math just needs two theories instead of one.
Comment: @jpmc26 they wouldn't give opposing results. One theory would simply add to the other.
Comment: @JackM They Are Saying It Would Be Useful because it would Escape The regress of using another theory that is likewise possibly inconsistent.
Comment: @JackM You've misread. $T$ **cannot** prove itself consistent. It is incapable of doing so. So we're forced to accept some axioms without definitive proof; we can't do any better. That's math, science, life in general for you. We can't prove anything with total certainty. We have to accept a starting point.
Comment: @jpmc26 so you are saying that godel was wrong when he wrote "it is conceivable that there exist finitary proofs that cannot be expressed in the formalism of P"?
Comment: @MJD when you wrote " So you didn't trust T, but you have evenless reason to trust T'"  are saying that godel was wrong when he wrote "it is conceivable that there exist finitary proofs that cannot be expressed in the formalism of P"?
Comment: @MJD From Mauro ' s link to the wiki on Gentzen's proof in the Answer below I Found this: "Gentzen's proof also highlights one commonly missed aspect of Gödel's second incompleteness theorem. It is sometimes claimed that the consistency of a theory can only be proved in a stronger theory. The theory obtained by adding quantifier-free transfinite induction to primitive recursive arithmetic proves the consistency of first-order arithmetic but is not stronger than first-order arithmetic." This seems to contradict your answer. Does it not?
Comment: @MadScientist I'm just trying to clarify this answer. If I understand that quote correctly, it's saying that there may be higher order theories beyond $P$ that can show the consistency of $P$. The second incompleteness theorem says that any attempt of a theory proving *itself* consistent makes the theory inconsistent, not that higher order theories can't. I mean that when you accept a higher order theory, you now just have a different set of axioms. I can't imagine how theories could be so fundamentally segregated that they can't be treated as a single theory, but perhaps I'm just uninformed.
Comment: @MadScientist: I know this is very late, but your last comment is right, but then again are you saying you would suspect PA of being inconsistent while you wouldn't suspect $ε_0$ of being not well-ordered? =) Anyway, your first comment is also probably right; see https://en.wikipedia.org/wiki/Self-verifying_theories.
Comment: On this topic, logician [Jean-Yves Girard](https://en.wikipedia.org/wiki/Jean-Yves_Girard) says: "A consistency proof is like an insurance [policy] against an explosion of [the] Earth": useless because if the Earth is destroyed, you never get to collect your insurance settlement.
Answer: Hilbert's program aimed at "solving" the foundational issues (form Cantor and Frege, to Russell and Brouwer) proving the consistency of the "main" mathematical theories, like arithmetic, real analysis and set theory.
In order to prove that, the program developed concepts and tools of metamathematics, i.e. the discipline based on mathematical logic able to study the mathematical theories as mathematical objcets themselves.
This metamathematical activity has to be "performed" into a "secure" mathematical theory: the "elementary" part of arithmetic.
This theory must supply the tools sufficient for the consistency proof of other theories.
Of course, this "gound-level" mathematical theory must be itself consistent.
Unfortunately, Gödel's Second Incompleteness Theorem shows that a formalized arithmetical theory having "enough resources" (this concept is made precise by the theorem) to be suitable for the metamatheatical aims is not able to prove its own consistency, and neither the consistency of "more powerful" theories like real analysis and set theory.

Regarding Gödel's comment after Th.XI :

I wish to note expressily that Theorem XI do not contradict Hilbert's formalistic viewpoint [emphasis added]. For this viewpoint presupposes only the existence of a consistency proof in which nothing but finitary means of proof is used, and it is conceivable that there exist finitary proofs that cannot be expressed in the formalism of $P$.

And this was exactly what happened with Gentzen's consistency proof.
Some comments are useful here :

Hilbert's concept of finitary is not precise: but it's hard to escape from the expectation that the "finitary part" of arithmetic must include $\mathsf{PA}$; thus, G's Th applies.

Gentzen's proof is hardly "finitistic".

the original aim of Hilbert's program was to "convince" intuitionstic mathematicians that axiomatized set theory was "secure"; if so, any "ostensive" consistency proof based on a model of, e.g. arithmetic, built up into set theory was clearly useless.

Added
Regarding your added question, you can see (in general) :

Peter Smith, An Introduction to Gödel's Theorems (2nd ed 2013).

In particular, you can see the overview of Presburger's arithmetic for a (very weak) first-order theory of the natural numbers with addition, without multiplication.
This theory is complete and decidable; thus, it "eludes" G's First Th.
Unfortunately, without multiplication it has not enough resources to implement the arithmetization of syntax; thus, it is unable to "perform" the basic metamathematical tasks and so it cannot prove relevant metamathemetical properties, like consistency of a theory (and neither of itself).
Gentzen's consistency proof "eludes" in some way G's Second Th :

Gentzen showed that the consistency of first-order arithmetic is provable, over the base theory of primitive recursive arithmetic with the additional principle of quantifier-free transfinite induction up to the ordinal $ε_0$.
Gentzen's proof also highlights one commonly missed aspect of Gödel's second incompleteness theorem. It is sometimes claimed that the consistency of a theory can only be proved in a stronger theory. The theory obtained by adding quantifier-free transfinite induction to primitive recursive arithmetic proves the consistency of first-order arithmetic but is not stronger than first-order arithmetic.
For example, it does not prove ordinary mathematical induction for all formulae, while first-order arithmetic does (it has this as an axiom schema). The resulting theory is not weaker than first-order arithmetic either, since it can prove a number-theoretical fact - the consistency of first-order arithmetic - that first-order arithmetic cannot. The two theories are simply incomparable.
Comment: I was unaware of this. My only knowledge of the second incompleteness theorem is from godels paper.
Comment: @MadScientist - I know ... the link to Stanford's entry provides you with a very useful intro to the background of G's Th.
Comment: Thanks. I'm going to get back to this with proper responses. Currently dealing with a fussy baby.
Answer: Based on your last comment:

"Who cares if a theory can prove itself consistent, if it can be
  proven using some other method? "

It's not that we can prove it using some other method, but we can prove it using some other (stronger) theory. But how can we prove that this stronger theory is consistent? (if this stronger theory itself is not consistent, it means that our proof does not amount to much as nobody assures as that it's result are indeed true)
So now we want to prove the consistency of this stronger theory. But we need another theory for that! A stronger one! And how do we prove the consistency of the latter?
You see where we are heading? You can make the exact same reasoning for ever, so proving the consistency of a theory using another one doesn't do much because then we can't prove the consistency of the latter, and we are doomed
Comment: Did Godel himself not appreciate this point when he wrote that it "represents no contradiction to the formalistic standpoint of hilbert. For this presupposes only the existence of a consistency proof effected by finite means  and there might be finite proofs that are not in p. " isn't it possible that the consistency proof of p could be in a system that is weaker than p (in the sense that it doesn't include multiplication for example,  but perhaps something else?)
Comment: @MadScientist If you can prove something with a system weaker that $p$, then you can prove it with $p$ itself - isn't that what "weaker" means?


Is it possible to group elements without closing the stream?

Question: Is it possible to group elements in a Stream, but then continue streaming instead of having to create a new stream from the EntrySet of the returned map?
For example, I can do this:
public static void main(String[] args) {
    // map of access date to list of users
    // Person is a POJO with first name, last name, etc.
    Map<Date, List<Person>> dateMap = new HashMap<>();
    // ...
    // output, sorted by access date, then person last name
    dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
        Date date = e.getKey();
        // group persons by last name and sort
        // this part seems clunky
        e.getValue().stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()))
                .entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e2 -> {
            // pool agent id is the key
            String lastName = e2.getKey();
            Set<Person> personSet = e2.getValue();
            float avgAge = calculateAverageAge(personSet);
            int numPersons = personSet.size();
            // write out row with date, lastName, avgAge, numPersons
        });
    });
}

Which works just fine, but seems a little clunky, especially the streaming into a map, and then immediately streaming on the entry set of that map.
Is there a way to group objects in a stream, but continue streaming?
Comment: the short answer is *No*; but may be you can explain exactly what you want to achieve (input and output) and we can help with that?
Comment: None of that is obvious in your question.  All that I can deduce is that you want to order the Persons by date, and then by last name.  Is that sorting sufficient, or do you really need them grouped?
Comment: VGR is right.. it's at least slightly confusing; the best way to explain it would be to provide an example here
Comment: @lucasvw that's not an example I meant... what I had in mind is: here is the Map I have (with some pseudo-real small data) and here is what List/Map/whatever I want to end-up with
Comment: @Eugene Thanks. The question contains exactly what I want to achieve, more or less. I have the dateMap to work with, and I need to output rows to a report grouped by date, then last name, and ordered by either date or last name.
Comment: I think I need them grouped. I added to the example - does that help?
Comment: I think you're overthinking what I want to do. The map has a few thousand entries, each of which has a list of anywhere from a dozen to a few hundred Person objects in the list. I need to write out a row for each distinct group of last name and date, and the output needs to be ordered by date and last name in either order. I could provided pseudo-data, but I'm not sure how that changes anything.
Answer: You can shorten your code by using Map.forEach, downstream collectors, TreeMap, and IntSummaryStatistics.
By grouping into a TreeMap (instead of leaving it up to the groupingBy collector), you get the names sorted automatically. Instead of immediately getting the grouped map, you add a summarizingInt collector that turns the list of persons with the same name into IntSummaryStatistics of their ages.
public static void main(String[] args) {
    Map<Date, List<Person>> dateMap = new HashMap<>();
    dateMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(e -> {
        Date date = e.getKey();

        e.getValue().stream()
                    .collect(Collectors.groupingBy(Person::getLastName,
                                                   TreeMap::new,
                                                   Collectors.summarizingInt(Person::getAge)))
                    .forEach((name, stats) -> System.out.println(date +" "+
                                                                 lastName +" "+
                                                                 stats.getAverage() +" "+
                                                                 stats.getCount()));
    });
}

If you have control over the type of the initial map, you could use TreeMap there as well, and shorten it further:
public static void main(String[] args) {
    Map<Date, List<Person>> dateMap = new TreeMap<>();
    dateMap.forEach((date, persons -> { ...

Comment: I know, it's tempting to use a `TreeMap`, to have the map already sorted after the `groupingBy` collection, but contrary to the first intuition, collecting into the default (hash) map and sorting afterwards will be more efficient in most cases.
Comment: Doing the `summarizingInt` during the grouping instead of creating temporary `Set`s will indeed improve the performance. Grouping into a `TreeSet` becomes interesting if you don't use the natural order as grouping criteria, which leads to the point that the `Map` is unavoidable, as it is a crucial part of the grouping operation itself. The map logic determines the groups (via its lookup implementation) and the map provides the required intermediate storage. Since you don't know to which group the last element belongs to, there is no way to proceed with any group before having grouped all items
Comment: @Holger That was my thinking. Thank you though, Malte!
Comment: @Holger thanks for pointing it out. I thought there might be a difference there, but wanted to keep the code shorter. Lucas, if that performance impact is of concern, you could still use the downstream collector to summarize the persons, and replace `forEach` with `entrySet.stream.sorted.foreach`. It almost the same as your code then, but at least the average is already calculated. Holger, do you have an idea how to get around materializing the grouped map?
Answer: There are several different ways to interpret the question, but if we restate the question as, "Is it possible to group elements within a Stream without using a terminal operation and apply stream operations to the resulting groups within the same stream pipeline," then the answer is "Yes." In this restatement of the question, terminal operation is defined in the way that the Java 8 streams API defines it.
Here is an example that demonstrates this.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

class StreamGrouper {

    public static class GroupableObj<K extends Comparable<? super K>, T>
            implements Comparable<GroupableObj<K, T>> {

        private K key;
        private T obj;
        private Set<T> setOfObj;

        public GroupableObj(K key, T obj) {
            if (key == null) {
                throw new NullPointerException("Key may not be null");
            }
            this.key = key;
            this.obj = obj;
        }

        @Override
        public int compareTo(GroupableObj<K, T> otherGroupable) {
            return key.compareTo(otherGroupable.key);
        }

        @Override
        public boolean equals(Object otherObj) {
            if (otherObj == null) {
                return false;
            }
            if (otherObj instanceof GroupableObj) {
                GroupableObj<?, ?> otherGroupable =
                        (GroupableObj<?, ?>)otherObj;
                return setOfObj == otherGroupable.setOfObj &&
                        key.equals(otherGroupable.key);
            }
            return false;
        }

        public Set<T> getGroup() {
            return setOfObj;
        }

        public K getKey() {
            return key;
        }

        public T getObject() {
            return obj;
        }

        @Override
        public int hashCode() {
            return key.hashCode();
        }

        public void setGroup(Set<T> setOfObj) {
            this.setOfObj = setOfObj;
        }
    }

    public static class PeekGrouper<K extends Comparable<? super K>, T>
            implements Consumer<GroupableObj<K, T>> {

        private Map<K, Set<T>> groupMap;

        public PeekGrouper() {
            groupMap = new HashMap<>();
        }

        @Override
        public void accept(GroupableObj<K, T> groupable) {
            K key = groupable.getKey();
            Set<T> group = groupMap.computeIfAbsent(key,
                    (k) -> new HashSet<T>());
            groupable.setGroup(group);
            group.add(groupable.getObject());
        }
    }

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        PeekGrouper<Long, Double> myGrouper = new PeekGrouper<>();

        Random simpleRand = new Random(20190527L);
        simpleRand.doubles(100).boxed().map((dblObj) ->
                new GroupableObj<Long, Double>(
                myKeyExtractor.apply(dblObj), dblObj)).peek(myGrouper).
                distinct().sorted().
                map(GroupableObj<Long, Double>::getGroup).
                forEachOrdered((grp) -> System.out.println(grp));
    }
}

In order to make a program that can be compiled and executed on its own, this example moves away from using the Person objects that are referenced in the question, but the grouping concept is the same, and the code from the question could turn into something like the following.
PeekGrouper<String, Person> myGrouper = new PeekGrouper<>();
e.getValue().stream().map((p) -> new GroupableObj<String, Person>(
        p.getLastName(), p)).peek(myGrouper).distinct().sorted().
        forEachOrdered(e2 -> {
    String lastName = e2.getKey();
    Set<Person> personSet = e2.getGroup();
    float avgAge = calculateAverageAge(personSet);
    int numPersons = personSet.size();
    // write out row with date, lastName, avgAge, numPersons
});

Please note that in order for this example to work, it is required that the stream call both the distinct function (which reduces the stream to only a single instance of each group) and the sorted function (which ensures that the entire stream has been processed and the groups have been fully "collected" before processing continues). Also note that as implemented here GroupableObj is not safe to use with parallel streams.  If the terminal operation of the stream does not require that the groups be fully "collected" when it processes the objects -- for example, if the terminal operation were something like Collectors.toList() -- then a call to sorted would not be required.  The critical point is that any portion of the stream that sees the groups prior to a call to sorted and prior to the end of a terminal operation (including processing during a terminal operation) may see a group that is incomplete.
For the specific example in the question, it may be somewhat less time-efficient to sort the objects before grouping them if many of them are in the same group, but if you are willing to sort the objects before grouping them, you can achieve the same functionality without performing any streaming after doing the grouping.  The following is a rewrite of the first example from this answer that demonstrates this.
import java.util.Comparator;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collector;

class PreSortOrderedGrouper {

    public static void main(String[] args) {

        Function<Double, Long> myKeyExtractor =
                (dblObj) -> Long.valueOf(
                (long)(Math.floor(dblObj.doubleValue()*10.0)));
        Random simpleRand = new Random(20190527L);
        Consumer<Set<Double>> groupProcessor =
                (grp) -> System.out.println(grp);
        simpleRand.doubles(100).boxed().sorted(
                Comparator.comparing(myKeyExtractor)).
                collect(Collector.of(HashSet<Double>::new,
                (set, dblObj) -> {
                    if (set.isEmpty() || myKeyExtractor.apply(set.iterator().
                            next()) == myKeyExtractor.apply(dblObj)) {
                        set.add(dblObj);
                    } else {
                        groupProcessor.accept(set);
                        set.clear();
                        set.add(dblObj);
                    }
                },
                (setOne, setTwo) -> {
                    throw new UnsupportedOperationException();
                },
                (finalSet) -> {
                    groupProcessor.accept(finalSet);
                    return Integer.valueOf(0);
                }));
    }
}

I can't be sure that either of these examples will feel less "clunky" to you, but if the example in your question is a pattern you use frequently, you could probably adapt one or both of these examples in ways that will suit your purposes and, aside from a few utility classes, result in no more code than you are currently using.


Interesting question about Borel-sigma algebra and Lebesgue measure.

Question: Let $a , b\in \Bbb R$ , $a>0$
$T_{a,b}: \Bbb R\to \Bbb R$ defined as:
$T_{a,b}(x)=ax+b$.
Show that

$T_{a,b}(B_R)=B_R$

2.$\forall A\in{B_R}$ $m(T_{a,b}(A))=am(A)$
Hints:
Notice that $T_{a,b}$ is bijection and its inverse is $T_{\frac{1}{a},\frac{-b}{a}}$.
First prove that $T_{a,b}$ is a sigma-algebra that contains all the open finite intervals and then look at:
$s: B_R\to [0,\infty]$
$s(A)=am(T^{-1}_{a,b}(A))$
$m$ is Lebesgue measure.
I tries to write:
$T_{a,b}(B_R)={aI+b : I\in B_R}$.
We know that the borel sigma algebra is generated by the collection of open intervals, closed intervals..
It's obvious that $T_{a,b}(B_R)\subset B_R$ as $I\in T_{a,b}(B_R)$ and $I=T_{1,0}$.
Then I have to show that $T_{a,b}(B_R)$ is a sigma-algebra that contain all of the finite segments so by the fact that $B_R$ is the minimal sigma algebra that contains all the finite segments, we get that $B_R\subset T_{a,b}(R)$.
So, we must prove two axioms, T is closed under complements and countable unions.
I tried to use the hint mentioned, but it's not obvious for me how to do it.
Thanks for any help.
Answer: For the first question, you can prove something more general( also more clean so see)
Lemma : For any function between two space $f: A \rightarrow B$, we have: $ f^{-1}( \sigma(S))= \sigma (f^{-1}(S))$ , where $S$ is any family of subsets of $B$.
The first question is the direct consequence of the above lemma by using $f(x)= \frac{x-b}{a}$
For the second question, we denote the righthand side measure as $\mu_2$, the lefthand side measure as $\mu_1$, they clearly equal on any elements in the semiring $ S=\{ (a,b] : a<b\}$, hence by the unicity of Caratheodory's extension theorem (+ the $\sigma$-finiteness), we get the equality.

Hints for lemma: You can firstly prove the $LHS$ is a $\sigma$-algebra, then the inclusion $ RHS \subset LHS$ is clear.
For the other direction, you define $P:= \{ A | f^{-1}(A) \in \sigma( f^{-1}(S))\}$ , that is the familiy of set $A$ such that $f^{-1}(A) \in \sigma( f^{-1}(S))$. So what is left to do is proving that $ \sigma(S) \subset P$.  So do this, you prove that $S \subset P$ and $P$ is a sigma algebra.

P/s: I assume that you are familiar with monotone class argument.
Comment: @Paresseux Nguyen can you give more information for the 2nd part..
Comment: In fact, you can also use the monotone class argument to solve the second part ( if you are familiar with it) , but just considering the famility:
$$S:= \{ A \in \mathcal{B}(\mathbb{R})  | \mu_1(A)=\mu_2(A)\}$$
You can prove that $S$ is a $sigma$-algebra, that contains all open interval $(u,v)$
Hence $ \mathcal{B}(\mathbb{R})  \subset S$, and that is:
$$ \mu_1(A)= \mu_2(A)$$ for all $A$ measurable.
Comment: @Almaa :  Your last reply was unedited so I didn't check it. Yeah you can do that to show the continuity, also you noticed what I had overlooked. I didn't pay attention that these measures are sigma-finite, not finite. And this makes $S$ no longer a dynkin system. Sorry about that. (though we can always fix that problem but that will lead to unnessary complification of our solution)
Comment: So let's stick with Caratheodory's approach then. Here is the Caratheodory's theorem in sigma finite case. https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_extension_theorem  So you see, $\mu_1$ and $\mu_2$ are the extensions of the same measure on a semiring. And because they are sigma finite, hence due to the unicity of extension, $\mu_1$ and $\mu_2$ must be identical.
Comment: I tried to do it many times but still not working:(
Comment: @Almaa : Okay. Let $\mu_1$ and $\mu_2$ be two functions such that: $$\mu_1(A)= \mu( T(A)) ; \mu_2(A)= a\mu(A)$$
Clearly, $\mu_1 $ and $\mu_2$ are two measures. ( $\mu_1$ is an image measure, $\mu_2$ is just a multiplication from a given measure)
Besides,$$\mu_1( (u,v] ) =a(v-u) =\mu_2( (u,v])$$
(By calculation), so $\mu_1$ and $\mu_2$ are identical on the element of the semiring $B=\{ (u,v] \}$  .Furthurmore, $\mu_2$ is $\sigma$-finite, hence by unicity of Caratheodory's extension theorem. We're done.
Comment: @Almaa : Okay. Let $\mu_1$ and $\mu_2$ be two functions such that: $$\mu_1(A)= \mu( T(A)) ; \mu_2(A)= a\mu(A)$$
Clearly, $\mu_1 $ and $\mu_2$ are two measures. ( $\mu_1$ is an image measure, $\mu_2$ is just a multiplication from a given measure)
Besides,$$\mu_1( (u,v] ) =a(v-u) =\mu_2( (u,v])$$
(By calculation), so $\mu_1$ and $\mu_2$ are identical on the element of the semiring $B=\{ (u,v] \}$  .Furthurmore, $\mu_2$ is $\sigma$-finite, hence by unicity of Caratheodory's extension theorem. We're done.
Comment: Thanks, S is a sigma algebra:let A in S so A in B(R) and also $\mu(T(A^c))=\mu(T(A))^c= (\mu(T(A))^c=(a\mu(A))^c=a\mu(A^c)$ and I can do same approach for showing that S is closed under countable unions.$\mu(T(c,d))=\mu(ac+b,ad+b)=\mu(ac+b,ad+b]\setminus{ad+b}$ then saying that $\mu({ad+b})=0$ and continue getting that S contains all the open intervals thus It containd B(R)?
Or can I do what as above for an interval (u,v], since B(R) is also generated by the collection of the ${(u,v], u<v}$ ? I couldn't understand how to use the $\sigma$ finite and the theorm to conclude in the 1 method
Comment: @Paresseux Nguyen using the fact that the measure of a singleton {ad+b} is zero
Comment: @Paresseux Nguyen For showing that the S is a sigma algebra , is it true that: if $A\in S$ then $A\in B(R)$ and $\mu_2(A^c)=\mu(T(A^c))=a\mu(A^c)=(a\mu(A))^c=\mu_1(A^c)$ that shows that S is closed under complements.
Comment: It is true if $\mu_1( \Omega)=\mu_1( \Omega)<+\infty$, and wrong otherwise.
Comment: In our case, for solving using the sigma-algebra, can we say that?
Comment: No, we can't that kind of complement argument when measures are infinite.
Answer: In fact, if $T:X\to X$ is any homeomorphism, then $T$ carries Borel sets bijectively to Borel sets. Prove this in the usual way, letting $B=\{T(E):E\in \mathscr B(X)\}$ and showing that $B$ is a $\sigma$-algebra that contains the open sets in $X$:
If $T(E_i)\in B$ then $\bigcup T(E_i)=T\left(\bigcup E_i\right)\in B$ because $\bigcup E_i\in \mathscr B(X).$ A similar argument works for complements.
Now, if $U$ is open in $X$, then $T^{-1}(X)$ is open in $X$ and therefore $T^{-1}(U)\in \mathscr B(X).$ But then $U=T(T^{-1}(U))\in B$ by defnition.
So, $B$ is a $\sigma$-algebra on $X$ that contains the open sets. That is, $\mathscr B(X)\subseteq B$. Replacing $T$ by $T^{-1}$ gives the reverse inclusion, so $\mathscr B(X)=B.$
Comment: You proved that for any X, which it can be replace by R, right?  The fact that T is a homeomorphism was not be used in the question?
Comment: @Matematleta , Thanks, it was helpful, can you explain the second part? In addition, for the complement can I say that if $I\in B$ so I=T(E) then $I^c=(T(E)^c=T(E^c)$ where $E^c\in B(x)$ ? Can we say that $T^{-1}(U)$ is open in X since T is continuos?
Comment: @Matematleta can you explain it?
Comment: @ Almaa @  user726608 If $A\in B$ then $A=T(E)$ for some Borel set $E$. Now, as $T$ is a homeomophism, $T^{-1}$ is continuous, so $(T^{-1})^{-1}=T$ carries Borel sets to Borel sets. That is, $A=T(E)\in \mathscr B(X).$


Elementary Model Theory

Question: I'm working through section 4.3. on model theory from Dirk van Dalen's Logic and Structure (fifth ed.) and am struggling with van Dalen's sometimes sloppy way of presenting proofs.
As usual let a structure $\mathfrak{A}$ be elementarily embeddable in a structure $\mathfrak{B}$ ($\mathfrak{A} \prec \mathfrak{B}$), if $\mathfrak{A}$ is isomorphic to some elementary substructure of $\mathfrak{B}$. Furthermore, let $\hat{\mathfrak{A}}$ be the structure resulting from $\mathfrak{A}$ by adding all the members of its domain as constants.
One crucial lemma in van Dalen's treatment of non-standard models is the following:

$\mathfrak{A} \prec \mathfrak{B} \Leftrightarrow \hat{\mathfrak{B}} \models Th(\hat{\mathfrak{A}})$

where $\models$ is the usual first-order satisfaction relation generalized for sets of sentences and $Th(\mathfrak{A})$ the set of sentences true in $\mathfrak{A}$.
Now, my main source of confusion in the proof of the left-to-right direction is that van Dalen assumes without proof that $\hat{\mathfrak{A}} \models \phi(\bar{a_1}, \ldots, \bar{a_n})$ entails $ \mathfrak{A} \models \phi(\bar{a_1}, \ldots, \bar{a_n})$ (let $\vec{a_i}$ abbreviate the sequence $\bar{a_1}, \ldots, \bar{a_n}$) and $\mathfrak{B} \models \phi(\vec{a_i})$ entails $\hat{\mathfrak{B}} \models \phi(\vec{a_i})$. Why is that so?
Concerning the right-to-left direction it's easy to prove that $\mathfrak{A}$ is a substructure of $\mathfrak{B}$ and that $\mathfrak{A} \models \phi(\vec{a_i}) \Rightarrow \mathfrak{B} \models \phi(\vec{a_i})$ for all ${a_i}$ from the domain of $\mathfrak{A}$. But I don't get the converse direction.
Any help would be greatly appreciated.
Comment: You probably mean $\hat {\mathfrak A} \models \phi(\bar a_1, ..., \bar a_n)$ entails $\mathfrak A \models \phi(\bar a_1, ..., \bar a_n)$. If this is not clear, then try to prove it by induction on $\phi$. The proof might depend on exact definitions van Dalen uses. So you are better of including them in the question.
Comment: Extending language $\mathfrak{L}$ by adding constant symbols for all elements $a\in A$ of the domain of some structure $\mathfrak{A}$ and interpretating these as the original elemnts $a\in A$ is just an equivalent (and sometimes more conveneint if u want to avoid explicit variable assignment functions) way for assigning truth values - to sentences.

See for instance *"There is a second common approach to defining truth values that does not rely on variable assignment functions.."* at http://en.wikipedia.org/wiki/First-order_logic
Answer: As per Yoneda's comment, you have to consider the basic definition of interpretation; see Ch.3.4 Semantics, page 64-on, at page 65 :

Let us now present a definition of interpretation for the general case. Consider [the structure] $\mathfrak{A} = \langle A,R_1,\ldots, R_n,F_1,\ldots, F_m, \{ c_i |i \in I \} \rangle$ of a given similarity type $\langle r_1,\ldots, r_n; a_1,\ldots, a_m; |I| \rangle$ [where, see page 54 : ] the $c_i$ are elements of A (constants).

I think that it is better to call them distinguished elements, in order to avoid confusion with the constants $\overline c_i$, which are symbols of the language [see page 56]; of course, the $c_i$'s are the reference of the $\overline c_i$'s.
The corresponding language has predicate symbols $\overline R_1,\ldots,\overline R_n$, function symbols $\overline F_1,\ldots, \overline F_m$ and constant symbols $\overline c_i$. $L(\mathfrak A)$, moreover, has constant symbols $\overline a$ for all $a \in |\mathfrak A|$.
Then see page 67 :

If $\varphi$ is a formula with free variables, say $FV(\varphi) = \{ z_1,\ldots, z_k \}$, then we say that $\varphi$ is satisfied by $a_1,\ldots, a_k \in |\mathfrak{A}|$ if $\mathfrak{A} \vDash \varphi[\overline a_1,\ldots, \overline a_k/z_1,\ldots, z_k]$ [...].

The definition of $\hat{\mathfrak{A}}$, page 112, is nothing new :

Since we will often join all elements of $|\mathfrak A|$ to $\mathfrak A$ as constants, it is convenient to have a special notation for the enriched structure: $\hat{\mathfrak{A}} = (\mathfrak{A}, |\mathfrak{A}|)$.

Thus, we have that : $\hat{\mathfrak{A}} \vDash \varphi (\overline a_1,\ldots, \overline a_n)$ entails $\mathfrak{A} \vDash \varphi(\overline a_1,\ldots, \overline a_n)$ because the enriched strucure $\hat{\mathfrak{A}}$ is obtained from $\mathfrak{A}$ "adding" all the  $a \in |\mathfrak{A}|$ as distinguished elements.
In this way, for the strucuture $\hat{\mathfrak{A}} = (\mathfrak{A}, |\mathfrak{A}|)$, the two sets of constants [symbols] : $\{ \overline c_i |i \in I \}$ and $\{ \overline c_i |i \in I \} \cup \{ \overline a_i |$ for all $a \in |\mathfrak{A}| \}$ are the same.
What happened is that we have expanded the original language $L$ to $L'$, adding new symbols : a name for each object in the domain.
Having expanded the language, we have to expand also the strucuture, because a structure $\mathfrak A$ is a domain $A$ plus a function $\mathcal I$ "mapping" the symbols of the language into objects and subsets of $A$.
Thus, we have to extend the mapping $\mathcal I$ in order to take into account the new symbols of the expanded language : but the domain does not change.
See  C.C.Chang & H.Jerome Keisler, Model Theory (3rd ed - Dover reprint), page 21 :

The processes of expansion and reduction [of a model or structure] do not change the universe of the model.

Elementary Model Theory


Linear Algebra, Finding matrix for transformation

Question: I am revising for a Linear Algebra exam and am quite stuck on this question-any help, guidance or tips appreciated!
So I have a mapping $T:V\rightarrow V$ where $V$ is a finite dimensional vector space. I am a told that there is some vector $v\in V$ such that the set of vectors $v, Tv, T^2v,...T^{n-1}v$ forms a basis for V. Then, I am asked to express $T^nv$ as a linear combination of these vectors.  And from here to write down a matrix of T.
I thought that $T^nv$ could only be expressed arbitrarily in terms of the basis vectors, I couldn't know any specifics, so $T^nv=a_1v+...+a_nT^{n-1}v$.
I then get my matrix for T with respect to this basis as $$
\begin{matrix}
0 & 0 & 0 & ...&0&a_1 \\
1 & 0 & 0 &...&0&a_2 \\
0 & 1 & 0 &...&0&a_3 \\
...&....&...&...&...&...\\
0&0&0&...&1&a_n
\end{matrix}
$$
Then, from here, they want me to show that the minimal polynomial and the characteristic polynomial are equal. This is where I think I get stuck, unless I've missed something earlier, as I end up with a complicated expansion for the characteristic polynomial.
I think I want to show that the matrix has $n=dimV$ eigenvalues, as then, as the minimal polynomial has a root at every eigenvalue, they must be equal. I don't know if I want to get it into triangular form to do this, and if so how.
Answer: Proof minimal polynomial = characteristic polynomial
Let
\begin{equation}
\mu(t) = \sum_{i=0}^{\deg \mu(t)} c_i t^i
\end{equation}
be the minimal polynomial, and let $f(t)$ be the characteristic polynomial of $A$. We know that $\mu(t)$ divides $f(t)$; so $\deg \mu(t) \leq \deg f(t)$. Once we show that the degrees are the same, the fact that both polynomials are monic forces them to be equal. So, to prove this, note that
\begin{align}
0 &= \mu(T)(v) \\
&= \sum_{i=0}^{\deg \mu(t)}c_i T^i(v)
\end{align}
Notice that if $\deg \mu(t) < n = \deg f(t)$, this would contradict the linear independence of the basis $\{ v, T(v), \dots, T^{n-1}(v) \}$. Hence, the degrees are the same, thus completing the proof.
Additional Info:
I'll modify your notation slightly. We know there exist constants $b_0, \dots, b_{n-1} \in F$ (the field we're working over) such that
\begin{equation}
T^n(v) + \sum_{i=0}^{n-1}b_i \cdot T^i(v) = 0
\end{equation}
Then, the matrix of $T$ relative to the given basis will be
\begin{equation}
A=
\begin{pmatrix}
0 & 0 & 0 & \dots & 0 & -b_0 \\
1 & 0 & 0 & \dots & 0 & -b_1 \\
0 & 1 & 0 & \dots & 0 & -b_2 \\
\vdots & \vdots & \vdots & \ddots & \vdots & \vdots \\
0 & 0 & 0 & \dots & 1 & -b_{n-1}
\end{pmatrix}
\end{equation}
A direct proof by induction and cofactor expansion will show you that the characteristic polynomial (and hence minimal polynomial) of $A$ is given by
\begin{equation}
f(t) = t^n + \sum_{i=0}^{n-1}b_i t^i.
\end{equation}
(assuming you defined characteristic polynomial as $\det (tI-A)$, otherwise there will be an overall sign of $(-1)^n$).
In the spirit of this question, you should read up about companion matrices of polynomials
Comment: A reference among others : https://math.stackexchange.com/q/10216


What is the expected value of $\bar\beta=(Y_4-Y_1)/(X_4-X_1)$ under GM assumptions?

Question: In other words, is $\bar\beta$ an unbiased estimator? Suppose that original regression is specified as following $Y_i=\beta_1 X_i+u_i$.
Also, I would be happy to learn whether the existence of the constant term in the regression would have changed the answer. Thanks.
Comment: Is this for some class, study textbook exercise or similar?  What does "GM" stand for in this context?
Comment: Is this a homework problem? If, so please mark this as self-study and indicate what you have tried so far.
Comment: If you only had two points for a linear regression, then clearly you would draw the line joining them, and the Gauss-Markov theorem would tell you that the line was the  best linear unbiased estimator of the coefficients, including the slope.  This would stop be the *best* if there are more points which you have ignored, but would still be *unbiased*.
Answer: I'm assuming in your notation that the $u_i$ is the error term of the $i$th observation.  In that case, under the Gauss-Markov model:
\begin{eqnarray*}
E\left[Y_{i}\right] & = & E\left[\beta_{1}X_{i}+u_{i}\right]\\
 & = & \beta_{1}X_{i}+E[u_{i}]\,(\mbox{Since}\,X_{i}\mbox{ is a constant})\\
 & = & \beta_{1}X_{i}+0\\
 & = & \beta_{1}X_{i}
\end{eqnarray*}
So,
\begin{eqnarray*}
E\left[\bar{\beta}\right] & = & E\left[\frac{Y_{4}-Y_{1}}{X_{4}-X_{1}}\right]\\
 & = & \left(\frac{1}{X_{4}-X_{1}}\right)E\left[Y_{4}-Y_{1}\right]\\
 & = & \left(\frac{1}{X_{4}-X_{1}}\right)\left(E\left[Y_{4}\right]-E\left[Y_{1}\right]\right)\\
 & = & \left(\frac{1}{X_{4}-X_{1}}\right)\left(\beta_{1}X_{4}-\beta_{1}X_{1}\right)\\
 & = & \left(\frac{\beta_{1}}{X_{4}-X_{1}}\right)\left(X_{4}-X_{1}\right)\\
 & = & \beta_{1}
\end{eqnarray*}
Note that the Gauss-Markov model says nothing about normality (I just figured I'd make this comment since you tagged "Normal-distribution").
Comment: Now, let's apply Rao-Blackwell to that...
Answer: This is not a question from an assignment or a text book and GM stands for Gauss-Markov assumptions.
Anyway, here is the solution I come up with. So, maybe you can at least tell me whether it is correct or not.
\begin{align}
\bar \beta &= \frac{(\beta_1 X_4-u_4)-(\beta_1 X_1-u_1)}{ X_4-X_1}  \\[7pt]
\bar \beta &= \frac{\beta_1(X_4-X_1)+( u_4-u_1)}{ X_4-X_1}  \\[7pt]
\bar \beta &= \beta_1+\frac{( u_4-u_1)}{ X_4-X_1}  \\[7pt]
E(\bar \beta) &= E\Bigg(\beta_1+\frac{( u_4-u_1)}{ X_4-X_1}\Bigg)  \\[7pt]
E(\bar \beta) &= \beta_1+E\Bigg(\frac{( u_4-u_1)}{ X_4-X_1}\Bigg)  \\[7pt]
E(u_i) &= 0
\end{align}
(this is where gauss-markov assumption "kicks in" as I believe)
$E(\bar \beta)=\beta_1$; therefore $E(\bar \beta)$ turns out to be an unbiased estimator.
Comment: This is not correct.  I'm not even sure what $\beta$ is in your solution.  See my solution provided above for complete details.


Drupal 7 Clean URLs and Image Upload

Question: I am currently having problems with uploading images and using clean urls on my website. File permissions are working correctly.
When I upload an image to an article page and then I click refresh to view the page, the image doesn't appear. I check for the image url and an example url would be:
http://example.com/sites/default/files/styles/large/public/field/image/01.jpg
but the image would appear if I modify the url on the address bar to:
http://example.com/?q=sites/default/files/styles/large/public/field/image/01.jpg
I have tried:
turning on and off clean urls (sometimes the images appear, but then they disappear again)
modifying rewrite rules in the the .htaccess file
folder permissions
This happened when I uploaded the site to a server and the url would change, but before uploading the site to the servers and testing it on my computer, the url doesn't change. I am currently thinking that it has something to do with some of the rewrite rules in the .htaccess file.
Comment: Does it work with vanilla Drupal `.htaccess`?
Comment: Slang term, sorry. It means unmodified, just the way it is when you download fresh copy.
Comment: Yes, I did a clean install (7.22) on my laptop and then I  used backup and migrate to load/create the mysql database to the server and the installation
Comment: Actually, I had to remove some settings because my server doesn't allow it, I had to remove both options directives and the entire mod_php5.c block.
Answer: Even if Clean URLs are successfully enabled at install-time, if you have a dedicated server you may still want to follow the steps (below) to enable the more efficient httpd.conf rewrite method for clean URLs. If you choose to do that, you might want to turn off Clean URLs while you are working on the server.
    Server configuration for Clean URLs on a dedicated server, with httpd.conf
Answer: Uncommenting the RewriteBase at line 110 in .htaccess file of root solved the problem for me.
Depending on your installation folder, you might uncomment and modify line 106 instead of 110.
I found that solution, in a drupal.org article and in case that doesn't solve your problem there are alternative solutions there as well.
Answer: I went on another direction with my photos but I figured it out anyway. All I had to do was to delete the .htaccess file in the site/default/files.
Comment: Great! You figured it out yourself.

Drupal 7 Clean URLs and Image Upload


Facebook OG Meta Tags Not Working

Question: So we've debuted our new website: http://www.lumativ.com and for some reason, I can't get the Open Graph tags to allow our social networking links to show up properly on Facebook. I have two questions:
Does it matter that the site redirects to https://?
Is there anything wrong with these OG tags?
<code><meta property="og:title" content="LUMATIV - E5 Snapback">
<meta property="og:type" content="website">
<meta property="og:url" content="https://www.lumativ.com/">
<meta property="og:image" content="https://www.lumativ.com/images/2014/promo/lumativ-2014-facebook.jpg">
<meta property="og:site_name" content="LUMATIV - E5 Snapback">
</code>
Thank you in advance. I've reviewed other posts on this and read through the docs on Open Graph and nothing is taking.
Comment: This is what Facebook sees: https://developers.facebook.com/tools/debug/og/echo?q=https%3A%2F%2Fwww.lumativ.com%2F and as you can see you have a body tag in the top that makes facebook not see your meta tags.
Comment: You are a miracle! thank You!
Answer: My bad. I had an error in my php that was throwing an "unseen" error into my HTML. WizKid got it!

Facebook OG Meta Tags Not Working


PHP Notice: Use of undefined constant php - assumed 'php'

Question: Was just editing a site I'm working on to include the subscription form in the footer.php rather than just the homepage. I made the changes on the local server then moved it to my live environment (dev sub-folder). I didn't see any errors on my localhost, but on the dev site it is showing the following error:

PHP Notice:  Use of undefined constant php - assumed 'php' in /home/website-name/public_html/uk-en/dev/wp-content/themes/theme-name/footer.php on line 1

The only thing on line 1 is the opening php tag, see code below from the footer.php file
<?php?>

SIGN UP TO OUR EMAIL NEWSLETTER FOR NEWS, OFFERS & EXCITING COMPETITIONS.

           <?php echo do_shortcode( '[contact-form-7 id="4563" title="Newsletter"]' ); ?>

            <img src="<?=site_url();?>/wp-content/uploads/2017/05/payment_cards.png" alt="payments cards"/>

        <?php /* Widgetized sidebar */ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('footerwidget') ) : ?><?php endif; ?>

<?php wp_footer(); ?>
<?php /* if(get_the_ID() == 5) { ?>

<?php } */ ?>

<?php /*?><?php */?>

I could turn off notice display however I would like to get the right solution rather than a cover up
Comment: I don't think the file you're showing above matches reality. Can you actually download the file from the live site and compare it to your local one?
Comment: i've changed the theme name to theme-name and changed the links to hide the identity of the site as it is a client site but besides that everything has been copied exactly from the file. the localhost footer.php file is the same as on the live site because that is what i uploaded
Comment: Are you totally sure of that? Sometimes files get altered by web hosts **after** they're uploaded
Comment: yes you were right. I did not know that. I have updated the code in the question as it is on the live site. I assumed the issue was with the opening php tag closing on the same line, so I have changed the first line to  and it seems to have fixed the problem, is the best way around it?
Comment: @Areej yes that should fix. Or else you can remove the tag altogether if it has no use.
Answer: Basic syntax of php opening tag is <?php[whitespace] not just <?php, see here http://php.net/manual/en/language.basic-syntax.phptags.php#118827.
So the right syntax would be adding a white space in between php opening and closing tag <?php ?>


Java inheritance with methods

Question: I have a question about the following MC problem:

Given the following declarations.
public class Vechicle {
 public void test(Car x, SportsCar y) {}
}

public class Car extends Vechicle {
}
public class SportsCar extends Car {
}

Also consider the following code that appears in a different class.

Vechicle v = new Vechicle();
Car c = new Car();
SportsCar sporty = new SportsCar();

Which of the following is a correct call to test? (A)
v.test(sporty,v); (B) sporty.test(c,c); (C) v.test(sporty,c); (D)
sporty.test(sporty,v); (E) c.test(sporty,sporty);

Why is the answer here E? Wouldn't the first input "x" have to be an instance of "Car", not its subclass "SportsCar"?
If subclass objects are interchangeable in function definitions, why would the other answers be incorrect?
Comment: Are you saying a sports car is not a car? But: is a car a sports car?
Comment: There is a typo: Vechicle  -> Vehicle. Also the relationship of the classes seems to be wrong. The parent class `Vechicle` shouldn't know about the child classes and this would be a better and more generic method declaration: `public void test(Vehicle x, Vehicle y)`
Comment: The question does make sense, my comment is about a typo and a poor design.
Comment: What is "MC" mentioned if first sentence?
Comment: @Boris I'm not sure what you mean - does the question not make sense as is?
Answer: Every Car object is a Vehicle. And every SportsCar object is a Car as well as a Vehicle.
But… not every Car object is a SportsCar, nor is every Vehicle object a SportsCar.
Since the first parameter of the test method requires a Vehicle, using a SportsCar object as that argument is correct and legitimate.

Let's run through the answers.

(A) v.test(sporty,v);

Wrong. The second argument must be a SportsCar. Not every Vehicle is a SportsCar.

(B) sporty.test(c,c);

Wrong. The second argument must be a SportsCar. Not every Car is a SportsCar.

(C) v.test(sporty,c);

Wrong. The second argument must be a SportsCar. Not every Car is a SportsCar.

(D) sporty.test(sporty,v);

Wrong. The second argument must be a SportsCar. Not every Vehicle is a SportsCar.

(E) c.test(sporty,sporty);

Correct. The first argument must be a Car, and every SportsCar object is a Car.

As commented by Boris, the semantics of the class design here is screwy. But this is supposed to be a simple exercise in the mechanics of inheritance, not realistic code.

Java inheritance with methods


Prove that $b^r =\sup B(r)$ when $r$ is rational.

Question: The information provided for this problem is:
Fix $b>1$ and suppose we only have defined $b^r$ where $r$ is rational by $b^r=(b^m)^{1/n}$ whenever $r=m/n$.
The actual problem states: If $x$ is real, define $B(x)$ to be the set of all numbers $b^t$ where $t$ is rational and $t$ is less than or equal to $x$. Prove that $b^r=\sup B(r)$ when $r$ is rational.
Comment: What else do you know? If you know that $x\mapsto b^x$ is an increasing function, then it's just $\sup (\mathbb{Q}\cap (0,b^r])$.
Answer: Write $t=\frac{p}{q}$ and $r=\frac{m}{n}$, where $m,n,p,q\in\mathbb{Z}$, and $n,q>0$.
If we can show that $t\leq r\implies b^t\leq b^r$ ($t,r\in\mathbb{Q}$), then $b^r$ will be an upper bound for the set $B(r)$, and it will also be a least upper bound, because $b^r\in B(r)$.
Note that
\begin{align*}
t&\leq r \\
\implies\frac{p}{q}&\leq\frac{m}{n} \\
\implies pn&\leq mq \\
\implies 0&\leq mq-pn
\end{align*}
Consider $b^{mq-pn}$. Since $mq-pn\in\mathbb{Z}_{\geq0}$, it is either 1 (when $mq-pn=0$), or $b$ multiplied by itself $mq-pn$ times (when $mq-pn\geq1$). It follows inductively from the properties of a field that in the latter case:
$$\underbrace{b\cdot b\cdots b}_{mq-pn\text{ times}}>\underbrace{1\cdot1\cdots1}_{mq-pn\text{ times}}=1.$$
Therefore, $b^{mq-pn}\geq1\implies b^{mq}\geq b^{pn}$. Now we want to be able to take the $nq$th root across the inequality, but we need to prove something first:
Lemma: If $c\leq d$, and $x\in \mathbb{Z}_{>0}$, then $c^{1/x}\leq d^{1/x}$.
Proof: Suppose that $c^{1/x}>d^{1/x}$. Then
$$\underbrace{c^{1/x}\cdot c^{1/x}\cdots c^{1/x}}_{x\text{ times}} > \underbrace{d^{1/x}\cdot d^{1/x}\cdots d^{1/x}}_{x\text{ times}}\implies c>d$$
this is a contradiction. So $c^{1/x}\leq d^{1/x}$.
Applying this to our previous inequality, we get:
\begin{align*}
b^{mq}&\geq b^{np} \\
\implies (b^{mq})^{1/(nq)} &\geq (b^{np})^{1/(nq)} \\
\implies b^{m/n} &\geq b^{p/q} \\
\implies b^r &\geq b^t
\end{align*}
as desired.


Sesquilinear Forms: Cauchy-Schwarz

Question: This thread is related: Parallelogram
Given a Hilbert space $\mathcal{H}$.
Consider a quadratic form:
$$q:\mathcal{H}\to\mathbb{C}:\quad q[\lambda\varphi]=|\lambda|^2q[\varphi]$$
Suppose it satisfies:
$$q[\varphi+\psi]+q[\varphi-\psi]=2q[\varphi]+2q[\psi]$$
Define a sesquilinear form:
$$s:\mathcal{H}\times\mathcal{H}\to\mathbb{C}:\quad s(\varphi,\psi):=\frac{1}{4}\sum_{\alpha=0\ldots3}i^\alpha q[\varphi+i^\alpha\psi]$$

Then for positive forms:
  $$q\geq0:\quad|s(\varphi,\psi)|\leq q[\varphi]q[\psi]$$

How can I check this?
Answer: For this, you need only assume $Q$ is real and non-negative on a complex space with
$$
         Q(x+y)+Q(x-y)=2Q(x)+2Q(y),\\
              Q(ix)=Q(x).
$$
Then it is true that $B(x,y)=\frac{1}{4}\sum_{n=0}^{3}i^{n}Q(x+i^{n}y)$ satisfies
$$
           |B(x,y)| \le Q(x)^{1/2}Q(y)^{1/2}.
$$
Therefore $|x|_{Q}=Q(x)^{1/2}$ satisfies the triangle inequality. Then, if $Q(\lambda x)=|\lambda|^{2}Q(x)$ holds for all scalars $\lambda$, it is also true that $B$ is sesquilinear.
Outline

$B(x+x',y)=B(x,y)+B(x',y)$. So $B(\alpha x,y)=\alpha B(x,y)$ for all complex scalars with rational real and imaginary parts.
$4|B(x,y)|=\lim_{n}4B(\alpha_n x,y)= \lim_{n}Q(\alpha_n x + y)-Q(\alpha_n x-y) \le 2Q(x)+2Q(y)$ if $Q(x) \ge 0$ for all $x$.
Use rational positive real scalars to obtain $|B(rx,sy)| \le 1$ and $|B(x,y)| \le Q(x)^{1/2}Q(y)^{1/2}$.
Continuity: $|\lambda B(x,y)-B(\lambda x,y)|=\lim_{n}|B((\lambda_n-\lambda)x,y)|\le\lim_{n}|\lambda_{n}-\lambda|Q(x)^{1/2}Q(y)^{1/2}=0$ if $Q(\alpha x)=|\alpha|^{2}Q(x)$. So $\lambda B(x,y)=B(\lambda x,y)$ for general $\lambda\in\mathbb{C}$. That makes $B$ fully sesquilinear.
Comment: Yes and how can I check Cqauchy-Schwarz: $|B(x,y)|\leq Q(x)^{1/2}Q(y)^{1/2}$
Comment: @Freeze_S I've given you the outline, and will let you fill in the pieces.
Comment: Number '3' is the normalization trick??
Comment: Number '2' restricts to hermitian forms??
Comment: Decomposing arbitrary form into: $s=s_\Re^++s_\Re^-+is_\Im^++is_\Im^-$
Comment: Ok I'm way to tired.. Let me just believe it for now. :)
Comment: @Freeze_S : #1 is general for $B$ coming from a general $Q$. The additivity gives linearity over rational scalars because $B(nx,y)=nB(x,y)$ and $mB(\frac{1}{m}x,y)=B(x,y)$ gives $B(\frac{1}{m}x,y)=\frac{1}{m}B(x,y)$ for positive integers $m$, $n$.  #2 is specific to $Q$ real and non-negative.#3 uses (1) and limits of rationals along with (2) to get the tight Cauchy-Schwarz bound.#4 uses (3) and $Q(\lambda x)=|\lambda|^{2}Q(x)$ to derive continuity. Or instead assume $Q(x) \le C|x|$ for some seminorm $|\cdot|$, which you can see directly. So $Q \ge 0$ bounded is enough.
Comment: Ya I guessed already that taking first positive quadratic forms is necessary to obtain the 'tight' Cauchy-Schwarz. Otherwise one probably obtains a factor 2 or 4 to much that cannot be killed afterwards. Right?
Comment: @Freeze_S : Yes, that's right. But you get Cauchy-Schwarz only having linearity over the rational complex scalars IF $Q \ge 0$. That, however, is not enough to give full linearity over $\mathbb{Q}$. But, $Q(\lambda x)=|\lambda|^{2}Q(x)$ then turns $|x|=Q(x)$ into a full-blow seminorm. And you really only need $Q(x) \le |x|$ for some seminorm $|\cdot|$ with $Q \ge 0$ to also force $Q$ to be a seminorm. Either condition forces continuity over the scalar field and, sesquiinearity for $B$. This stuff is tricky and wrapped up with the axiom of choice.
Comment: Mhh yes. Like measurability and continuity as you mentioned earlier..
Comment: By the way isn't there the hypothesis in ZF: $AC\iff WE\iff Zorn\iff Hamel\iff Baire\stackrel{???}{\iff} UBP\iff OMT\iff CGT\iff Zabreiko$
Comment: @Freeze_S : I'm not sure of all of those. What is Zabreiko?
Comment: See on wiki: [Baire vs. AC](https://en.wikipedia.org/wiki/Baire_category_theorem#Relation_to_the_axiom_of_choice) See on MSE: [Zabreiko](http://math.stackexchange.com/a/138005/79762)
Comment: @Freeze_S : In this case, you end up with additive functions on $\mathbb{R}$, which is to say that $f(x+y)=f(x)+f(y)$ for all $x,y\in\mathbb{R}$. And you want to know if $f$ is linear. $f$ is linear iff it is continuous. $f$ is linear over every set $x\mathbb{Q}=\{ x q : q \in \mathbb{Q}\}$ because $f(xq)=qf(x)$. You can partition $\mathbb{R}\setminus\{0\}$ into sets by the equivalent relation $x \sim y$ iff $x/y \in \mathbb{Q}$. This is very closely related to the classical construction of a non-measurable set. Consequently, if $f$ is meausrable, then it is continuous.

Sesquilinear Forms: Cauchy-Schwarz


Graphical application.config editor?

Question: I am wondering if .net has some sort of inbuilt gui for editing application.config files.
From googling around it seems that they exist but are designed to be run from visual studio.
What I want to do is to allow admins of the software I am writing to be able to customise the application config from within the software at a customers site.
Could someone advise me if this is possible?
At the minute I thinking I will have to wite my own code to parse the config files to generate the Gui.
Comment: Don't know about anything "builtin", but you could roll your own without too much work, couldn't you? Here is a link that might help you: http://www.codeproject.com/Articles/6160/Application-Configuration-Editor-using-the-Propert
Comment: Yeh i assumed I was going to roll my own, but just thought I would check that there wasnt something already out there before I put effort into it :D Cheers
Answer: Create your own form whcih takes application.config values from user and update that in the application.config

Graphical application.config editor?