问:
CMake - Check if a higher level directory exists
I'm new to CMake and I tried to do this in my root CMakeLists.txt :

```<code>set(HAVE_MY_SDK   OFF)

if(IS_DIRECTORY "${PROJECT_SOURCE_DIR}../Libs/A")
    if(EXISTS "${PROJECT_SOURCE_DIR}../Libs/A/CMakeLists.txt")
        set (HAVE_MY_SDK   ON)
    endif()
endif()
</code>```

Currently, CMake is just avoiding the instruction, leaving HAVE_MY_SDK in a OFF status. Is it possible to check an higher level directory with CMake ? Or maybe doing it with an indirect method

答:
I think you're just missing a / after ${PROJECT_SOURCE_DIR}.

Out of completeness here is the code I use for this (note that if (EXISTS ...) needs full paths):

```<code>get_filename_component(_fullpath "${_dir}" REALPATH)
if (EXISTS "${_fullpath}" AND EXISTS "${_fullpath}/CMakeLists.txt")
    ...
</code>```

And here inside my extended add_subdirectory() version (including a "add once guard"):

```<code>function(my_add_subdirectory _dir)
    get_filename_component(_fullpath "${_dir}" REALPATH)
    if (EXISTS "${_fullpath}" AND EXISTS "${_fullpath}/CMakeLists.txt")
        get_property(_included_dirs GLOBAL PROPERTY GlobalAddSubdirectoryOnceIncluded)
        list(FIND _included_dirs "${_fullpath}" _used_index)
        if (${_used_index} EQUAL -1)
            set_property(GLOBAL APPEND PROPERTY GlobalAddSubdirectoryOnceIncluded "${_fullpath}")
            add_subdirectory(${_dir} ${ARGN})
        endif()
    else()
        message(WARNING "my_add_subdirectory: Can't find ${_fullpath}/CMakeLists.txt")
    endif()
endfunction(my_add_subdirectory)
</code>```

Body:
I'm new to CMake and I tried to do this in my root CMakeLists.txt :

set(HAVE_MY_SDK   OFF)

if(IS_DIRECTORY "${PROJECT_SOURCE_DIR}../Libs/A")
    if(EXISTS "${PROJECT_SOURCE_DIR}../Libs/A/CMakeLists.txt")
        set (HAVE_MY_SDK   ON)
    endif()
endif()

Currently, CMake is just avoiding the instruction, leaving HAVE_MY_SDK in a OFF status. Is it possible to check an higher level directory with CMake ? Or maybe doing it with an indirect method

Body:
I think you're just missing a / after ${PROJECT_SOURCE_DIR}.

Out of completeness here is the code I use for this (note that if (EXISTS ...) needs full paths):

get_filename_component(_fullpath "${_dir}" REALPATH)
if (EXISTS "${_fullpath}" AND EXISTS "${_fullpath}/CMakeLists.txt")
    ...

And here inside my extended add_subdirectory() version (including a "add once guard"):

function(my_add_subdirectory _dir)
    get_filename_component(_fullpath "${_dir}" REALPATH)
    if (EXISTS "${_fullpath}" AND EXISTS "${_fullpath}/CMakeLists.txt")
        get_property(_included_dirs GLOBAL PROPERTY GlobalAddSubdirectoryOnceIncluded)
        list(FIND _included_dirs "${_fullpath}" _used_index)
        if (${_used_index} EQUAL -1)
            set_property(GLOBAL APPEND PROPERTY GlobalAddSubdirectoryOnceIncluded "${_fullpath}")
            add_subdirectory(${_dir} ${ARGN})
        endif()
    else()
        message(WARNING "my_add_subdirectory: Can't find ${_fullpath}/CMakeLists.txt")
    endif()
endfunction(my_add_subdirectory)


来源: stackexchange

问:
Code golf: combining multiple sorted lists into a single sorted list
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

```<code>input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)
</code>```

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

```<code>sorted(sum(lists,[])) # cheating: out of bounds!
</code>```

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

答:
VB is usually not the language of choice for code golf, but here goes anyway.

The setup -

```<code>
        Dim m1 As List(Of Integer) = New List(Of Integer)
        Dim m2 As List(Of Integer) = New List(Of Integer)
        Dim m3 As List(Of Integer) = New List(Of Integer)
        Dim m4 As List(Of Integer) = New List(Of Integer)

        m1.Add(1)
        m1.Add(2)
        m1.Add(3)

        m2.Add(4)
        m2.Add(5)
        m2.Add(6)

        m3.Add(7)
        m3.Add(8)
        m3.Add(9)

        Dim m5 As List(Of List(Of Integer)) = New List(Of List(Of Integer))
        m5.Add(m1)
        m5.Add(m2)
        m5.Add(m3)
</code>```

An attempt in VB.NET (without sort)

```<code>        While m5.Count > 0
            Dim idx As Integer = 0
            Dim min As Integer = Integer.MaxValue
            For k As Integer = 0 To m5.Count - 1
                If m5(k)(0) < min Then min = m5(k)(0) : idx = k
            Next
            m4.Add(min) : m5(idx).RemoveAt(0)
            If m5(idx).Count = 0 Then m5.RemoveAt(idx)
        End While
</code>```

Another VB.NET attempt (with an allowed sort)

```<code>
    Private Function Comp(ByVal l1 As List(Of Integer), ByVal l2 As List(Of Integer)) As Integer
        Return l1(0).CompareTo(l2(0))
    End Function
    .
    .
    .
    While m5.Count > 0
        m5.Sort(AddressOf Comp)
        m4.Add(m5(0)(0)) : m5(0).RemoveAt(0)
        If m5(0).Count = 0 Then m5.RemoveAt(0)
    End While
</code>```

The entire program -

```<code>        Dim rand As New Random
        Dim m1 As List(Of Integer) = New List(Of Integer)
        Dim m2 As List(Of Integer) = New List(Of Integer)
        Dim m3 As List(Of Integer) = New List(Of Integer)
        Dim m4 As List(Of Integer) = New List(Of Integer)
        Dim m5 As List(Of List(Of Integer)) = New List(Of List(Of Integer))
        m5.Add(m1)
        m5.Add(m2)
        m5.Add(m3)

        For Each d As List(Of Integer) In m5
            For i As Integer = 0 To 100000
                d.Add(rand.Next())
            Next
            d.Sort()
        Next

        Dim sw As New Stopwatch
        sw.Start()
        While m5.Count > 0
            Dim idx As Integer = 0
            Dim min As Integer = Integer.MaxValue
            For k As Integer = 0 To m5.Count - 1
                If m5(k)(0) < min Then min = m5(k)(0) : idx = k
            Next
            m4.Add(min) : m5(idx).RemoveAt(0)
            If m5(idx).Count = 0 Then m5.RemoveAt(idx)
        End While
        sw.Stop()

        'Dim sw As New Stopwatch
        'sw.Start()
        'While m5.Count > 0
        '    m5.Sort(AddressOf Comp)
        '    m4.Add(m5(0)(0)) : m5(0).RemoveAt(0)
        '    If m5(0).Count = 0 Then m5.RemoveAt(0)
        'End While
        'sw.Stop()

        Console.WriteLine(sw.Elapsed)
        Console.ReadLine()
</code>```

OwnerDisplayName: jamesbrady

ContentLicense: CC BY-SA 2.5

Body:
Implement an algorithm to merge an arbitrary number of sorted lists into one sorted list. The aim is to create the smallest working programme, in whatever language you like.

For example:

input:  ((1, 4, 7), (2, 5, 8), (3, 6, 9))
output: (1, 2, 3, 4, 5, 6, 7, 8, 9)

input:  ((1, 10), (), (2, 5, 6, 7))
output: (1, 2, 5, 6, 7, 10)

Note: solutions which concatenate the input lists then use a language-provided sort function are not in-keeping with the spirit of golf, and will not be accepted:

sorted(sum(lists,[])) # cheating: out of bounds!

Apart from anything else, your algorithm should be (but doesn't have to be) a lot faster!

Clearly state the language, any foibles and the character count. Only include meaningful characters in the count, but feel free to add whitespace to the code for artistic / readability purposes.

To keep things tidy, suggest improvement in comments or by editing answers where appropriate, rather than creating a new answer for each "revision".

EDIT: if I was submitting this question again, I would expand on the "no language provided sort" rule to be "don't concatenate all the lists then sort the result". Existing entries which do concatenate-then-sort are actually very interesting and compact, so I won't retro-actively introduce a rule they break, but feel free to work to the more restrictive spec in new submissions.

Inspired by Combining two sorted lists in Python

LastEditorDisplayName: Alabaster Codify

Body:
VB is usually not the language of choice for code golf, but here goes anyway.

The setup -

        Dim m1 As List(Of Integer) = New List(Of Integer)
        Dim m2 As List(Of Integer) = New List(Of Integer)
        Dim m3 As List(Of Integer) = New List(Of Integer)
        Dim m4 As List(Of Integer) = New List(Of Integer)

        m1.Add(1)
        m1.Add(2)
        m1.Add(3)

        m2.Add(4)
        m2.Add(5)
        m2.Add(6)

        m3.Add(7)
        m3.Add(8)
        m3.Add(9)

        Dim m5 As List(Of List(Of Integer)) = New List(Of List(Of Integer))
        m5.Add(m1)
        m5.Add(m2)
        m5.Add(m3)

An attempt in VB.NET (without sort)

        While m5.Count > 0
            Dim idx As Integer = 0
            Dim min As Integer = Integer.MaxValue
            For k As Integer = 0 To m5.Count - 1
                If m5(k)(0) < min Then min = m5(k)(0) : idx = k
            Next
            m4.Add(min) : m5(idx).RemoveAt(0)
            If m5(idx).Count = 0 Then m5.RemoveAt(idx)
        End While

Another VB.NET attempt (with an allowed sort)

    Private Function Comp(ByVal l1 As List(Of Integer), ByVal l2 As List(Of Integer)) As Integer
        Return l1(0).CompareTo(l2(0))
    End Function
    .
    .
    .
    While m5.Count > 0
        m5.Sort(AddressOf Comp)
        m4.Add(m5(0)(0)) : m5(0).RemoveAt(0)
        If m5(0).Count = 0 Then m5.RemoveAt(0)
    End While

The entire program -

        Dim rand As New Random
        Dim m1 As List(Of Integer) = New List(Of Integer)
        Dim m2 As List(Of Integer) = New List(Of Integer)
        Dim m3 As List(Of Integer) = New List(Of Integer)
        Dim m4 As List(Of Integer) = New List(Of Integer)
        Dim m5 As List(Of List(Of Integer)) = New List(Of List(Of Integer))
        m5.Add(m1)
        m5.Add(m2)
        m5.Add(m3)

        For Each d As List(Of Integer) In m5
            For i As Integer = 0 To 100000
                d.Add(rand.Next())
            Next
            d.Sort()
        Next

        Dim sw As New Stopwatch
        sw.Start()
        While m5.Count > 0
            Dim idx As Integer = 0
            Dim min As Integer = Integer.MaxValue
            For k As Integer = 0 To m5.Count - 1
                If m5(k)(0) < min Then min = m5(k)(0) : idx = k
            Next
            m4.Add(min) : m5(idx).RemoveAt(0)
            If m5(idx).Count = 0 Then m5.RemoveAt(idx)
        End While
        sw.Stop()

        'Dim sw As New Stopwatch
        'sw.Start()
        'While m5.Count > 0
        '    m5.Sort(AddressOf Comp)
        '    m4.Add(m5(0)(0)) : m5(0).RemoveAt(0)
        '    If m5(0).Count = 0 Then m5.RemoveAt(0)
        'End While
        'sw.Stop()

        Console.WriteLine(sw.Elapsed)
        Console.ReadLine()


问:
wordpress ubermenu warnings on nginx server
I have a site on my aws server with PHP 7.1 and nginx as server for php. Wordpress latest version is running. Many time about after every 20 minutes I saw 502 error while accessing the site.
Nginx server logs shows the following warnings.

```<code>*674241 FastCGI sent in stderr: "m_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'submenu_type_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 371
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
</code>```

After simple googling I got this file: http://sevenspark.com/docs/ubermenu-3/faqs/php-7-1-warnings after which error still the same.

Please provide some useful solution, thanks

答:
I just commented out that initialisation lines of code </p>

```<code>// $this->settings['item_display_calc'] = '';
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a site on my aws server with PHP 7.1 and nginx as server for php. Wordpress latest version is running. Many time about after every 20 minutes I saw 502 error while accessing the site.
Nginx server logs shows the following warnings.

*674241 FastCGI sent in stderr: "m_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'submenu_type_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 371
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Cannot assign an empty string to a string offset in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 673
PHP message: PHP Warning:  Illegal string offset 'item_display_calc' in wp-content/plugins/ubermenu/includes/menuitems/UberMenuItem.class.php on line 563

After simple googling I got this file: http://sevenspark.com/docs/ubermenu-3/faqs/php-7-1-warnings after which error still the same.

Please provide some useful solution, thanks

Body:
I just commented out that initialisation lines of code

// $this->settings['item_display_calc'] = '';


问:
OAuth flow for Google Drive App
Background: I have created and installed a Google Drive App. It sits in my https://apps.google.com/u/1/user/hub as seen in the image below.

I am signed into my Google account to be on this page. When I click on one of these installed apps the behaviour is very inconsistent.

If I am signed into multiple google accounts in the browser, it asks me to sign-in with google when I arrive on the app but then sometimes it just signs me in automatically.

If I have already signed into the app separately from Google Drive, then it uses the existing login profile on the app.

If I have only signed into one google account on my browser it sometimes signs me in to this account on the app and sometimes does not.

I have scoured far and wide for documentation and all I have found is this snippet from https://developers.google.com/drive/v3/web/practices:

Treat all Create New and Open with events like potential logins. Some
  users may have multiple accounts. If the user ID in the state
  parameter does not match the current session, you may need to end the
  current session for your app and log in as the requested user.

But this snippet doesn't mention if any OAuth login flow is done automatically when you arrive on the app.

The question: Does anyone know how the OAuth flow logic actually works when you open an installed app from Google Drive, either by clicking on the app (as in the picture above) or by opening/creating a file in Google Drive with the app?

My desired outcome is that the app is always logged in with the account that the user is using in Google Drive when they clicks the link, without having to sign-in with Google again on the app, or needing to switch account.

答: Check the About Authorization for Drive API. It describes the OAuth flow. Or you can just opt to use one gmail account in your browser to avoid confusion altogether. </p>

Title: OAuth flow for Google Drive App


问:
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'
After updating the Android Studio, I am getting error like

No resource found that matches the given name: attr
  'android:keyboardNavigationCluster'

What should I do?

答:
It is a major issue you just need to do this

In app level build.gradle file use

```<code>complieSdkVersion 26
buildToolVersion "26.0.1"
</code>```

This will resolve your error.

Body:
It is a major issue you just need to do this

In app level build.gradle file use

complieSdkVersion 26
buildToolVersion "26.0.1"

This will resolve your error.


问:
SQL Count total of addresses
Here is my data

```<code>Vehicle    | Street       | Number | Postcode
Car          Fakestreet      3       0010NK
Motorbike    Fakestreet      3       0010NK
Car          Fakestreet      4       0010NK
Car          Fakestreet      1       0010NK
Companycar   Fakestreet      1       0010NK
</code>```

I want to count unique adresses per postcode so this is want I want to see:

```<code>Postcode | Total_adresses
0010NK   | 3
</code>```

I thought this must be a simple query so I have this:

```<code>SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode, Street, Number
</code>```

But I get this result:

```<code>Postcode | total_adresses
0010NK   | 2
0010NK   | 2
0010NK   | 1
</code>```

I can't get my head around why it doesn't give me the desired result. Any ideas why?

答:
Have a derived table to return the unique addresses. Then GROUP BY its result:</p>

```<code>select Postcode, count(*)
from
(
    SELECT DISTINCT Street, Number, Postcode
    FROM my_database
) dt
group by Postcode
</code>```

Title: SQL Count total of addresses

Body:
Here is my data

Vehicle    | Street       | Number | Postcode
Car          Fakestreet      3       0010NK
Motorbike    Fakestreet      3       0010NK
Car          Fakestreet      4       0010NK
Car          Fakestreet      1       0010NK
Companycar   Fakestreet      1       0010NK

I want to count unique adresses per postcode so this is want I want to see:

Postcode | Total_adresses
0010NK   | 3

I thought this must be a simple query so I have this:

SELECT Postcode, COUNT(*) AS total_adresses
FROM my_database
WHERE Postcode = '0010NK'
GROUP BY Postcode, Street, Number

But I get this result:

Postcode | total_adresses
0010NK   | 2
0010NK   | 2
0010NK   | 1

I can't get my head around why it doesn't give me the desired result. Any ideas why?

Body:
Have a derived table to return the unique addresses. Then GROUP BY its result:

select Postcode, count(*)
from
(
    SELECT DISTINCT Street, Number, Postcode
    FROM my_database
) dt
group by Postcode


问:
How do I make a dotted/dashed line in Android?
I'm trying to make a dotted line. I'm using this right now for a solid line:

```<code>LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );
</code>```

I need something like this, but dotted instead of solid. I'd like to avoid making hundreds of layouts alternating between a transparent layout and solid layout.

答:
If you are looking for a vertical line  use this drawable.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-8dp"
        android:bottom="-8dp"
        android:left="-8dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke
                android:width="4dp"
                android:color="#ffffff"
                android:dashGap="4dp"
                android:dashWidth="4dp"/>
        </shape>
    </item>
</layer-list>
</code>```

The negative top bottom and left values remove the unwanted sides of the shape leaving a single dashed line.

Use it in a view like so.

```<code><View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />
</code>```

Body:
I'm trying to make a dotted line. I'm using this right now for a solid line:

LinearLayout divider = new LinearLayout( this );
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, 2 );
divider.setLayoutParams( params );
divider.setBackgroundColor( getResources().getColor( R.color.grey ) );

I need something like this, but dotted instead of solid. I'd like to avoid making hundreds of layouts alternating between a transparent layout and solid layout.

Body:
If you are looking for a vertical line  use this drawable.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:top="-8dp"
        android:bottom="-8dp"
        android:left="-8dp">
        <shape>
            <solid android:color="@android:color/transparent"/>
            <stroke
                android:width="4dp"
                android:color="#ffffff"
                android:dashGap="4dp"
                android:dashWidth="4dp"/>
        </shape>
    </item>
</layer-list>

The negative top bottom and left values remove the unwanted sides of the shape leaving a single dashed line.

Use it in a view like so.

<View
android:layout_width="4dp"
android:layout_height="match_parent"
android:background="@drawable/dash_line_vertical"
android:layerType="software" />

ContentLicense: CC BY-SA 4.0


问:
Merge two datasets in Python
I have two sets of x-y data, whose x values should be merged. To illustrate, the first set looks something like this:

```<code>0.5;3.4
0.8;3.8
0.9;1.2
1.3;1.1
1.9;2.3
</code>```

And the second set like this:

```<code>0.3;-0.2
0.8;-0.9
1.0;0.1
1.5;1.2
1.6;6.3
</code>```

The data is in two separate csv files. I would like to merge both files into one, so that the x values are in order, and the y values appear in two columns with their (linearly) interpolated values (y1 and y2) completed. The second column contains the y values of the first dataset (plus interpolated values) and the third column the y values of the second dataset.

```<code>0.3;y1;-0.2
0.5;3.4;y2
0.8;3.8;-0.9
0.9;1.2;y2
1.0;y1;0.1
1.3;1.1;y2
1.5;y1;1.2
1.6;y1;6.3
1.9;2.3;y2
</code>```

My only idea so far would be to read the data into numpy arrays, join them together, sort the values and calculate the average of preceding and following values, in case the value is empty.

Is there a more elegant way to do this in Python?

Edit: Here is my attempt. It works and delivers the result I imagined, although the script is quite long.

```<code>#-*- coding: utf-8 -*-

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import csv

# Read data files and turn them into numpy array for further processing
def read_datafile(file_name):
    data = np.loadtxt(file_name, delimiter=";")
    return data

data1 = read_datafile("testcsv1.csv")
data2 = read_datafile("testcsv2.csv")

# Add empty column at the appropriate position
emptycol1 = np.empty((len(data1), 3))
emptycol1[:] = np.nan
emptycol2 = np.empty((len(data2), 3))
emptycol2[:] = np.nan
emptycol1[:,:-1] = data1
emptycol2[:,[0, 2]] = data2

# Merge and sort the data sets. Create empty array to add final results
merged_temp = np.concatenate((emptycol1, emptycol2))
merged_temp = np.array(sorted(merged_temp, key = lambda x: float(x[0])))
merged = np.empty((1, 3))

# Check for entries where the x values already match. Merge those into one row
i = 0
while i < len(merged_temp)-1:
    if merged_temp[i, 0] == merged_temp[i+1, 0]:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i+1, 2]])
        merged = np.vstack((merged, newrow))
        i += 2
    else:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i, 2]])
        merged = np.vstack((merged, newrow))
        i += 1

# Check for so far undefined values (gaps in the data). Interpolate between them (linearly)
for i in range(len(merged)-1):
    # First y column
    if np.isnan(merged[i, 1]) == True:
        # If only one value is missing (maybe not necessary to separate this case)
        if (np.isnan(merged[i-1, 1]) == False) and (np.isnan(merged[i+1, 1]) == False):
            merged[i, 1] = (merged[i-1, 1] + merged[i+1, 1])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 1]) == True:
            l = 0
            while (np.isnan(merged[i+l, 1]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 1], merged[i+l, 1]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 1] = f(k)
    # Second y column
    if np.isnan(merged[i, 2]) == True:
        # If only one value is missing
        if (np.isnan(merged[i-1, 2]) == False) and (np.isnan(merged[i+1, 2]) == False):
            merged[i, 2] = (merged[i-1, 2] + merged[i+1, 2])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 2]) == True:
            l = 0
            while (np.isnan(merged[i+l, 2]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 2], merged[i+l, 2]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 2] = f(k)

# Remove lines which still have "nan" values (beginning and end). This could be prevented by an extrapolation
merged = merged[~np.isnan(merged).any(axis=1)]
merged = np.delete(merged, (0), axis=0)

# Write table to new csv file in the same directory
with open("testcsv_merged.csv", "w") as mergedfile:
    writer = csv.writer(mergedfile)
    [writer.writerow(r) for r in merged]
</code>```

答:
I would use pandas for this type of processing:

```<code>import pandas as pd
#I assumed you have no headers in the data files
df1 = pd.read_csv('./dataset1.txt',sep=';',header=None)
df2 = pd.read_csv('./dataset2.txt',sep=';',header=None)
#Join the datasets using full outer join on the first column in both datasets
df_merged = df1.merge(df2, on=0, how='outer')
#Fill the nulls with the desirable values in this case the average of the column
df_merged['1_x'].fillna(df_merged['1_x'].mean(),inplace=True)
df_merged['1_y'].fillna(df_merged['1_y'].mean(),inplace=True)
</code>```

Output:

```<code>print(df_merged)
    0   1_x 1_y
0   0.5 3.4 y2
1   0.8 3.8 -0.9
2   0.9 1.2 y2
3   1.3 1.1 y2
4   1.9 2.3 y2
5   0.3 y1  -0.2
6   1.0 y1  0.1
7   1.5 y1  1.2
8   1.6 y1  6.3
</code>```

You can change the column names easily:

```<code>df_merged.columns = ['col1','col2','col3']
</code>```

You can also sort values easily using sort_values method:

```<code>df_merged.sort_values('col1')
</code>```

Finally, you can convert this final DataFrame into a numpy array easily using:

```<code>import numpy as np
np.array(df_merged)
</code>```

Title: Merge two datasets in Python

Body:
I have two sets of x-y data, whose x values should be merged. To illustrate, the first set looks something like this:

0.5;3.4
0.8;3.8
0.9;1.2
1.3;1.1
1.9;2.3

And the second set like this:

0.3;-0.2
0.8;-0.9
1.0;0.1
1.5;1.2
1.6;6.3

The data is in two separate csv files. I would like to merge both files into one, so that the x values are in order, and the y values appear in two columns with their (linearly) interpolated values (y1 and y2) completed. The second column contains the y values of the first dataset (plus interpolated values) and the third column the y values of the second dataset.

0.3;y1;-0.2
0.5;3.4;y2
0.8;3.8;-0.9
0.9;1.2;y2
1.0;y1;0.1
1.3;1.1;y2
1.5;y1;1.2
1.6;y1;6.3
1.9;2.3;y2

My only idea so far would be to read the data into numpy arrays, join them together, sort the values and calculate the average of preceding and following values, in case the value is empty.

Is there a more elegant way to do this in Python?

Edit: Here is my attempt. It works and delivers the result I imagined, although the script is quite long.

#-*- coding: utf-8 -*-

import numpy as np
from matplotlib import pyplot as plt
from scipy.interpolate import interp1d
import csv

# Read data files and turn them into numpy array for further processing
def read_datafile(file_name):
    data = np.loadtxt(file_name, delimiter=";")
    return data

data1 = read_datafile("testcsv1.csv")
data2 = read_datafile("testcsv2.csv")

# Add empty column at the appropriate position
emptycol1 = np.empty((len(data1), 3))
emptycol1[:] = np.nan
emptycol2 = np.empty((len(data2), 3))
emptycol2[:] = np.nan
emptycol1[:,:-1] = data1
emptycol2[:,[0, 2]] = data2

# Merge and sort the data sets. Create empty array to add final results
merged_temp = np.concatenate((emptycol1, emptycol2))
merged_temp = np.array(sorted(merged_temp, key = lambda x: float(x[0])))
merged = np.empty((1, 3))

# Check for entries where the x values already match. Merge those into one row
i = 0
while i < len(merged_temp)-1:
    if merged_temp[i, 0] == merged_temp[i+1, 0]:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i+1, 2]])
        merged = np.vstack((merged, newrow))
        i += 2
    else:
        newrow = np.array([merged_temp[i, 0], merged_temp[i, 1], merged_temp[i, 2]])
        merged = np.vstack((merged, newrow))
        i += 1

# Check for so far undefined values (gaps in the data). Interpolate between them (linearly)
for i in range(len(merged)-1):
    # First y column
    if np.isnan(merged[i, 1]) == True:
        # If only one value is missing (maybe not necessary to separate this case)
        if (np.isnan(merged[i-1, 1]) == False) and (np.isnan(merged[i+1, 1]) == False):
            merged[i, 1] = (merged[i-1, 1] + merged[i+1, 1])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 1]) == True:
            l = 0
            while (np.isnan(merged[i+l, 1]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 1], merged[i+l, 1]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 1] = f(k)
    # Second y column
    if np.isnan(merged[i, 2]) == True:
        # If only one value is missing
        if (np.isnan(merged[i-1, 2]) == False) and (np.isnan(merged[i+1, 2]) == False):
            merged[i, 2] = (merged[i-1, 2] + merged[i+1, 2])/2
        # If two or more values are missing
        elif np.isnan(merged[i, 2]) == True:
            l = 0
            while (np.isnan(merged[i+l, 2]) == True) and (i+l != len(merged)-1):
                l += 1
            x1 = np.array([i-1, i+l])                       # endpoints
            x = np.linspace(i, i+l-1, l, endpoint=True)     # missing points
            y = np.array([merged[i-1, 2], merged[i+l, 2]])  # values at endpoints
            f = interp1d(x1, y)                             # linear interpolation
            for k in x:
                merged[k, 2] = f(k)

# Remove lines which still have "nan" values (beginning and end). This could be prevented by an extrapolation
merged = merged[~np.isnan(merged).any(axis=1)]
merged = np.delete(merged, (0), axis=0)

# Write table to new csv file in the same directory
with open("testcsv_merged.csv", "w") as mergedfile:
    writer = csv.writer(mergedfile)
    [writer.writerow(r) for r in merged]

Body:
I would use pandas for this type of processing:

import pandas as pd
#I assumed you have no headers in the data files
df1 = pd.read_csv('./dataset1.txt',sep=';',header=None)
df2 = pd.read_csv('./dataset2.txt',sep=';',header=None)
#Join the datasets using full outer join on the first column in both datasets
df_merged = df1.merge(df2, on=0, how='outer')
#Fill the nulls with the desirable values in this case the average of the column
df_merged['1_x'].fillna(df_merged['1_x'].mean(),inplace=True)
df_merged['1_y'].fillna(df_merged['1_y'].mean(),inplace=True)

Output:

print(df_merged)
    0   1_x 1_y
0   0.5 3.4 y2
1   0.8 3.8 -0.9
2   0.9 1.2 y2
3   1.3 1.1 y2
4   1.9 2.3 y2
5   0.3 y1  -0.2
6   1.0 y1  0.1
7   1.5 y1  1.2
8   1.6 y1  6.3

You can change the column names easily:

df_merged.columns = ['col1','col2','col3']

You can also sort values easily using sort_values method:

df_merged.sort_values('col1')

Finally, you can convert this final DataFrame into a numpy array easily using:

import numpy as np
np.array(df_merged)


问:
Find single color, horizontal spaces in image
For example, there might be a table with text in rows. How could I find all straight, horizontal lines going through the table? E.g. (red lines are the found lines):

答:
Just for this question, to detect the horizontal lines, the morph-op is enough.

```<code>import cv2
img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((1,100), np.uint8)
morphed = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
cv2.imshow("res", morphed);cv2.waitKey();cv2.destroyAllWindows()
</code>```

Update, similar questions:

(1) Find single color, horizontal spaces in image

(2) OpenCV/cv2: Removing horizontal underlines

Body:
Just for this question, to detect the horizontal lines, the morph-op is enough.

import cv2
img = cv2.imread("test.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
kernel = np.ones((1,100), np.uint8)
morphed = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel)
cv2.imshow("res", morphed);cv2.waitKey();cv2.destroyAllWindows()

Update, similar questions:

(1) Find single color, horizontal spaces in image

(2) OpenCV/cv2: Removing horizontal underlines


问:
Random Forest and Python
I have a Random Forest model for a dataset with 72 features: Objective is to find the feature importances and use it for feature selection.

```<code>rf = RandomForestRegressor(n_estimators=XXX)
rf.fit(X, y)
</code>```

I am not able to get the list of predictors with their feature values, it just provide 72 feature importance numbers, which is very diffficult to map with each feature name,
Is there a way to get the names and importance together
Like

A 0.55656

  B 0.4333

etc

答:
Suppose your features are assigned to a list called feature_labels,

You may print the feature importance as follows,

```<code>for feature in zip(feature_labels, rf.feature_importances_):
    print(feature)
</code>```

The scores above are the importance scores for each variable. There thing to remember here is all the importance scores add up to 100%.

Inorder to identify and select most important features,

```<code># Create a selector object that will use the random forest classifier to identify
# features that have an importance of more than 0.15
sfm = SelectFromModel(rf, threshold=0.15)

# Train the selector
sfm.fit(X_train, y_train)

'''SelectFromModel(estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_split=1e-07, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            n_estimators=10000, n_jobs=-1, oob_score=False, random_state=0,
            verbose=0, warm_start=False),
        prefit=False, threshold=0.15)'''

# Print the names of the most important features
for feature_list_index in sfm.get_support(indices=True):
    print(feature_labels[feature_list_index])
</code>```

This will print out your most important feature names based on the threshold setting.

OwnerDisplayName: Amrita

Title: Random Forest and Python

Body:
I have a Random Forest model for a dataset with 72 features: Objective is to find the feature importances and use it for feature selection.

rf = RandomForestRegressor(n_estimators=XXX)
rf.fit(X, y)

I am not able to get the list of predictors with their feature values, it just provide 72 feature importance numbers, which is very diffficult to map with each feature name,
Is there a way to get the names and importance together
Like

A 0.55656

  B 0.4333

etc

Body:
Suppose your features are assigned to a list called feature_labels,

You may print the feature importance as follows,

for feature in zip(feature_labels, rf.feature_importances_):
    print(feature)

The scores above are the importance scores for each variable. There thing to remember here is all the importance scores add up to 100%.

Inorder to identify and select most important features,

# Create a selector object that will use the random forest classifier to identify
# features that have an importance of more than 0.15
sfm = SelectFromModel(rf, threshold=0.15)

# Train the selector
sfm.fit(X_train, y_train)

'''SelectFromModel(estimator=RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
            max_depth=None, max_features='auto', max_leaf_nodes=None,
            min_impurity_split=1e-07, min_samples_leaf=1,
            min_samples_split=2, min_weight_fraction_leaf=0.0,
            n_estimators=10000, n_jobs=-1, oob_score=False, random_state=0,
            verbose=0, warm_start=False),
        prefit=False, threshold=0.15)'''

# Print the names of the most important features
for feature_list_index in sfm.get_support(indices=True):
    print(feature_labels[feature_list_index])

This will print out your most important feature names based on the threshold setting.


问:
Cordova onActivityResult is called immediately after startActivityForResult with RESULT_CANCELED
In the code below, when onActivityResult is called immediately with RESULT_CANCELED.

As suggested in other answers, I have added setActivityResultCallback just before startActivityForResult() and PluginResult#setKeepCallback(true);. But nothing is helping out.
Any suggestion?

```<code> ....
  public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

    this.callbackContext  = callbackContext;

    if (action.equals(ACTION_OPEN))
    {
        if(PermissionHelper.hasPermission(this, READ))
        {
            chooseFile();
        }
     }
    else
    {
        return false;
    }

    return true;
}

  public void chooseFile() {

    final CordovaPlugin plugin = (CordovaPlugin) this;
    Runnable worker = new Runnable() {
        public void run() {
            Intent filePickerIntent = new Intent(Intent.ACTION_PICK);
            filePickerIntent.setType("image/*");
            plugin.cordova.setActivityResultCallback(plugin);
            plugin.cordova.startActivityForResult(plugin, Intent.createChooser(filePickerIntent,"Choose file"), PICK_FILE_REQUEST);
        }
    };
    this.cordova.getThreadPool().execute(worker);
    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    callbackContext.sendPluginResult(r);

}

 public void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.d(TAG,"Enter onActivityResult");

    if (requestCode == PICK_FILE_REQUEST) {

        Log.d(TAG,"requestCode == PICK_FILE_REQUEST");

        if (resultCode == Activity.RESULT_OK) {

            Log.d(TAG,"Result Ok");

            Uri uri = data.getData();
            Log.d(TAG, uri.toString());

        } else if (resultCode == Activity.RESULT_CANCELED) {

            Log.d(TAG,"Result canceled");

            callbackContext.error("OPERATION_CANCELLED");
            return;
        }

        this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "UNKNOWN_ERROR"));
    }
}
</code>```

答: I faced the same issue in one of my cordova application. I could not find the source of error but I resolved it by creating new project and installing all plugins again. It worked.</p>

Body:
In the code below, when onActivityResult is called immediately with RESULT_CANCELED.

As suggested in other answers, I have added setActivityResultCallback just before startActivityForResult() and PluginResult#setKeepCallback(true);. But nothing is helping out.
Any suggestion?

 ....
  public boolean execute(String action, CordovaArgs args, CallbackContext callbackContext) throws JSONException {

    this.callbackContext  = callbackContext;

    if (action.equals(ACTION_OPEN))
    {
        if(PermissionHelper.hasPermission(this, READ))
        {
            chooseFile();
        }
     }
    else
    {
        return false;
    }

    return true;
}

  public void chooseFile() {

    final CordovaPlugin plugin = (CordovaPlugin) this;
    Runnable worker = new Runnable() {
        public void run() {
            Intent filePickerIntent = new Intent(Intent.ACTION_PICK);
            filePickerIntent.setType("image/*");
            plugin.cordova.setActivityResultCallback(plugin);
            plugin.cordova.startActivityForResult(plugin, Intent.createChooser(filePickerIntent,"Choose file"), PICK_FILE_REQUEST);
        }
    };
    this.cordova.getThreadPool().execute(worker);
    PluginResult r = new PluginResult(PluginResult.Status.NO_RESULT);
    r.setKeepCallback(true);
    callbackContext.sendPluginResult(r);

}

 public void onActivityResult(int requestCode, int resultCode, Intent data) {

    Log.d(TAG,"Enter onActivityResult");

    if (requestCode == PICK_FILE_REQUEST) {

        Log.d(TAG,"requestCode == PICK_FILE_REQUEST");

        if (resultCode == Activity.RESULT_OK) {

            Log.d(TAG,"Result Ok");

            Uri uri = data.getData();
            Log.d(TAG, uri.toString());

        } else if (resultCode == Activity.RESULT_CANCELED) {

            Log.d(TAG,"Result canceled");

            callbackContext.error("OPERATION_CANCELLED");
            return;
        }

        this.callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "UNKNOWN_ERROR"));
    }
}


问:
WooCommerce, show some message after product were added to cart and update quantity of cart in header
I tried to figure this out for 2nd day already, but all I get is one of these two - neither it shows me a "View Cart" message (which I don't know where/how to edit) but only updates cart quantity at the next page refresh, or it refreshes cart quantity after adding item to cart, but doesn't show any message.

To show a message without cart quantity update in content-product.php I used this piece of code:

```<code><div class="prod-item-add-to-cart">
    <?php

        echo apply_filters( 'woocommerce_loop_add_to_cart_link',
        sprintf( '<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
                esc_url( $product->add_to_cart_url() ),
                esc_attr( isset( $quantity ) ? $quantity : 1 ),
                esc_attr( $product->get_id() ),
                esc_attr( $product->get_sku() ),
                esc_attr( isset( $class ) ? $class : 'button' ),
                esc_html( $product->add_to_cart_text() )
            ),
        $product );

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

And In header I have this:

```<code><?php echo sprintf ( WC()->cart->get_cart_contents_count() ); ?> <?php _e('pcs.', 'eg'); ?> / ~ <?php echo WC()->cart->get_cart_total(); ?>
</code>```

To update quantity in header, but in this case added cart message doesn't show, I used this code in content-product.php:

```<code><div class="prod-item-add-to-cart">
    <?php do_action('woocommerce_after_shop_loop_item'); ?>
</div>
</code>```

I need to make both options work - to show some success message after adding item to cart, and to update cart quantity without update.

答:
please check following code for message after added product into the cart.

```<code>    /**
      * Custom Add To Cart Messages
      * Add this to your theme functions.php file
    **/
   add_filter( 'woocommerce_add_to_cart_message',
          'custom_add_to_cart_message' );
    function custom_add_to_cart_message() {
global $woocommerce;
    // Output success messages
    if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
        $return_to  = get_permalink(woocommerce_get_page_id('shop'));
        $message    = sprintf('<a href="%s" class="button">%s</a> %s',
        $return_to, __('Continue Shopping →', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
     else :
        $message    = sprintf('<a href="%s" class="button">%s</a> %s',
          get_permalink(woocommerce_get_page_id('cart')), __('View
          Cart →', 'woocommerce'), __('Product successfully added
          to your cart.', 'woocommerce') );
     endif;

    return $message;
 }
</code>```

Hope this helps you

Body:
I tried to figure this out for 2nd day already, but all I get is one of these two - neither it shows me a "View Cart" message (which I don't know where/how to edit) but only updates cart quantity at the next page refresh, or it refreshes cart quantity after adding item to cart, but doesn't show any message.

To show a message without cart quantity update in content-product.php I used this piece of code:

    <?php

        echo apply_filters( 'woocommerce_loop_add_to_cart_link',
        sprintf( '%s',
                esc_url( $product->add_to_cart_url() ),
                esc_attr( isset( $quantity ) ? $quantity : 1 ),
                esc_attr( $product->get_id() ),
                esc_attr( $product->get_sku() ),
                esc_attr( isset( $class ) ? $class : 'button' ),
                esc_html( $product->add_to_cart_text() )
            ),
        $product );

        ?>

And In header I have this:

<?php echo sprintf ( WC()->cart->get_cart_contents_count() ); ?> <?php _e('pcs.', 'eg'); ?> / ~ <?php echo WC()->cart->get_cart_total(); ?>

To update quantity in header, but in this case added cart message doesn't show, I used this code in content-product.php:

    <?php do_action('woocommerce_after_shop_loop_item'); ?>

I need to make both options work - to show some success message after adding item to cart, and to update cart quantity without update.

Body:
please check following code for message after added product into the cart.

    /**
      * Custom Add To Cart Messages
      * Add this to your theme functions.php file
    **/
   add_filter( 'woocommerce_add_to_cart_message',
          'custom_add_to_cart_message' );
    function custom_add_to_cart_message() {
global $woocommerce;
    // Output success messages
    if (get_option('woocommerce_cart_redirect_after_add')=='yes') :
        $return_to  = get_permalink(woocommerce_get_page_id('shop'));
        $message    = sprintf('<a href="%s" class="button">%s</a> %s',
        $return_to, __('Continue Shopping &rarr;', 'woocommerce'), __('Product successfully added to your cart.', 'woocommerce') );
     else :
        $message    = sprintf('<a href="%s" class="button">%s</a> %s',
          get_permalink(woocommerce_get_page_id('cart')), __('View
          Cart &rarr;', 'woocommerce'), __('Product successfully added
          to your cart.', 'woocommerce') );
     endif;

    return $message;
 }

Hope this helps you


问:
Any pointers to fix the Unix millennium bug or Y2k38 problem?
I've been reviewing the year 2038 problem (Unix Millennium Bug).

I read the article about this on Wikipedia, where I read about a solution for this problem.

Now I would like to change the time_t data type to an unsigned 32bit integer, which will allow me to be alive until 2106. I have Linux kernel 2.6.23 with RTPatch on PowerPC.

Is there any patch available that would allow me to change the time_t data type to an unsigned 32bit integer for PowerPC? Or any patch available to resolve this bug?

答:
time_t is actually defined in your libc implementation, and not the kernel itself.

The kernel provides various mechanisms that provide the current time (in the form of system calls), many of which already support over 32-bits of precision. The problem is actually your libc implementation (glibc on most desktop Linux distributions), which, after fetching the time from the kernel, returns it back to your application in the form of a 32-bit signed integer data type.

While one could theoretically change the definition of time_t in your libc implementation, in practice it would be fairly complicated: such a change would change the ABI of libc, in turn requiring that every application using libc to also be recompiled from sources.

The easiest solution instead is to upgrade your system to a 64-bit distribution, where time_t is already defined to be a 64-bit data type, avoiding the problem altogether.


问:
Check if dynamically created checkbox is checked or not?
I have a table with 16 rows and each row contains checkbox. I need to check if checkbox is checked or not. If check then do something otherwise do something else. I am trying but logic not working:

BtnGet is a button in each row. I am firing event on BtnGet:

```<code>$('.btnGet').each(function (i, obj) {
   if ($(obj)
      .closest("tr")
      .children("td:nth-child(3)")
      .find("input[type = checkbox]")
      .checked)
      {
          console.log("Working");
       }
}
</code>```

答:
Do like this:

$('.btnGet tr').each(function (i, obj) {
  if($(this).children().eq(2).find("input[type = checkbox]").is(":checked")){
    console.log('checked');
  }else{
     console.log('not checked');
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="btnGet" style="width:500px;height:500px;border:1px solid;">
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
</table></code>```

Body:
I have a table with 16 rows and each row contains checkbox. I need to check if checkbox is checked or not. If check then do something otherwise do something else. I am trying but logic not working:

BtnGet is a button in each row. I am firing event on BtnGet:

$('.btnGet').each(function (i, obj) {
   if ($(obj)
      .closest("tr")
      .children("td:nth-child(3)")
      .find("input[type = checkbox]")
      .checked)
      {
          console.log("Working");
       }
}

Body:
Do like this:

$('.btnGet tr').each(function (i, obj) {
  if($(this).children().eq(2).find("input[type = checkbox]").is(":checked")){
    console.log('checked');
  }else{
     console.log('not checked');
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="btnGet" style="width:500px;height:500px;border:1px solid;">
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" ></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
<tr><td>1</td><td>2</td><td><input type="checkbox" checked></td></tr>
</table>


问:
Unable to merge dex
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

```<code>Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
</code>```

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

```<code>    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

My app gradle:

```<code>    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}
</code>```

And my module gradle:

```<code>    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}
</code>```

My second module:

```<code>     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}
</code>```

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D

答:
Simple solution worked for me:

Don't compile/implement two versions of same dependencies.

Don't use .jar file in libs folder of your project, if you are compiling it directly from gradle. Above point applies here too.

Then Clean and Rebuild project.

Title: Unable to merge dex

Body:
I have Android Studio Beta. I created a new project with compile my old modules but when I tried launching the app it did not launch with the message:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

But I don't know how to solve this error. I googled this for hours but with no success.

My project gradle:

    // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-beta6'
        classpath "io.realm:realm-gradle-plugin:3.7.1"
        classpath 'com.google.gms:google-services:3.1.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My app gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        applicationId "parad0x.sk.onlyforyou"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        multiDexEnabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {
        }
    }
    compileOptions {
        targetCompatibility 1.7
        sourceCompatibility 1.7
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/NOTICE'
    }
    lintOptions {
        checkReleaseBuilds false
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleCompatible
    compile 'com.android.support:appcompat-v7:26.0.0-alpha1'
    compile project(path: ':loginregisterview')

}

And my module gradle:

    apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"

    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.0.2'
    compile 'com.android.support:support-v4:26.1.0'
    compile 'com.github.bumptech.glide:glide:4.0.0'
    testCompile 'junit:junit:4.12'
    compile project(path: ':parser')

}

My second module:

     apply plugin: 'com.android.library'
apply plugin: 'realm-android'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

    realm {
        syncEnabled = true
    }
    useLibrary 'org.apache.http.legacy'

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile 'junit:junit:4.12'
    //  compile 'com.android.support:appcompat-v7:23.1.0'

    //   compile 'com.fasterxml.jackson.core:jackson-core:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-annotations:2.9.0'
 //   compile 'com.fasterxml.jackson.core:jackson-databind:2.9.0'
    compile 'com.google.code.gson:gson:2.6.2'
}

____________finding_________

When I did not import the second module (parser) the app did not crash on dex but when the module was not imported app did not work. :D :D


问:
How to produce cartesian product in bash?
I want to produce such file (cartesian product of [1-3]X[1-5]):

```<code>1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
3 1
3 2
3 3
3 4
3 5
</code>```

I can do this using nested loop like:

```<code>for i in $(seq 3)
do
  for j in $(seq 5)
  do
      echo $i $j
  done
done
</code>```

is there any solution without loops?

答:
A shorter (but hacky) version of Rubens's answer:

```<code>join -j 999999 -o 1.1,2.1 file1 file2
</code>```

Since the field 999999 most likely does not exist it is considered equal for both sets and therefore join have to do the Cartesian product. It uses O(N+M) memory and produces output at 100..200 Mb/sec on my machine.

I don't like the "shell brace expansion" method like echo {1..100}x{1..100} for large datasets because it uses O(N*M) memory and can when used careless bring your machine to knees. It is hard to stop because ctrl+c does not interrupts brace expansion which is done by the shell itself.

Body:
I want to produce such file (cartesian product of [1-3]X[1-5]):

1 1
1 2
1 3
1 4
1 5
2 1
2 2
2 3
2 4
2 5
3 1
3 2
3 3
3 4
3 5

I can do this using nested loop like:

for i in $(seq 3)
do
  for j in $(seq 5)
  do
      echo $i $j
  done
done

is there any solution without loops?

Body:
A shorter (but hacky) version of Rubens's answer:

join -j 999999 -o 1.1,2.1 file1 file2

Since the field 999999 most likely does not exist it is considered equal for both sets and therefore join have to do the Cartesian product. It uses O(N+M) memory and produces output at 100..200 Mb/sec on my machine.

I don't like the "shell brace expansion" method like echo {1..100}x{1..100} for large datasets because it uses O(N*M) memory and can when used careless bring your machine to knees. It is hard to stop because ctrl+c does not interrupts brace expansion which is done by the shell itself.


问:
Visual Studio 2013 .aspx intellisense not working
In my .aspx page I am trying to write some code but it seems my intellisense is not working. (Visual Studio 2013)

I tried deleting my v12.suo file but that did not resolve anything. I also tried web essentials and looking around my options but I couldn't get it to work.

So I tried:

Deleting v12.suo file

Cleaning/Rebuilding solution

Web Essentials

Different options in Tools -> options

Anyone have an idea of how to fix this?

答: As mentioned above, check that intellisense is enabled, if it is enabled and not appearing you can refresh it, the standard command in visual studio is CTRL+SHIFT+R</p>


问:
"Collapsing" state in a functional map?
This question is inspired by Software Foundations, but isn't about an exercise. That I know about, so far.

The Imp chapter ("Simple Imperative Programs") uses functional maps (from the Maps chapter ("Total and Partial Maps")) for the environment of the simpl.[1] programming language.

```<code>Inductive id : Type :=
  | Id : string -> id.

Definition total_map (A:Type) := id -> A.

Definition t_empty {A:Type} (v : A) : total_map A :=
  (fun _ => v).

Definition t_update {A:Type} (m : total_map A) (x : id) (v : A) :=
  fun x' => if beq_id x x' then v else m x'.
</code>```

Reasoning about programs in the Imp chapter requires manipulating program states of the form t_update (t_update (...) x 4) y 12), which becomes tedious because the state grows with every assignment, even if what the assignment is "implementing" is an update of an existing variable.

In theory, it should be possible to collapse program states down to single t_update's for each variable, and I've gone so far as to prove a couple of lemmas that go in the right direction.

```<code>Require Import Coq.Logic.FunctionalExtensionality.

Lemma swap_updates : forall A (m : total_map A) x vx y vy,
  x <> y -> t_update (t_update m x vx) y vy = t_update (t_update m y vy) x vx.
Proof.
  intros A m x vx y vy H. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id y k) eqn:Eqyk.
  - destruct (beq_id x k) eqn:Eqxk.
    + apply beq_id_true_iff in Eqyk. apply beq_id_true_iff in Eqxk. subst.
      contradiction.
    + reflexivity.
  - destruct (beq_id x k) eqn:Eqxk; reflexivity.
Qed.

Lemma collapse_updates : forall A (m : total_map A) x v1 v2,
  t_update (t_update m x v1) x v2 = t_update m x v2.
Proof.
  intros A m x v1 v2. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id x k); reflexivity.
Qed.
</code>```

But I don't know how to state (much less prove or use, for that matter) a theorem that t_update (... (t_update (...) x 4) ...) x 27 is equal to t_update (...) x 27; i.e. with the useless bindings for x removed.

Any ideas?

[1] I just saw this. I'm leaving it, but I'm considering taking a vacation from Coq soon.

答:
How about something like this?

```<code>Definition almost_equal {A} x (m m' : total_map A) :=
  forall y, x <> y -> m y = m' y.

Lemma update_almost_equal : forall A (m : total_map A) x v1,
  almost_equal x (t_update m x v1) m.
Proof.
  intros A m x v1 y H.
  unfold t_update.
  destruct (beq_id x y) eqn:Eqxy.
  + rewrite beq_id_true_iff in Eqxy. congruence.
  + reflexivity.
Qed.

Lemma update_preserves_almost_equal : forall A (m m' : total_map A) x y v,
  almost_equal x m m' ->
  almost_equal x (t_update m y v) (t_update m' y v).
Proof.
  intros A m m' x y v H z H'.
  unfold t_update.
  destruct (beq_id y z); auto.
Qed.

Lemma collapse_updates : forall x A (m m' : total_map A) v,
  almost_equal x m m' ->
  t_update m x v = t_update m' x v.
Proof.
  intros x A m m' v Hae. apply functional_extensionality. intros k.
  unfold t_update.
  destruct (beq_id x k) eqn:Heq.
  + reflexivity.
  + rewrite beq_id_false_iff in Heq.
    apply Hae; exact Heq.
Qed.
</code>```

You can rewrite with collapse_updates, and eauto can construct the proof of almost_equal.

```<code>Example ex1 :
  forall A x y z (v1 v2 v3 v4 : A) m,
      t_update (t_update (t_update (t_update m x v1) z v2) y v3) x v4
    = t_update (t_update (t_update m                 z v2) y v3) x v4.
Proof.
  intros.
  erewrite collapse_updates by eauto using update_almost_equal, update_preserves_almost_equal.
  reflexivity.
Qed.

Example ex2 :
  forall A x y z (v1 v2 v3 v4: A) m,
      t_update (t_update (t_update (t_update m y v1) z v2) y v3) x v4
    = t_update (t_update (t_update m                 z v2) y v3) x v4.
Proof.
  intros.
  erewrite (collapse_updates y) by eauto using update_almost_equal, update_preserves_almost_equal.
  reflexivity.
Qed.
</code>```

A drawback is that you have to mention the variable you want to simplify on, e.g. collapse_updates y above. I guess this is because rewrite doesn't backtrack across different choices of subterms, so if you don't mention the variable it will try the outermost one and then give up if that fails. That meant that I couldn't figure out any way to use this as an autorewrite hint, although you can write an Ltac which tries all different variables:

```<code>Ltac simpl_updates :=
  repeat match goal with
  | [ |- context C1[t_update _ ?X _] ] =>
    erewrite (collapse_updates X) by eauto using update_almost_equal, update_preserves_almost_equal
  end.

Example ex3 :
  forall A x y z w (v1 v2 v3 v4 v5 v6 v7 v8: A) m,
      t_update (t_update (t_update (t_update (t_update (t_update (t_update m x v1) y v2) z v3) x v4) y v5) w v6) y v7
    = t_update (t_update (t_update (t_update m z v3) x v4) w v6) y v7.
Proof.
  intros.
  simpl_updates.
  reflexivity.
Qed.
</code>```

Title: "Collapsing" state in a functional map?

Body:
This question is inspired by Software Foundations, but isn't about an exercise. That I know about, so far.

The Imp chapter ("Simple Imperative Programs") uses functional maps (from the Maps chapter ("Total and Partial Maps")) for the environment of the simpl.[1] programming language.

Inductive id : Type :=
  | Id : string -> id.

Definition total_map (A:Type) := id -> A.

Definition t_empty {A:Type} (v : A) : total_map A :=
  (fun _ => v).

Definition t_update {A:Type} (m : total_map A) (x : id) (v : A) :=
  fun x' => if beq_id x x' then v else m x'.

Reasoning about programs in the Imp chapter requires manipulating program states of the form t_update (t_update (...) x 4) y 12), which becomes tedious because the state grows with every assignment, even if what the assignment is "implementing" is an update of an existing variable.

In theory, it should be possible to collapse program states down to single t_update's for each variable, and I've gone so far as to prove a couple of lemmas that go in the right direction.

Require Import Coq.Logic.FunctionalExtensionality.

Lemma swap_updates : forall A (m : total_map A) x vx y vy,
  x <> y -> t_update (t_update m x vx) y vy = t_update (t_update m y vy) x vx.
Proof.
  intros A m x vx y vy H. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id y k) eqn:Eqyk.
  - destruct (beq_id x k) eqn:Eqxk.
    + apply beq_id_true_iff in Eqyk. apply beq_id_true_iff in Eqxk. subst.
      contradiction.
    + reflexivity.
  - destruct (beq_id x k) eqn:Eqxk; reflexivity.
Qed.

Lemma collapse_updates : forall A (m : total_map A) x v1 v2,
  t_update (t_update m x v1) x v2 = t_update m x v2.
Proof.
  intros A m x v1 v2. apply functional_extensionality. intros k.
  unfold t_update. destruct (beq_id x k); reflexivity.
Qed.

But I don't know how to state (much less prove or use, for that matter) a theorem that t_update (... (t_update (...) x 4) ...) x 27 is equal to t_update (...) x 27; i.e. with the useless bindings for x removed.

Any ideas?

[1] I just saw this. I'm leaving it, but I'm considering taking a vacation from Coq soon.

Body:
How about something like this?

Definition almost_equal {A} x (m m' : total_map A) :=
  forall y, x <> y -> m y = m' y.

Lemma update_almost_equal : forall A (m : total_map A) x v1,
  almost_equal x (t_update m x v1) m.
Proof.
  intros A m x v1 y H.
  unfold t_update.
  destruct (beq_id x y) eqn:Eqxy.
  + rewrite beq_id_true_iff in Eqxy. congruence.
  + reflexivity.
Qed.

Lemma update_preserves_almost_equal : forall A (m m' : total_map A) x y v,
  almost_equal x m m' ->
  almost_equal x (t_update m y v) (t_update m' y v).
Proof.
  intros A m m' x y v H z H'.
  unfold t_update.
  destruct (beq_id y z); auto.
Qed.

Lemma collapse_updates : forall x A (m m' : total_map A) v,
  almost_equal x m m' ->
  t_update m x v = t_update m' x v.
Proof.
  intros x A m m' v Hae. apply functional_extensionality. intros k.
  unfold t_update.
  destruct (beq_id x k) eqn:Heq.
  + reflexivity.
  + rewrite beq_id_false_iff in Heq.
    apply Hae; exact Heq.
Qed.

You can rewrite with collapse_updates, and eauto can construct the proof of almost_equal.

Example ex1 :
  forall A x y z (v1 v2 v3 v4 : A) m,
      t_update (t_update (t_update (t_update m x v1) z v2) y v3) x v4
    = t_update (t_update (t_update m                 z v2) y v3) x v4.
Proof.
  intros.
  erewrite collapse_updates by eauto using update_almost_equal, update_preserves_almost_equal.
  reflexivity.
Qed.

Example ex2 :
  forall A x y z (v1 v2 v3 v4: A) m,
      t_update (t_update (t_update (t_update m y v1) z v2) y v3) x v4
    = t_update (t_update (t_update m                 z v2) y v3) x v4.
Proof.
  intros.
  erewrite (collapse_updates y) by eauto using update_almost_equal, update_preserves_almost_equal.
  reflexivity.
Qed.

A drawback is that you have to mention the variable you want to simplify on, e.g. collapse_updates y above. I guess this is because rewrite doesn't backtrack across different choices of subterms, so if you don't mention the variable it will try the outermost one and then give up if that fails. That meant that I couldn't figure out any way to use this as an autorewrite hint, although you can write an Ltac which tries all different variables:

Ltac simpl_updates :=
  repeat match goal with
  | [ |- context C1[t_update _ ?X _] ] =>
    erewrite (collapse_updates X) by eauto using update_almost_equal, update_preserves_almost_equal
  end.

Example ex3 :
  forall A x y z w (v1 v2 v3 v4 v5 v6 v7 v8: A) m,
      t_update (t_update (t_update (t_update (t_update (t_update (t_update m x v1) y v2) z v3) x v4) y v5) w v6) y v7
    = t_update (t_update (t_update (t_update m z v3) x v4) w v6) y v7.
Proof.
  intros.
  simpl_updates.
  reflexivity.
Qed.


问:
"javafx.fxml.LoadException" when loading fxml
The error is being produced at showAdminLoginScene() method,
However if I modify this method and I put another fxml file from the same package to load, it loads just fine :  here's my Main :

```<code>package application;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
  private Stage primaryStage;
  private static BorderPane mainLayout;
  @Override
public void start(Stage primaryStage) throws IOException {
    this.primaryStage= primaryStage;
    this.primaryStage.setTitle("LAU LABS");
    showMainView();
}
private void showMainView() throws IOException{
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("MainView.fxml"));

    mainLayout=loader.load();

    Scene scene=new Scene(mainLayout);
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void showAdminLoginScene() {
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("AdminLogin.fxml"));
    BorderPane adminLogin;
    try {
        adminLogin = loader.load();
        mainLayout.setCenter(adminLogin);
        } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void showAdminLoggedIn() {
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("AdminLoggedIn.fxml"));
    AnchorPane adminLoggedIn;
    try {
        adminLoggedIn = loader.load();
        mainLayout.setCenter(adminLoggedIn);
    } catch (IOException e) {
        System.out.println("the error is in Main, ShowAdminLoggedIn");
    }

}
public static void main(String[] args) {
    launch(args);
}
}
</code>```

And here's my controller class :

```<code>package application;

import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javafx.fxml.FXML;

public class AdminLoginController {
   @FXML private TextField txtUsername;
   @FXML private TextField txtPassword;
   @FXML private Label lblStatus;
   private Main main;

public void Login(ActionEvent event) {
   if(txtUsername.getText().equals("user")&&
         txtPassword.getText().equals("pass")){
    main.showAdminLoggedIn();
}
else{
    lblStatus.setText("Login Failed!");
}
}
}
</code>```

Here's my fxml :

```<code><?xml version="1.0" encoding="UTF-8"?>

<?import com.gluonhq.charm.glisten.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Text?>

<BorderPane xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AdminLoginController">
   <center>
      <AnchorPane prefHeight="300.0" prefWidth="300.0">
         <children>
            <TextField fx:id="txtUsername" layoutX="56.0" layoutY="79.0" prefHeight="26.0" prefWidth="189.0" />
            <PasswordField fx:id="txtPassword" layoutX="56.0" layoutY="150.0" prefHeight="26.0" prefWidth="189.0" />
            <Button layoutX="56.0" layoutY="227.0" mnemonicParsing="false" onAction="#Login" prefHeight="32.0" prefWidth="189.0" style="-fx-background-color: #004c3c;" text="Login" />
            <Text fill="#004c3c" layoutX="56.0" layoutY="75.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Username" wrappingWidth="60.98307228088379" />
            <Text fill="#004c3c" layoutX="56.0" layoutY="146.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Password" />
            <Button layoutX="1.0" minWidth="52.0" mnemonicParsing="false" prefHeight="39.0" prefWidth="52.0" style="-fx-background-color: Transparent;" />
            <ImageView fitHeight="35.0" fitWidth="200.0" layoutX="10.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@BackButton.png" />
               </image>
            </ImageView>
            <Label fx:id="lblStatus" layoutX="56.0" layoutY="202.0" prefHeight="16.0" prefWidth="189.0" style="-fx-text-fill: Red;" text="Status: " />
         </children>
      </AnchorPane>
   </center>
</BorderPane>
</code>```

They're all in the same package named "application" (the fxml, controller and main)

That's the error :

```<code>javafx.fxml.LoadException:
/C:/Users/Owner/Documents/UNI/programming/workspace/Lau/bin/application/AdminLogin.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2848)
    at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
    at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at application.Main.showAdminLoginScene(Main.java:39)
    at application.MainViewController.goAdminLogin(MainViewController.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.gluonhq.charm.glisten.control.TextField
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
    at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
    ... 65 more
</code>```

答:
You are using an incorrect TextField (I guess it is not intentional) in your FXML:

```<code><?import com.gluonhq.charm.glisten.control.TextField?>
</code>```

which is causing:

```<code>Caused by: java.lang.ClassNotFoundException: com.gluonhq.charm.glisten.control.TextField
</code>```

You can change the import as ...

```<code><?import javafx.scene.control.TextField?>
</code>```

to use the built-in TextField.

Body:
The error is being produced at showAdminLoginScene() method,
However if I modify this method and I put another fxml file from the same package to load, it loads just fine :  here's my Main :

package application;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
  private Stage primaryStage;
  private static BorderPane mainLayout;
  @Override
public void start(Stage primaryStage) throws IOException {
    this.primaryStage= primaryStage;
    this.primaryStage.setTitle("LAU LABS");
    showMainView();
}
private void showMainView() throws IOException{
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("MainView.fxml"));

    mainLayout=loader.load();

    Scene scene=new Scene(mainLayout);
    primaryStage.setScene(scene);
    primaryStage.show();
}

public static void showAdminLoginScene() {
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("AdminLogin.fxml"));
    BorderPane adminLogin;
    try {
        adminLogin = loader.load();
        mainLayout.setCenter(adminLogin);
        } catch (IOException e) {
        e.printStackTrace();
    }

}
public static void showAdminLoggedIn() {
    FXMLLoader loader=new FXMLLoader();
    loader.setLocation(Main.class.getResource("AdminLoggedIn.fxml"));
    AnchorPane adminLoggedIn;
    try {
        adminLoggedIn = loader.load();
        mainLayout.setCenter(adminLoggedIn);
    } catch (IOException e) {
        System.out.println("the error is in Main, ShowAdminLoggedIn");
    }

}
public static void main(String[] args) {
    launch(args);
}
}

And here's my controller class :

package application;

import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.io.IOException;

import javafx.fxml.FXML;

public class AdminLoginController {
   @FXML private TextField txtUsername;
   @FXML private TextField txtPassword;
   @FXML private Label lblStatus;
   private Main main;

public void Login(ActionEvent event) {
   if(txtUsername.getText().equals("user")&&
         txtPassword.getText().equals("pass")){
    main.showAdminLoggedIn();
}
else{
    lblStatus.setText("Login Failed!");
}
}
}

Here's my fxml :

<?xml version="1.0" encoding="UTF-8"?>

<?import com.gluonhq.charm.glisten.control.TextField?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.PasswordField?>
<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.BorderPane?>
<?import javafx.scene.text.Text?>

<BorderPane xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.AdminLoginController">

      <AnchorPane prefHeight="300.0" prefWidth="300.0">
         <children>
            <TextField fx:id="txtUsername" layoutX="56.0" layoutY="79.0" prefHeight="26.0" prefWidth="189.0" />
            <PasswordField fx:id="txtPassword" layoutX="56.0" layoutY="150.0" prefHeight="26.0" prefWidth="189.0" />
            <Button layoutX="56.0" layoutY="227.0" mnemonicParsing="false" onAction="#Login" prefHeight="32.0" prefWidth="189.0" style="-fx-background-color: #004c3c;" text="Login" />
            <Text fill="#004c3c" layoutX="56.0" layoutY="75.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Username" wrappingWidth="60.98307228088379" />
            <Text fill="#004c3c" layoutX="56.0" layoutY="146.0" strokeType="OUTSIDE" strokeWidth="0.0" text="Password" />
            <Button layoutX="1.0" minWidth="52.0" mnemonicParsing="false" prefHeight="39.0" prefWidth="52.0" style="-fx-background-color: Transparent;" />
            <ImageView fitHeight="35.0" fitWidth="200.0" layoutX="10.0" layoutY="14.0" pickOnBounds="true" preserveRatio="true">
               <image>
                  <Image url="@BackButton.png" />
               </image>
            </ImageView>

         </children>
      </AnchorPane>

</BorderPane>

They're all in the same package named "application" (the fxml, controller and main)

That's the error :

javafx.fxml.LoadException:
/C:/Users/Owner/Documents/UNI/programming/workspace/Lau/bin/application/AdminLogin.fxml

    at javafx.fxml.FXMLLoader.constructLoadException(FXMLLoader.java:2601)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2848)
    at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
    at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
    at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
    at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
    at application.Main.showAdminLoginScene(Main.java:39)
    at application.MainViewController.goAdminLogin(MainViewController.java:8)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Node.fireEvent(Node.java:8413)
    at javafx.scene.control.Button.fire(Button.java:185)
    at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
    at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
    at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:381)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:417)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:416)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.gluonhq.charm.glisten.control.TextField
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
    at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
    at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
    ... 65 more

Body:
You are using an incorrect TextField (I guess it is not intentional) in your FXML:

<?import com.gluonhq.charm.glisten.control.TextField?>

which is causing:

Caused by: java.lang.ClassNotFoundException: com.gluonhq.charm.glisten.control.TextField

You can change the import as ...

<?import javafx.scene.control.TextField?>

to use the built-in TextField.