问:
Android multiple Progressbar Instances not updating correctly
I have a CustomView that has a progress bar in it. The custom view has a progress bar with a title and text progress as "1/5". I use this CustomView (ProgressBadgeWidget) in several places, including twice in my item layout for a RecyclerView (item_levels.xml - simplified for this):

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"

>

<com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget
    android:id="@+id/courses_done_progress_widget"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:elevation="4dp"
    android:visibility="visible"
    app:badge_image="@drawable/trophy_gold"
    app:layout_constraintBottom_toBottomOf="@id/background_image"
    app:layout_constraintEnd_toEndOf="@id/background_image"
    app:layout_constraintHeight_percent="0.18"
    app:layout_constraintHorizontal_bias="0.12"
    app:layout_constraintStart_toStartOf="@id/background_image"
    app:layout_constraintTop_toTopOf="@id/background_image"
    app:layout_constraintVertical_bias="0.96"
    app:layout_constraintWidth_percent="0.24"
    app:progress_badge_title="@string/courses_done"
    app:progress_bar_background_color="@color/progress_bar_background_default"
    app:progress_text_color="@color/progress_bar_background_course_header"

    />

<com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget
    android:id="@+id/medals_earned_progress_widget"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:elevation="4dp"
    android:visibility="visible"
    app:badge_image="@drawable/medal_gold_small"
    app:layout_constraintBottom_toBottomOf="@id/background_image"
    app:layout_constraintEnd_toEndOf="@id/background_image"
    app:layout_constraintHeight_percent="0.18"
    app:layout_constraintHorizontal_bias="0.85"
    app:layout_constraintStart_toStartOf="@id/background_image"
    app:layout_constraintTop_toTopOf="@id/background_image"
    app:layout_constraintVertical_bias="0.96"
    app:layout_constraintWidth_percent="0.24"
    app:progress_badge_title="@string/medals_earned"
    app:progress_bar_background_color="@color/progress_bar_background_default"
    app:progress_bar_foreground_color="@color/progress_bar_default_color"
    app:progress_text_color="@color/progress_bar_background_course_header" />
</code>```

The xml layout for the ProgressBadgeWidget is below:

```<code><merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
tools:parentTag="com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget">

<TextView
    android:id="@+id/badge_title"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:fontFamily="@font/avenir_family"
    android:gravity="center"
    android:letterSpacing="-0.04"
    android:textColor="@color/courses_badge_text_color"
    android:textSize="12sp"
    app:lineHeight="16sp"
    app:layout_constraintBottom_toTopOf="@id/badge_image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"

    />

<com.trala.learn.violin.view.core.widgets.EZColorProgressBar
    android:id="@+id/progress_badge_widget_progress_bar"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHeight_percent="0.10"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_percent="0.90"
    tools:progress="50" />

<ImageView
    android:id="@+id/badge_image"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintEnd_toEndOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintStart_toStartOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintTop_toTopOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintWidth_percent="0.27"
    tools:src="@drawable/trophy_gold" />

<TextView
    android:id="@+id/progress_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/avenir_family"
    android:textColor="@color/courses_badge_text_color"
    android:textSize="12sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/badge_image"
    tools:text="4/7" />
</code>```

Pretty simple, as described before. Main part is the EZColorProgressBar, which is a subclassed ProgressBar just providing ways to change bar colors and a method to set progress and max:

```<code> class EZColorProgressBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.progressBarStyleHorizontal, defStyleRes: Int = 0):
            ProgressBar(context, attrs, defStyleAttr, defStyleRes) {

fun setProgressNumbers(currentCount: Int, totalCount: Int) {
        if (currentCount > totalCount) Timber.d("Current Badge Count > Total Badge Count")

        val shouldShowBadges = currentCount >= totalCount && (currentCount != 0 && totalCount != 0)
        showBadge(shouldShowBadges)

        viewBinding?.progressBadgeWidgetProgressBar?.setMax(totalCount)
        viewBinding?.progressBadgeWidgetProgressBar?.setProgress(currentCount)
        viewBinding?.progressText?.setText(String.format(context.getString(R.string.score_string), currentCount, totalCount))

      }
}
</code>```

I use the ProgressBadgeWidget and EZProgressBar on almost all of my Fragments. When I go between fragments and navigate backwards, the progress bars are not always showing their numbers correctly, ie the first time 0/5 will show correctly, then navigating to other pages that use this EZProgressBar and navigate back will show 1/5 even if the text has 0/5.

First navigation:

After: data model backing progress bar is correct (you can see from the 0/5 being correct). Looks like it's applying the 3/11 from the other progress bar

When this happens it actually applies the incorrect progress bar numbers to all progress bars in the layout (ie every progress bar in all items of item_level in the recyclerview adapter and even in a separate fragment so it's not tied to the recyclerview.) But again all of the text "x/x" shows correctly.

I've tried using kotlin synthetics bindings and google view bindings. It feels like the separate instances of the progress bars (they are separate as I've printed out the hashcodes) they are pointing at the same progress bar because it's searching for views based on IDs. The ProgressBadgeWidgets have unique ID's but their nested progress bars have the same IDs.

Has anyone come across issues like this and/or specifically with Android Progress Bars?

答:
If anyone comes upon an issue with multiple progress bars not updating properly, seems there is a big Android bug related to this. Way to solve it is to explicitly change/reset the max and progress values before setting to your correct numbers. I added these methods to my custom progress bar:</p>

```<code>fun setProgressSafely(progress: Int) {
    setProgress(progress + 1)
    setProgress(progress)
}

fun setMaxSafely(max: Int) {
    setMax(max + 1)
    setMax(max)
}
</code>```

Body:
I have a CustomView that has a progress bar in it. The custom view has a progress bar with a title and text progress as "1/5". I use this CustomView (ProgressBadgeWidget) in several places, including twice in my item layout for a RecyclerView (item_levels.xml - simplified for this):

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"

>

<com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget
    android:id="@+id/courses_done_progress_widget"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:elevation="4dp"
    android:visibility="visible"
    app:badge_image="@drawable/trophy_gold"
    app:layout_constraintBottom_toBottomOf="@id/background_image"
    app:layout_constraintEnd_toEndOf="@id/background_image"
    app:layout_constraintHeight_percent="0.18"
    app:layout_constraintHorizontal_bias="0.12"
    app:layout_constraintStart_toStartOf="@id/background_image"
    app:layout_constraintTop_toTopOf="@id/background_image"
    app:layout_constraintVertical_bias="0.96"
    app:layout_constraintWidth_percent="0.24"
    app:progress_badge_title="@string/courses_done"
    app:progress_bar_background_color="@color/progress_bar_background_default"
    app:progress_text_color="@color/progress_bar_background_course_header"

    />

<com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget
    android:id="@+id/medals_earned_progress_widget"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:elevation="4dp"
    android:visibility="visible"
    app:badge_image="@drawable/medal_gold_small"
    app:layout_constraintBottom_toBottomOf="@id/background_image"
    app:layout_constraintEnd_toEndOf="@id/background_image"
    app:layout_constraintHeight_percent="0.18"
    app:layout_constraintHorizontal_bias="0.85"
    app:layout_constraintStart_toStartOf="@id/background_image"
    app:layout_constraintTop_toTopOf="@id/background_image"
    app:layout_constraintVertical_bias="0.96"
    app:layout_constraintWidth_percent="0.24"
    app:progress_badge_title="@string/medals_earned"
    app:progress_bar_background_color="@color/progress_bar_background_default"
    app:progress_bar_foreground_color="@color/progress_bar_default_color"
    app:progress_text_color="@color/progress_bar_background_course_header" />

The xml layout for the ProgressBadgeWidget is below:

<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
tools:parentTag="com.trala.learn.violin.view.core.widgets.ProgressBadgeWidget">

<TextView
    android:id="@+id/badge_title"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:fontFamily="@font/avenir_family"
    android:gravity="center"
    android:letterSpacing="-0.04"
    android:textColor="@color/courses_badge_text_color"
    android:textSize="12sp"
    app:lineHeight="16sp"
    app:layout_constraintBottom_toTopOf="@id/badge_image"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"

    />

<com.trala.learn.violin.view.core.widgets.EZColorProgressBar
    android:id="@+id/progress_badge_widget_progress_bar"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHeight_percent="0.10"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintWidth_percent="0.90"
    tools:progress="50" />

<ImageView
    android:id="@+id/badge_image"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintEnd_toEndOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintStart_toStartOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintTop_toTopOf="@id/progress_badge_widget_progress_bar"
    app:layout_constraintWidth_percent="0.27"
    tools:src="@drawable/trophy_gold" />

<TextView
    android:id="@+id/progress_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/avenir_family"
    android:textColor="@color/courses_badge_text_color"
    android:textSize="12sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/badge_image"
    tools:text="4/7" />

Pretty simple, as described before. Main part is the EZColorProgressBar, which is a subclassed ProgressBar just providing ways to change bar colors and a method to set progress and max:

 class EZColorProgressBar @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.progressBarStyleHorizontal, defStyleRes: Int = 0):
            ProgressBar(context, attrs, defStyleAttr, defStyleRes) {

fun setProgressNumbers(currentCount: Int, totalCount: Int) {
        if (currentCount > totalCount) Timber.d("Current Badge Count > Total Badge Count")

        val shouldShowBadges = currentCount >= totalCount && (currentCount != 0 && totalCount != 0)
        showBadge(shouldShowBadges)

        viewBinding?.progressBadgeWidgetProgressBar?.setMax(totalCount)
        viewBinding?.progressBadgeWidgetProgressBar?.setProgress(currentCount)
        viewBinding?.progressText?.setText(String.format(context.getString(R.string.score_string), currentCount, totalCount))

      }
}

I use the ProgressBadgeWidget and EZProgressBar on almost all of my Fragments. When I go between fragments and navigate backwards, the progress bars are not always showing their numbers correctly, ie the first time 0/5 will show correctly, then navigating to other pages that use this EZProgressBar and navigate back will show 1/5 even if the text has 0/5.

First navigation:

After: data model backing progress bar is correct (you can see from the 0/5 being correct). Looks like it's applying the 3/11 from the other progress bar

When this happens it actually applies the incorrect progress bar numbers to all progress bars in the layout (ie every progress bar in all items of item_level in the recyclerview adapter and even in a separate fragment so it's not tied to the recyclerview.) But again all of the text "x/x" shows correctly.

I've tried using kotlin synthetics bindings and google view bindings. It feels like the separate instances of the progress bars (they are separate as I've printed out the hashcodes) they are pointing at the same progress bar because it's searching for views based on IDs. The ProgressBadgeWidgets have unique ID's but their nested progress bars have the same IDs.

Has anyone come across issues like this and/or specifically with Android Progress Bars?

Body:
If anyone comes upon an issue with multiple progress bars not updating properly, seems there is a big Android bug related to this. Way to solve it is to explicitly change/reset the max and progress values before setting to your correct numbers. I added these methods to my custom progress bar:

fun setProgressSafely(progress: Int) {
    setProgress(progress + 1)
    setProgress(progress)
}

fun setMaxSafely(max: Int) {
    setMax(max + 1)
    setMax(max)
}


来源: stackexchange

问:
Linear and bilinear constraint with Gurobi
Looking at Gurobi's expamples for programs, there is one for QCPs, and one for bilinear programs, and I was wondering how to add a constraint that is linear and bilinear (sorry if there's specific jargon for such a problem) in R (or any other language, if easier, but I am using R). Specifically, how would I add a matrix of constraints of the form (for example) that

xz + y - yz < c

where c is some constant. I think I could use mccormick relaxation to re-write this as a linear program (right?), but I was wondering if Gurobi has easy syntax for such constraints?

My current understanding of the syntax for QCPs and bilinear programs is that you use a sparse matrix construction of the form

And so you cannot refer to x,y,z on their own..

答: Figured it out. In case anyone else comes across a similar issue, you create a quadcon list and add it to the model, as described here. For an illustration of using quadcon, it is quite similar to quadratic constraints in this example, though this example is not explicitly of the type of constraint I asked about.</p>

ContentLicense: CC BY-SA 4.0


问:
PHP MySQLi not working anymore after upgrade to Ubuntu 20.04
I do have php7.4-mysql installed, the error is here below and the rest is in the title

PHP Fatal error:  Uncaught Error: Class 'mysqli' not found in {long_path}/index.php:9\nStack trace:\n#0 {main}\n  thrown in {long_path}/index.php on line 9

Is there a solution to this or do I have to reinstall and reconfigure everything (which means I will just downgrade to Ubuntu 18.04 again via backups)?

答:
I had the same problem after an update today. I figured something was messed up so I tried to remove it

```<code>apt remove php-mysqli
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'php7.4-mysql' instead of 'php-mysqli'
0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.
</code>```

I then tried a purge, and install exact same result.

Finally, apt-get dist-upgrade fixed my problem.

You can see the upgrade left my system is a weird state that wasn't fully flushed out.

```<code>apt-get dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages were automatically installed and are no longer required:
  apt-show-versions libapt-pkg-perl libauthen-pam-perl libimagequant0 libio-pty-perl libnet-ssleay-perl libpython-all-dev libpython2-dev
  libpython2.7-dev libwebpdemux2 perl-openssl-defaults python-all python-all-dev python-automat python-certifi python-configparser python-constantly
  python-crypto python-dbus python-entrypoints python-gi python-hyperlink python-keyring python-olefile python-pil python-xdg python2-dev python2.7-dev
  python3-scour scour
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
  libapache2-mod-php7.2 libapache2-mod-php7.3 libpcre2-posix0 libpython-dev libpython-stdlib minecraft-overviewer php7.2 php7.3 python python-click
  python-colorama python-configobj python-dev python-incremental python-keyrings.alt python-minimal python-pip python-requests python-scour
  python-secretstorage python-serial python-twisted-bin python-twisted-core python-urllib3 python-wheel webmin
The following NEW packages will be installed:
  libapache2-mod-php7.4 libpcre2-posix2 php7.4
The following packages have been kept back:
  libomp-dev
The following packages will be upgraded:
  libapache2-mod-php libpcre2-16-0 libpcre2-32-0 libpcre2-8-0 libpcre2-dev libpython-all-dev libpython2-dev libpython2-stdlib php python-all
  python-all-dev python-pip-whl python2 python2-dev python2-minimal python3-pip
16 upgraded, 3 newly installed, 26 to remove and 1 not upgraded.
Need to get 2,675 kB/4,704 kB of archives.
After this operation, 196 MB disk space will be freed.
Do you want to continue? [Y/n] y
</code>```

After that I refreshed my page and it was working again.

Hopefully this helps and you are not alone.

Body:
I had the same problem after an update today. I figured something was messed up so I tried to remove it

apt remove php-mysqli
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'php7.4-mysql' instead of 'php-mysqli'
0 upgraded, 0 newly installed, 0 to remove and 19 not upgraded.

I then tried a purge, and install exact same result.

Finally, apt-get dist-upgrade fixed my problem.

You can see the upgrade left my system is a weird state that wasn't fully flushed out.

apt-get dist-upgrade
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following packages were automatically installed and are no longer required:
  apt-show-versions libapt-pkg-perl libauthen-pam-perl libimagequant0 libio-pty-perl libnet-ssleay-perl libpython-all-dev libpython2-dev
  libpython2.7-dev libwebpdemux2 perl-openssl-defaults python-all python-all-dev python-automat python-certifi python-configparser python-constantly
  python-crypto python-dbus python-entrypoints python-gi python-hyperlink python-keyring python-olefile python-pil python-xdg python2-dev python2.7-dev
  python3-scour scour
Use 'apt autoremove' to remove them.
The following packages will be REMOVED:
  libapache2-mod-php7.2 libapache2-mod-php7.3 libpcre2-posix0 libpython-dev libpython-stdlib minecraft-overviewer php7.2 php7.3 python python-click
  python-colorama python-configobj python-dev python-incremental python-keyrings.alt python-minimal python-pip python-requests python-scour
  python-secretstorage python-serial python-twisted-bin python-twisted-core python-urllib3 python-wheel webmin
The following NEW packages will be installed:
  libapache2-mod-php7.4 libpcre2-posix2 php7.4
The following packages have been kept back:
  libomp-dev
The following packages will be upgraded:
  libapache2-mod-php libpcre2-16-0 libpcre2-32-0 libpcre2-8-0 libpcre2-dev libpython-all-dev libpython2-dev libpython2-stdlib php python-all
  python-all-dev python-pip-whl python2 python2-dev python2-minimal python3-pip
16 upgraded, 3 newly installed, 26 to remove and 1 not upgraded.
Need to get 2,675 kB/4,704 kB of archives.
After this operation, 196 MB disk space will be freed.
Do you want to continue? [Y/n] y

After that I refreshed my page and it was working again.

Hopefully this helps and you are not alone.


问:
How to insert manual line breaks inside LaTeX tables?
I know that if you define a width in a table's column, you can get automatic word-wrapping.
However, I need to control where newlines should happen in a specific table cell.

Thus, how can I insert manual line breaks in a LaTeX table cell?

答: \newline works to break a line within a cell in tabularx environment.</p>

ContentLicense: CC BY-SA 2.5


问:
Loading a PNG using SDL2 + SDL2Image using C++ and cmake on Ubuntu
I'm working on a simple tutorial from here: https://lazyfoo.net/tutorials/SDL/02_getting_an_image_on_the_screen/index.php

My initial program did not do any image loading. It just showed a screen and went away. Everything worked fine. Here is my initial CMakeLists.txt file:

```<code>cmake_minimum_required(VERSION 3.7)
project(01_hello_world)

set(CXX_STANDARD 17)

find_package(SDL2 REQUIRED)

add_executable(hello 01_hello_SDL.cpp)
target_include_directories(hello PRIVATE ${SDL2_INCLUDE_DIRS})
target_link_libraries(hello ${SDL2_LIBRARIES})
</code>```

Everything worked and compiled just fine. However, I then wanted to load a PNG image, which I thought would be a very easy. Googling led me to the SDL2 Image library, and the IMG_Load method. So I went ahead and installed libsdl2-image-dev, and my CMakeLists.txt file grew by two more lines::

```<code>set(SDL2IMAGE_INCLUDE_DIRS ${SDL2_INCLUDE_DIRS})
set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")
</code>```

However, just by using the IMG_Load method, the make command threw a whole bunch of library requirements: libtiff-dev, libpng-dev, libjpeg-dev, libwebp-dev. All this just to load a png file! So I went ahead and installed all those, and now my CMakeLists.txt file looks like this abomination (I used find_package where I could, and manually set variables where I couldn't):

```<code>cmake_minimum_required(VERSION 3.7)
project(01_hello_world)

set(CXX_STANDARD 17)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
find_package(SDL2 REQUIRED)
find_package(PNG REQUIRED)
find_package(JPEG REQUIRED)
find_package(TIFF REQUIRED)

set(SDL2IMAGE_INCLUDE_DIRS ${SDL2_INCLUDE_DIRS})
set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")
set(WEBP_LIBRARIES "/usr/lib/x86_64-linux-gnu/libwebp.a")

add_executable(hello 01_hello_SDL.cpp)
target_include_directories(hello PRIVATE ${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS} ${PNG_INCLUDE_DIRS})
target_link_libraries(hello ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES} ${PNG_LIBRARY} ${JPEG_LIBRARY} ${WEBP_LIBRARIES} ${TIFF_LIBRARIES} Threads::Threads)
</code>```

At this point, when I make, I get this error:

```<code>[ 50%] Linking CXX executable hello
/usr/bin/ld: cannot find -l{TIFF_LIBRARIES}
collect2: error: ld returned 1 exit status
CMakeFiles/hello.dir/build.make:98: recipe for target 'hello' failed
make[2]: *** [hello] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/hello.dir/all' failed
make[1]: *** [CMakeFiles/hello.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2
</code>```

I've been googling for hours. Can someone provide a light in this darkness?

Also is this the correct approach to working with sdl + cmake?

答:
```<code>set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")
</code>```

It seems like you aren't dynamically linking SDL2_image to your program.
I don't know how to change it in CMake,but you could compile your program utilizing this pattern:

```<code>g++ your_program.cpp -o your_program -lSDL2 -lSDL2_image
</code>```

You may also utilize a Makefile like this one:

```<code>OBJS = your_program.cpp

OBJ_NAME = your_program_output

all:
    g++ $(OBJS) -o $(OBJ_NAME) -lSDL2 -lSDL2_image # don't forget about replacing the four spaces by a tab character
</code>```

One last thing, lazy foo has a tutorial teaching how to install and set up the SDL2_image library on linux utilizing an IDE (Code::Blocks) or not (command lines and Makefiles).
http://lazyfoo.net/tutorials/SDL/06_extension_libraries_and_loading_other_image_formats/linux/index.php

Body:
I'm working on a simple tutorial from here: https://lazyfoo.net/tutorials/SDL/02_getting_an_image_on_the_screen/index.php

My initial program did not do any image loading. It just showed a screen and went away. Everything worked fine. Here is my initial CMakeLists.txt file:

cmake_minimum_required(VERSION 3.7)
project(01_hello_world)

set(CXX_STANDARD 17)

find_package(SDL2 REQUIRED)

add_executable(hello 01_hello_SDL.cpp)
target_include_directories(hello PRIVATE ${SDL2_INCLUDE_DIRS})
target_link_libraries(hello ${SDL2_LIBRARIES})

Everything worked and compiled just fine. However, I then wanted to load a PNG image, which I thought would be a very easy. Googling led me to the SDL2 Image library, and the IMG_Load method. So I went ahead and installed libsdl2-image-dev, and my CMakeLists.txt file grew by two more lines::

set(SDL2IMAGE_INCLUDE_DIRS ${SDL2_INCLUDE_DIRS})
set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")

However, just by using the IMG_Load method, the make command threw a whole bunch of library requirements: libtiff-dev, libpng-dev, libjpeg-dev, libwebp-dev. All this just to load a png file! So I went ahead and installed all those, and now my CMakeLists.txt file looks like this abomination (I used find_package where I could, and manually set variables where I couldn't):

cmake_minimum_required(VERSION 3.7)
project(01_hello_world)

set(CXX_STANDARD 17)

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED)
find_package(SDL2 REQUIRED)
find_package(PNG REQUIRED)
find_package(JPEG REQUIRED)
find_package(TIFF REQUIRED)

set(SDL2IMAGE_INCLUDE_DIRS ${SDL2_INCLUDE_DIRS})
set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")
set(WEBP_LIBRARIES "/usr/lib/x86_64-linux-gnu/libwebp.a")

add_executable(hello 01_hello_SDL.cpp)
target_include_directories(hello PRIVATE ${SDL2_INCLUDE_DIRS} ${SDL2IMAGE_INCLUDE_DIRS} ${PNG_INCLUDE_DIRS})
target_link_libraries(hello ${SDL2_LIBRARIES} ${SDL2IMAGE_LIBRARIES} ${PNG_LIBRARY} ${JPEG_LIBRARY} ${WEBP_LIBRARIES} ${TIFF_LIBRARIES} Threads::Threads)

At this point, when I make, I get this error:

[ 50%] Linking CXX executable hello
/usr/bin/ld: cannot find -l{TIFF_LIBRARIES}
collect2: error: ld returned 1 exit status
CMakeFiles/hello.dir/build.make:98: recipe for target 'hello' failed
make[2]: *** [hello] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/hello.dir/all' failed
make[1]: *** [CMakeFiles/hello.dir/all] Error 2
Makefile:83: recipe for target 'all' failed
make: *** [all] Error 2

I've been googling for hours. Can someone provide a light in this darkness?

Also is this the correct approach to working with sdl + cmake?

Body:
set(SDL2IMAGE_LIBRARIES "/usr/lib/x86_64-linux-gnu/libSDL2_image.a")

It seems like you aren't dynamically linking SDL2_image to your program.
I don't know how to change it in CMake,but you could compile your program utilizing this pattern:

g++ your_program.cpp -o your_program -lSDL2 -lSDL2_image

You may also utilize a Makefile like this one:

OBJS = your_program.cpp

OBJ_NAME = your_program_output

all:
    g++ $(OBJS) -o $(OBJ_NAME) -lSDL2 -lSDL2_image # don't forget about replacing the four spaces by a tab character

One last thing, lazy foo has a tutorial teaching how to install and set up the SDL2_image library on linux utilizing an IDE (Code::Blocks) or not (command lines and Makefiles).
http://lazyfoo.net/tutorials/SDL/06_extension_libraries_and_loading_other_image_formats/linux/index.php


问:
R get the means for all columns in a data frame while ignoring zeroes
I have a dataframe with columns of simulation data.
I want the means of each column.
The issue is some columns have a bunch of zeroes on the bottom and these need to be ignored.

I can ignore the zeroes and look at one column with

```<code>mean(which(df$colname >0))
</code>```

But I want a vector of every column's mean, gotten with sapply.
Is there a clean way to ignore the zeroes and get these values within a sapply function?

Or do I have to write a custom function and call that in the sapply?

答:
We can use an one-liner in base R

```<code>colMeans(replace(df, !df, NA), na.rm = TRUE)
</code>```

Or with dplyr

```<code>library(dplyr)
df %>%
   summarise(across(everything(), ~ mean(na_if(., 0), na.rm = TRUE))
</code>```

Body:
I have a dataframe with columns of simulation data.
I want the means of each column.
The issue is some columns have a bunch of zeroes on the bottom and these need to be ignored.

I can ignore the zeroes and look at one column with

mean(which(df$colname >0))

But I want a vector of every column's mean, gotten with sapply.
Is there a clean way to ignore the zeroes and get these values within a sapply function?

Or do I have to write a custom function and call that in the sapply?

Body:
We can use an one-liner in base R

colMeans(replace(df, !df, NA), na.rm = TRUE)

Or with dplyr

library(dplyr)
df %>%
   summarise(across(everything(), ~ mean(na_if(., 0), na.rm = TRUE))


问:
User-switchable custom themes with Vue.js
I have a VueJS app that will come with many different themes (at least 20 or so). Each theme stylesheet not only changes things like color and font size, but also the position and layout of some elements as well.

I want the user to be able to switch between these themes dynamically. So, at runtime, the user will be able to open an Options menu and select from a dropdown.

What is the cleanest way to have many dynamic user-selectable themes in VueJS?

I've thought of a couple of ways, such as:

Dynamically inserting a <link> or

答:
Today I found possibly the simplest way to solve this and it even works with SCSS (no need to have separate CSS for each theme, which is important if your themes are based on one library and you only want to define the changes), but it needs

Make an .scss/.css file for each theme

Make these available somewhere in the src folder, src/bootstrap-themes/dark.scss for example

Import the .scss with a condition in the App.vue, in the created:, for example

```<code>if (Vue.$cookies.get('darkmode') === 'true') {
     import('../bootstrap-themes/dark.scss');
     this.nightmode = true;
} else {
     import('../bootstrap-themes/light.scss');
     this.nightmode = false;
}
</code>```

When the user lands on the page, I read the cookies and see if they left nightmode enabled when they left last time and load the correct scss

When they use the switch to change the theme, this method is called, which saves the cookie and reloads the page, which will then read the cookie and load the correct scss

```<code>setTheme(nightmode) {
     this.$cookies.set("darkmode", nightmode, "7d")
     this.$router.go()
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Today I found possibly the simplest way to solve this and it even works with SCSS (no need to have separate CSS for each theme, which is important if your themes are based on one library and you only want to define the changes), but it needs

Make an .scss/.css file for each theme

Make these available somewhere in the src folder, src/bootstrap-themes/dark.scss for example

Import the .scss with a condition in the App.vue, in the created:, for example

if (Vue.$cookies.get('darkmode') === 'true') {
     import('../bootstrap-themes/dark.scss');
     this.nightmode = true;
} else {
     import('../bootstrap-themes/light.scss');
     this.nightmode = false;
}

When the user lands on the page, I read the cookies and see if they left nightmode enabled when they left last time and load the correct scss

When they use the switch to change the theme, this method is called, which saves the cookie and reloads the page, which will then read the cookie and load the correct scss

setTheme(nightmode) {
     this.$cookies.set("darkmode", nightmode, "7d")
     this.$router.go()
}


问:
Add birthday field to WooCommerce my account and admin user page
I have added the code below. The birthday field is showing in my account page and also in WP admin user page as well but the problem is that the date is not saving.

What I have so far

function iconic_get_account_fields() {
return apply_filters( 'iconic_account_fields', array(
    'user_url' => array(
        'type'        => 'date',
        'label'       => __( 'My Birth Date', 'iconic' ),
        'placeholder' => __( 'Date of Birth', 'iconic' ),
        'required'    => true,
    ),
) );
}
/**
* Add fields to registration form and account area.

*/
function iconic_print_user_frontend_fields() {
$fields = iconic_get_account_fields();

foreach ( $fields as $key => $field_args ) {
    woocommerce_form_field( $key, $field_args );
}
}
add_action( 'woocommerce_edit_account_form', 'iconic_print_user_frontend_fields', 10 ); // my account

 /**
 * Add fields to admin area.
 */
function iconic_print_user_admin_fields() {
$fields = iconic_get_account_fields();
?>

<?php _e( 'Additional Information', 'iconic' ); ?>

    <?php foreach ( $fields as $key => $field_args ) { ?>

                <label for="<?php echo $key; ?>"><?php echo $field_args['label']; ?>

                <?php $field_args['label'] = false; ?>
                <?php woocommerce_form_field( $key, $field_args ); ?>

    <?php } ?>

 <?php
 }

 add_action( 'show_user_profile', 'iconic_print_user_admin_fields', 30 ); // admin: edit profile
 add_action( 'edit_user_profile', 'iconic_print_user_admin_fields', 30 ); // admin: edit other users
```

I use the code partly from:

The Ultimate Guide to Adding Custom WooCommerce Registration Fields

答:
The following code will add (and save) a custom birthday field to

My account - edit account

Admin user page - profile

// Add field - my account
function action_woocommerce_edit_account_form() {
    woocommerce_form_field( 'birthday_field', array(
        'type'        => 'date',
        'label'       => __( 'My Birth Date', 'woocommerce' ),
        'placeholder' => __( 'Date of Birth', 'woocommerce' ),
        'required'    => true,
    ), get_user_meta( get_current_user_id(), 'birthday_field', true ));
}
add_action( 'woocommerce_edit_account_form', 'action_woocommerce_edit_account_form' );

// Validate - my account
function action_woocommerce_save_account_details_errors( $args ){
    if ( isset($_POST['birthday_field']) && empty($_POST['birthday_field']) ) {
        $args->add( 'error', __( 'Please provide a birth date', 'woocommerce' ) );
    }
}
add_action( 'woocommerce_save_account_details_errors','action_woocommerce_save_account_details_errors', 10, 1 );

// Save - my account
function action_woocommerce_save_account_details( $user_id ) {
    if( isset($_POST['birthday_field']) && ! empty($_POST['birthday_field']) ) {
        update_user_meta( $user_id, 'birthday_field', sanitize_text_field($_POST['birthday_field']) );
    }
}
add_action( 'woocommerce_save_account_details', 'action_woocommerce_save_account_details', 10, 1 );

// Add field - admin
function add_user_birtday_field( $user ) {
    ?>

<?php _e('Birthday','woocommerce' ); ?>

                <?php _e( 'Date of Birth', 'woocommerce' ); ?>
                <input type="date" name="birthday_field" value="<?php echo esc_attr( get_the_author_meta( 'birthday_field', $user->ID )); ?>" class="regular-text" />

    <?php
}
add_action( 'show_user_profile', 'add_user_birtday_field', 10, 1 );
add_action( 'edit_user_profile', 'add_user_birtday_field', 10, 1 );

// Save field - admin
function save_user_birtday_field( $user_id ) {
    if( ! empty($_POST['birthday_field']) ) {
        update_user_meta( $user_id, 'birthday_field', sanitize_text_field( $_POST['birthday_field'] ) );
    }
}
add_action( 'personal_options_update', 'save_user_birtday_field', 10, 1 );
add_action( 'edit_user_profile_update', 'save_user_birtday_field', 10, 1 );
```

Body:
I have added the code below. The birthday field is showing in my account page and also in WP admin user page as well but the problem is that the date is not saving.

What I have so far

function iconic_get_account_fields() {
return apply_filters( 'iconic_account_fields', array(
    'user_url' => array(
        'type'        => 'date',
        'label'       => __( 'My Birth Date', 'iconic' ),
        'placeholder' => __( 'Date of Birth', 'iconic' ),
        'required'    => true,
    ),
) );
}
/**
* Add fields to registration form and account area.

*/
function iconic_print_user_frontend_fields() {
$fields = iconic_get_account_fields();

foreach ( $fields as $key => $field_args ) {
    woocommerce_form_field( $key, $field_args );
}
}
add_action( 'woocommerce_edit_account_form', 'iconic_print_user_frontend_fields', 10 ); // my account

 /**
 * Add fields to admin area.
 */
function iconic_print_user_admin_fields() {
$fields = iconic_get_account_fields();
?>

<?php _e( 'Additional Information', 'iconic' ); ?>

    <?php foreach ( $fields as $key => $field_args ) { ?>

                <label for="<?php echo $key; ?>"><?php echo $field_args['label']; ?>

                <?php $field_args['label'] = false; ?>
                <?php woocommerce_form_field( $key, $field_args ); ?>

    <?php } ?>

 <?php
 }

 add_action( 'show_user_profile', 'iconic_print_user_admin_fields', 30 ); // admin: edit profile
 add_action( 'edit_user_profile', 'iconic_print_user_admin_fields', 30 ); // admin: edit other users

I use the code partly from:

The Ultimate Guide to Adding Custom WooCommerce Registration Fields

Body:
The following code will add (and save) a custom birthday field to

My account - edit account

Admin user page - profile

// Add field - my account
function action_woocommerce_edit_account_form() {
    woocommerce_form_field( 'birthday_field', array(
        'type'        => 'date',
        'label'       => __( 'My Birth Date', 'woocommerce' ),
        'placeholder' => __( 'Date of Birth', 'woocommerce' ),
        'required'    => true,
    ), get_user_meta( get_current_user_id(), 'birthday_field', true ));
}
add_action( 'woocommerce_edit_account_form', 'action_woocommerce_edit_account_form' );

// Validate - my account
function action_woocommerce_save_account_details_errors( $args ){
    if ( isset($_POST['birthday_field']) && empty($_POST['birthday_field']) ) {
        $args->add( 'error', __( 'Please provide a birth date', 'woocommerce' ) );
    }
}
add_action( 'woocommerce_save_account_details_errors','action_woocommerce_save_account_details_errors', 10, 1 );

// Save - my account
function action_woocommerce_save_account_details( $user_id ) {
    if( isset($_POST['birthday_field']) && ! empty($_POST['birthday_field']) ) {
        update_user_meta( $user_id, 'birthday_field', sanitize_text_field($_POST['birthday_field']) );
    }
}
add_action( 'woocommerce_save_account_details', 'action_woocommerce_save_account_details', 10, 1 );

// Add field - admin
function add_user_birtday_field( $user ) {
    ?>
        <h3><?php _e('Birthday','woocommerce' ); ?></h3>
        <table class="form-table">
            <tr>
                <th><label for="birthday_field"><?php _e( 'Date of Birth', 'woocommerce' ); ?></label></th>
                <td><input type="date" name="birthday_field" value="<?php echo esc_attr( get_the_author_meta( 'birthday_field', $user->ID )); ?>" class="regular-text" /></td>
            </tr>
        </table>
        <br />
    <?php
}
add_action( 'show_user_profile', 'add_user_birtday_field', 10, 1 );
add_action( 'edit_user_profile', 'add_user_birtday_field', 10, 1 );

// Save field - admin
function save_user_birtday_field( $user_id ) {
    if( ! empty($_POST['birthday_field']) ) {
        update_user_meta( $user_id, 'birthday_field', sanitize_text_field( $_POST['birthday_field'] ) );
    }
}
add_action( 'personal_options_update', 'save_user_birtday_field', 10, 1 );
add_action( 'edit_user_profile_update', 'save_user_birtday_field', 10, 1 );


问:
Unable to connect to Apache Ignite (jdbc) through LB in AWS EKS
I am trying to connect to an Apache Ignite (2.8.0)  deployed on Kubernetes Cluster. The cluster itself seems fine, as i am able to exec into the pods and access via sqlline tool as shown below

```<code>root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin# kubectl exec -it ignite-cluster-6d69696b67-8vvmm /bin/bash

bash-4.4# apache-ignite/bin/sqlline.sh --verbose=true -u jdbc:ignite:thin://127.0.0.1:10800/
issuing: !connect jdbc:ignite:thin://127.0.0.1:10800/ '' '' org.apache.ignite.IgniteJdbcThinDriver
Connecting to jdbc:ignite:thin://127.0.0.1:10800/
Connected to: Apache Ignite (version 2.8.0#20200226-sha1:341b01df)
Driver: Apache Ignite Thin JDBC Driver (version 2.8.0#20200226-sha1:341b01df)
Autocommit status: true
Transaction isolation: TRANSACTION_REPEATABLE_READ
sqlline version 1.3.0
0: jdbc:ignite:thin://127.0.0.1:10800/>
</code>```

However if i try connecting from the external LB it gives the following error.

```<code>root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin/bin# ./sqlline.sh --verbose=true -u jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800
issuing: !connect jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800 '' '' org.apache.ignite.IgniteJdbcThinDriver
Connecting to jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800
Error: Failed to connect to server [url=jdbc:ignite:thin://weiury734ry34ry34urt.us-east-1.elb.amazonaws.com:10800/PUBLIC] (state=08001,code=0)
java.sql.SQLException: Failed to connect to server [url=jdbc:ignite:thin://abc123.us-east-1.elb.amazonaws.com:10800/PUBLIC]
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.handleConnectExceptions(JdbcThinConnection.java:1529)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1506)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.ensureConnected(JdbcThinConnection.java:231)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.<init>(JdbcThinConnection.java:210)
        at org.apache.ignite.IgniteJdbcThinDriver.connect(IgniteJdbcThinDriver.java:154)
        at sqlline.DatabaseConnection.connect(DatabaseConnection.java:156)
        at sqlline.DatabaseConnection.getConnection(DatabaseConnection.java:204)
        at sqlline.Commands.connect(Commands.java:1095)
        at sqlline.Commands.connect(Commands.java:1001)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sqlline.ReflectiveCommandHandler.execute(ReflectiveCommandHandler.java:38)
        at sqlline.SqlLine.dispatch(SqlLine.java:791)
        at sqlline.SqlLine.initArgs(SqlLine.java:566)
        at sqlline.SqlLine.begin(SqlLine.java:643)
        at sqlline.SqlLine.start(SqlLine.java:373)
        at sqlline.SqlLine.main(SqlLine.java:265)
        Suppressed: java.io.IOException: Failed to read incoming message (not enough data).
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:546)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:524)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.handshake(JdbcThinTcpIo.java:266)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.<init>(JdbcThinTcpIo.java:212)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1477)
                ... 17 more
        Suppressed: java.io.IOException: Failed to read incoming message (not enough data).
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:546)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:524)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.handshake(JdbcThinTcpIo.java:266)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.<init>(JdbcThinTcpIo.java:212)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1477)
                ... 17 more
sqlline version 1.3.0

</code>```

Interestingly telnet to the port via LB says connected as shown below.

```<code>root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin/bin# telnet abc-123.us-east-1.elb.amazonaws.com 10800
Trying 3.209.73.243...
Connected to abc-123.us-east-1.elb.amazonaws.com.
Escape character is '^]'.
Connection closed by foreign host.
</code>```

Why is it not able to connect via jdbc client even though telnet works on port 10800?
I also tried to connect via DBeaver, but the error is the same.

Here are the service and deployment yaml used in Kubernetes EKS Deployment.

Ignite-service.yaml

```<code>apiVersion: v1
kind: Service
metadata:
  name: ignite
  namespace: default
  labels:
    app: ignite
spec:
  type: LoadBalancer
  ports:
    - name: rest
      port: 8080
      protocol: TCP
      targetPort: 8080
    - name: sql
      port: 10800
      protocol: TCP
      targetPort: 10800
    - name: thinclients
      port: 10900
      protocol: TCP
      targetPort: 10900
  selector:
    app: ignite
</code>```

Ignite-deployment.yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: ignite-cluster
  namespace: default
spec:
  selector:
    matchLabels:
      app: ignite
  replicas: 2
  template:
    metadata:
      labels:
        app: ignite
    spec:
      serviceAccount: ignite
      containers:
      - name: ignite-node
        image: apacheignite/ignite:2.8.0
        env:
        - name: OPTION_LIBS
          value: ignite-kubernetes
        - name: CONFIG_URI
          value: https://raw.githubusercontent.com/apache/ignite/master/modules/kubernetes/config/example-kube.xml
        ports:
        - containerPort: 11211 # REST port number.
        - containerPort: 47100 # communication SPI port number.
        - containerPort: 47500 # discovery SPI port number.
        - containerPort: 49112 # JMX port number.
        - containerPort: 10800 # SQL port number.
</code>```

答:
check the service itself:  kubectl describe services my-service

https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#finding-your-ip-address

make sure an external IP is provided and works.

Restrict K8 to one pod and re-try.

Set the externalTrafficPolicy and the pod selector

```<code>externalTrafficPolicy: Local
  selector:
    statefulset.kubernetes.io/pod-name: pod-name
</code>```

https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#preserving-the-client-source-ip

https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-name-label

A thin client needs to communicate to a specific pod/server

Check the server logs to make sure that data is flowing.

Body:
I am trying to connect to an Apache Ignite (2.8.0)  deployed on Kubernetes Cluster. The cluster itself seems fine, as i am able to exec into the pods and access via sqlline tool as shown below

root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin# kubectl exec -it ignite-cluster-6d69696b67-8vvmm /bin/bash

bash-4.4# apache-ignite/bin/sqlline.sh --verbose=true -u jdbc:ignite:thin://127.0.0.1:10800/
issuing: !connect jdbc:ignite:thin://127.0.0.1:10800/ '' '' org.apache.ignite.IgniteJdbcThinDriver
Connecting to jdbc:ignite:thin://127.0.0.1:10800/
Connected to: Apache Ignite (version 2.8.0#20200226-sha1:341b01df)
Driver: Apache Ignite Thin JDBC Driver (version 2.8.0#20200226-sha1:341b01df)
Autocommit status: true
Transaction isolation: TRANSACTION_REPEATABLE_READ
sqlline version 1.3.0
0: jdbc:ignite:thin://127.0.0.1:10800/>

However if i try connecting from the external LB it gives the following error.

root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin/bin# ./sqlline.sh --verbose=true -u jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800
issuing: !connect jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800 '' '' org.apache.ignite.IgniteJdbcThinDriver
Connecting to jdbc:ignite:thin://abc-123.us-east-1.elb.amazonaws.com:10800
Error: Failed to connect to server [url=jdbc:ignite:thin://weiury734ry34ry34urt.us-east-1.elb.amazonaws.com:10800/PUBLIC] (state=08001,code=0)
java.sql.SQLException: Failed to connect to server [url=jdbc:ignite:thin://abc123.us-east-1.elb.amazonaws.com:10800/PUBLIC]
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.handleConnectExceptions(JdbcThinConnection.java:1529)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1506)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.ensureConnected(JdbcThinConnection.java:231)
        at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.<init>(JdbcThinConnection.java:210)
        at org.apache.ignite.IgniteJdbcThinDriver.connect(IgniteJdbcThinDriver.java:154)
        at sqlline.DatabaseConnection.connect(DatabaseConnection.java:156)
        at sqlline.DatabaseConnection.getConnection(DatabaseConnection.java:204)
        at sqlline.Commands.connect(Commands.java:1095)
        at sqlline.Commands.connect(Commands.java:1001)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at sqlline.ReflectiveCommandHandler.execute(ReflectiveCommandHandler.java:38)
        at sqlline.SqlLine.dispatch(SqlLine.java:791)
        at sqlline.SqlLine.initArgs(SqlLine.java:566)
        at sqlline.SqlLine.begin(SqlLine.java:643)
        at sqlline.SqlLine.start(SqlLine.java:373)
        at sqlline.SqlLine.main(SqlLine.java:265)
        Suppressed: java.io.IOException: Failed to read incoming message (not enough data).
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:546)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:524)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.handshake(JdbcThinTcpIo.java:266)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.<init>(JdbcThinTcpIo.java:212)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1477)
                ... 17 more
        Suppressed: java.io.IOException: Failed to read incoming message (not enough data).
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:546)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.read(JdbcThinTcpIo.java:524)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.handshake(JdbcThinTcpIo.java:266)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinTcpIo.<init>(JdbcThinTcpIo.java:212)
                at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.connectInCommonMode(JdbcThinConnection.java:1477)
                ... 17 more
sqlline version 1.3.0

Interestingly telnet to the port via LB says connected as shown below.

root@ip-172-17-28-68:/opt/apache-ignite-2.8.0-bin/bin# telnet abc-123.us-east-1.elb.amazonaws.com 10800
Trying 3.209.73.243...
Connected to abc-123.us-east-1.elb.amazonaws.com.
Escape character is '^]'.
Connection closed by foreign host.

Why is it not able to connect via jdbc client even though telnet works on port 10800?
I also tried to connect via DBeaver, but the error is the same.

Here are the service and deployment yaml used in Kubernetes EKS Deployment.

Ignite-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: ignite
  namespace: default
  labels:
    app: ignite
spec:
  type: LoadBalancer
  ports:
    - name: rest
      port: 8080
      protocol: TCP
      targetPort: 8080
    - name: sql
      port: 10800
      protocol: TCP
      targetPort: 10800
    - name: thinclients
      port: 10900
      protocol: TCP
      targetPort: 10900
  selector:
    app: ignite

Ignite-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: ignite-cluster
  namespace: default
spec:
  selector:
    matchLabels:
      app: ignite
  replicas: 2
  template:
    metadata:
      labels:
        app: ignite
    spec:
      serviceAccount: ignite
      containers:
      - name: ignite-node
        image: apacheignite/ignite:2.8.0
        env:
        - name: OPTION_LIBS
          value: ignite-kubernetes
        - name: CONFIG_URI
          value: https://raw.githubusercontent.com/apache/ignite/master/modules/kubernetes/config/example-kube.xml
        ports:
        - containerPort: 11211 # REST port number.
        - containerPort: 47100 # communication SPI port number.
        - containerPort: 47500 # discovery SPI port number.
        - containerPort: 49112 # JMX port number.
        - containerPort: 10800 # SQL port number.

Body:
check the service itself:  kubectl describe services my-service

https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#finding-your-ip-address

make sure an external IP is provided and works.

Restrict K8 to one pod and re-try.

Set the externalTrafficPolicy and the pod selector

externalTrafficPolicy: Local
  selector:
    statefulset.kubernetes.io/pod-name: pod-name

https://kubernetes.io/docs/tasks/access-application-cluster/create-external-load-balancer/#preserving-the-client-source-ip

https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#pod-name-label

A thin client needs to communicate to a specific pod/server

Check the server logs to make sure that data is flowing.


问:
Java: Handling ' - ' character in custom component text field
I have a custom text field that only accepts numbers in it.

Everything works fine except when I try to handle the negative (-) sign.

```<code>public void processKeyEvent(KeyEvent ev) {

   char c = ev.getKeyChar();
   [...]

   if(c == '-' && getDocument().getLength() > 0 ){
      ev.consume();
   }else{
      super.processKeyEvent(ev);
   }
}
</code>```

This works fine when I start with the sign - but not when I already have numbers and want to add a - in front.

What I really need is a way to get the position at which this character is inserted but I can't find that.

Any ideas?

答: If your control is a TextComponent or derived from that, you could try using the getCaretPosition method to check whether or not the input is being typed at the start of the text.

Body:
I have a custom text field that only accepts numbers in it.

Everything works fine except when I try to handle the negative (-) sign.

public void processKeyEvent(KeyEvent ev) {

   char c = ev.getKeyChar();
   [...]

   if(c == '-' && getDocument().getLength() > 0 ){
      ev.consume();
   }else{
      super.processKeyEvent(ev);
   }
}

This works fine when I start with the sign - but not when I already have numbers and want to add a - in front.

What I really need is a way to get the position at which this character is inserted but I can't find that.

Any ideas?


问:
Different results trying to solve the same problem using for and while loops in python
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)
</code>```

While Loop Code

```<code>glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)
</code>```

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

答:
You while loop loops over idexes. The for loop over values. You use the values to index back into the list.

Fix:

```<code>glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:      # these are the VALUES of the list, not indexes
    if i<0:
        total3 += i   # simply add up the values
print(total3)         # -13 for the win
</code>```

fixes it.

It is sheer luck that your numbers all work as indexes into your list as well - try adding a 99 and you'll get an IndexError.

Short version:

```<code>print( sum( i for i in [7,5,4,4,2,1,1,-2,-2,-4,-5] if i < 0) )

# or if you want to confuse people:
print( sum( i * (i<0) for i in [7,5,4,4,2,1,1,-2,-2,-4,-5]) )
</code>```

Body:
Hi! I am new to coding and was trying to solve I tried to solve a problem that required me to sum all of the negative integers in a list using loops. I tried to solve the problem using both for and while loops but got different answers.

For Loop Code

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:
    if glist3[i]<0:
        total3+=glist3[i]
print(total3)

While Loop Code

glist4 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
i2=0
total4=0
while i2 < len(glist4):
    if glist4[i2] < 0:
        total4+=glist4[i2]
    i2+=1
print (total4)

The Result I got for the for loop is -12 (which is incorrect), but the while loop did give back the correct answer which is -13. Just wanted to ask for possible causes for this discrepancy. Thank you!

Body:
You while loop loops over idexes. The for loop over values. You use the values to index back into the list.

Fix:

glist3 = [7,5,4,4,2,1,1,-2,-2,-4,-5]
total3=0
for i in glist3:      # these are the VALUES of the list, not indexes
    if i<0:
        total3 += i   # simply add up the values
print(total3)         # -13 for the win

fixes it.

It is sheer luck that your numbers all work as indexes into your list as well - try adding a 99 and you'll get an IndexError.

Short version:

print( sum( i for i in [7,5,4,4,2,1,1,-2,-2,-4,-5] if i < 0) )

# or if you want to confuse people:
print( sum( i * (i<0) for i in [7,5,4,4,2,1,1,-2,-2,-4,-5]) )


问:
reactjs: setState being called twice in a function called once? why?
EDIT: since the code snip does not reproduce the bug - here is a link to the github repo: (code is far FAR from complete)

https://github.com/altruios/clicker-game

I have run it on two computers now - both with the same behavior the code snip doesn't show.

//interestingly enough, this works just fine, where the same code I run locally has the doubling.
//when I comment out ALL other code except for this code I STILL get the error locally
//at this point the only difference is import export of components... here they are in one file.
//below is original code from file (
/*
FILE::::Clicker.js

import React from 'react';

function Clicker(props)
 {
 return(

  {props.name}
  <button
   name={props.name}
   onClick={props.HandleClick}
   data-target={props.subjectsOfIncrease}>
    {props.name} {props.value}

  </button>

  )
}

export default Clicker;

FILE:: Resouce.js

import React from 'react';
function Resource(props)
 {
 return(

  {props.name} and  {props.amount || 0}

  )
}

export default Resource;

*/
//besides the import/export and seprate files - code is the same. it works in here, does not work locally on my machine.

const gameData = {
  clickerData: [{
    name: "grey",
    subjectsOfIncrease: ["grey"],
    isUnlocked: true,
    value: 1
  }],
  resourceData: [{
    name: "grey",
    resouceMax: 100,
    isUnlocked: true,
    changePerTick: 0,
    counterTillStopped: 100,
    amount: 0
  }]
}
class App extends React.Component {
    constructor() {
      super();
      this.state = {
        resources: gameData.resourceData,
        clickers: gameData.clickerData
      };
      this.gainResource = this.gainResource.bind(this);
    }
    gainResource(event) {
      console.count("gain button");
      const name = event.target.name;
      this.setState((prevState) => {
        const newResources = prevState.resources.map(resource => {
          if (resource.name === name) {
            resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
          }
          return resource;
        });
        console.log(prevState.resources.find(item => item.name === name).amount, "old");
        console.log(newResources.find(item => item.name === name).amount, "new");
        return {
          resources: newResources
        }
      });
    }
    render() {
      const resources = this.state.resources.map(resourceData => {
          return (
            <Resource
              name = {resourceData.name}
              resouceMax = {resourceData.resourceMax}
              isUnlocked = {resourceData.isUnlocked}
              changePerTick = {resourceData.changePerTick}
              counterTillStopped = {resourceData.countTillStopped}
              amount = {resourceData.amount}
              key = {resourceData.name}
            />
          )
      })

      const clickers = this.state.clickers.map(clickerData => {
          return (
            <Clicker
              name = {clickerData.name}
              HandleClick = {this.gainResource}
              value = {clickerData.amount}
              key = {clickerData.name}
            />
          )
    })

    return (

            {resources}
           {clickers}

   )
 }
}
function Resource(props) {
      return
  {props.name} and {props.amount || 0}

}

function Clicker(props) {
      return (

 {props.name}
          <button name = {props.name}  onClick = {props.HandleClick}>
            {props.name} {props.value}
          </button>

     )
}
const root = document.getElementById('root');
ReactDOM.render(  <App / >,root );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

so I'm building a clicker game to learn react, and something I don't understand why this code is behaving the way it does:

in the main app I have this function:

```<code>
  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
        if(resource.name === name)
          {
          resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return resource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }
</code>```

that console.count runs a single time... but I get 2 'old and new' pairs. as if setState is running twice in this function which only runs once?

the console.output is:

```<code>App.js:64 gain button: 1
App.js:76 1 "old"
App.js:77 1 "new"
App.js:76 2 "old"
App.js:77 2 "new"
</code>```

so it looks like the function is running once. but the set state is being run twice?

the symptoms are that it counts up by 2. but also the initial state of amount is 0, not 1, as seen in the gamedata.json

```<code>    resourceData:
        [
            {
            name:"grey",
            resouceMax:100,
            isUnlocked:true,
            changePerTick:0,
            counterTillStopped:100,
            amount:0
            },{etc},{},{}],
        clickerData:
        [
            {
            name:"grey",
            subjectsOfIncrease:["grey"],
            isUnlocked:true,
            value:1
           },{etc},{},{}]

</code>```

i don't think the rest of the code I'm about to most is relevant to this behavior, but I don't know react yet, so I don't know what I'm missing: but this is how I'm generating the clicker button:

```<code>const clickers = this.state.clickers.map(clickerData=>
      {
      return(
        <Clicker
          name={clickerData.name}
          HandleClick = {this.gainResource}
          value = {clickerData.amount}
          key={clickerData.name}

        />

        )
    })

</code>```

and in the clicker.js functional component I'm just returning this:

```<code>        <div>
        {props.name}
        <button name={props.name} onClick={props.HandleClick}>
                {props.name} {props.value}
        </button>
        </div>

</code>```

the function is bound to this in the constructor... I don't understand why this is running setState twice inside a function that's called once.

I've also tried:

```<code>
        <div>
        {props.name}
        <button name={props.name} onClick={()=>props.HandleClick}> //anon function results in no output
                {props.name} {props.value}
        </button>
        </div>
</code>```

答:
BEST ANSWER:

I was using create-react-app. and my App Component was wrapped in Strict mode... which fires setState twice... which perfectly explains why this was not reproducible on the code snip, and why the function was being called once, yet setState  was called twice.

removing strict mode fixed the issue completely.

Body:
EDIT: since the code snip does not reproduce the bug - here is a link to the github repo: (code is far FAR from complete)

https://github.com/altruios/clicker-game

I have run it on two computers now - both with the same behavior the code snip doesn't show.

//interestingly enough, this works just fine, where the same code I run locally has the doubling.
//when I comment out ALL other code except for this code I STILL get the error locally
//at this point the only difference is import export of components... here they are in one file.
//below is original code from file (
/*
FILE::::Clicker.js

import React from 'react';

function Clicker(props)
 {
 return(

  {props.name}
  <button
   name={props.name}
   onClick={props.HandleClick}
   data-target={props.subjectsOfIncrease}>
    {props.name} {props.value}

  </button>

  )
}

export default Clicker;

FILE:: Resouce.js

import React from 'react';
function Resource(props)
 {
 return(

  {props.name} and  {props.amount || 0}

  )
}

export default Resource;

*/
//besides the import/export and seprate files - code is the same. it works in here, does not work locally on my machine.

const gameData = {
  clickerData: [{
    name: "grey",
    subjectsOfIncrease: ["grey"],
    isUnlocked: true,
    value: 1
  }],
  resourceData: [{
    name: "grey",
    resouceMax: 100,
    isUnlocked: true,
    changePerTick: 0,
    counterTillStopped: 100,
    amount: 0
  }]
}
class App extends React.Component {
    constructor() {
      super();
      this.state = {
        resources: gameData.resourceData,
        clickers: gameData.clickerData
      };
      this.gainResource = this.gainResource.bind(this);
    }
    gainResource(event) {
      console.count("gain button");
      const name = event.target.name;
      this.setState((prevState) => {
        const newResources = prevState.resources.map(resource => {
          if (resource.name === name) {
            resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
          }
          return resource;
        });
        console.log(prevState.resources.find(item => item.name === name).amount, "old");
        console.log(newResources.find(item => item.name === name).amount, "new");
        return {
          resources: newResources
        }
      });
    }
    render() {
      const resources = this.state.resources.map(resourceData => {
          return (
            <Resource
              name = {resourceData.name}
              resouceMax = {resourceData.resourceMax}
              isUnlocked = {resourceData.isUnlocked}
              changePerTick = {resourceData.changePerTick}
              counterTillStopped = {resourceData.countTillStopped}
              amount = {resourceData.amount}
              key = {resourceData.name}
            />
          )
      })

      const clickers = this.state.clickers.map(clickerData => {
          return (
            <Clicker
              name = {clickerData.name}
              HandleClick = {this.gainResource}
              value = {clickerData.amount}
              key = {clickerData.name}
            />
          )
    })

    return (

            {resources}
           {clickers}

   )
 }
}
function Resource(props) {
      return
  {props.name} and {props.amount || 0}

}

function Clicker(props) {
      return (

 {props.name}
          <button name = {props.name}  onClick = {props.HandleClick}>
            {props.name} {props.value}
          </button>

     )
}
const root = document.getElementById('root');
ReactDOM.render(  <App / >,root );

so I'm building a clicker game to learn react, and something I don't understand why this code is behaving the way it does:

in the main app I have this function:

  gainResource(event)
    {
    console.count("gain button");
    const name = event.target.name;
    this.setState( (prevState)=>
      {
      const newResources =  prevState.resources.map(resource=>
        {
        if(resource.name === name)
          {
          resource.amount = Number(resource.amount) + 1 //Number(prevState.clickers.find(x=>x.name===name).value)
        }
        return resource;
      });
      console.log(prevState.resources.find(item=>item.name===name).amount, "old");
      console.log(newResources.find(item=>item.name===name).amount, "new");
      return {resources: newResources}
    });
  }

that console.count runs a single time... but I get 2 'old and new' pairs. as if setState is running twice in this function which only runs once?

the console.output is:

App.js:64 gain button: 1
App.js:76 1 "old"
App.js:77 1 "new"
App.js:76 2 "old"
App.js:77 2 "new"

so it looks like the function is running once. but the set state is being run twice?

the symptoms are that it counts up by 2. but also the initial state of amount is 0, not 1, as seen in the gamedata.json

    resourceData:
        [
            {
            name:"grey",
            resouceMax:100,
            isUnlocked:true,
            changePerTick:0,
            counterTillStopped:100,
            amount:0
            },{etc},{},{}],
        clickerData:
        [
            {
            name:"grey",
            subjectsOfIncrease:["grey"],
            isUnlocked:true,
            value:1
           },{etc},{},{}]

i don't think the rest of the code I'm about to most is relevant to this behavior, but I don't know react yet, so I don't know what I'm missing: but this is how I'm generating the clicker button:

const clickers = this.state.clickers.map(clickerData=>
      {
      return(
        <Clicker
          name={clickerData.name}
          HandleClick = {this.gainResource}
          value = {clickerData.amount}
          key={clickerData.name}

        />

        )
    })

and in the clicker.js functional component I'm just returning this:

        {props.name}
        <button name={props.name} onClick={props.HandleClick}>
                {props.name} {props.value}
        </button>

the function is bound to this in the constructor... I don't understand why this is running setState twice inside a function that's called once.

I've also tried:

        {props.name}
        <button name={props.name} onClick={()=>props.HandleClick}> //anon function results in no output
                {props.name} {props.value}
        </button>


问:
Scala spark: Access value in a struct in an array-typed column? (Or, access member of anonymous struct-typed column)
I have a dataframe that has a column which is an array of structs, like:

```<code>+-----+-----+------------------+---+----+
|index|state|entries           |0  |1   |
+-----+-----+------------------+---+----+
|0    |KY   |[[A, 45]]         |45 |null|
|1    |OR   |[[A, 30], [B, 10]]|30 |10  |
+-----+-----+------------------+---+----+
</code>```

where "Entries" are structs with two fields, "name" and "number". I want to be able to grab one of those inner values at a particular index.

One way I could do this is:

```<code>df.withColumn(col("entries").getItem(0), "dumbName").select("dumbName.name")
</code>```

I want to be able to do this with anonymous columns, though, so it would look more like

col("entries").getItem(0).someMagicFunction("name")

答:
getItem works as magic function:

df.select(col("entries").getItem(0).getItem("Name")).show()
```

<p>prints</p>

<pre class="lang-none prettyprint-override"><code>+---------------+
|entries[0].Name|
+---------------+
|              A|
|              A|
+---------------+
</code>```

It is also possible to use element_at from the functions object  (available since 2.4.0):

df.select(element_at('entries, 1).getItem("Name")).show()
```

<p>prints</p>

<pre class="lang-none prettyprint-override"><code>+---------------------------+
|element_at(entries, 1).Name|
+---------------------------+
|                          A|
|                          A|
+---------------------------+
</code>```

For earlier Spark versions it would be possible to use SQL:

df.createOrReplaceGlobalTempView("df")
spark.sql("select entries[0].name from global_temp.df").show()
```

Body:
I have a dataframe that has a column which is an array of structs, like:

+-----+-----+------------------+---+----+
|index|state|entries           |0  |1   |
+-----+-----+------------------+---+----+
|0    |KY   |[[A, 45]]         |45 |null|
|1    |OR   |[[A, 30], [B, 10]]|30 |10  |
+-----+-----+------------------+---+----+

where "Entries" are structs with two fields, "name" and "number". I want to be able to grab one of those inner values at a particular index.

One way I could do this is:

df.withColumn(col("entries").getItem(0), "dumbName").select("dumbName.name")

I want to be able to do this with anonymous columns, though, so it would look more like

col("entries").getItem(0).someMagicFunction("name")

Body:
getItem works as magic function:

df.select(col("entries").getItem(0).getItem("Name")).show()

prints

+---------------+
|entries[0].Name|
+---------------+
|              A|
|              A|
+---------------+

It is also possible to use element_at from the functions object  (available since 2.4.0):

df.select(element_at('entries, 1).getItem("Name")).show()

prints

+---------------------------+
|element_at(entries, 1).Name|
+---------------------------+
|                          A|
|                          A|
+---------------------------+

For earlier Spark versions it would be possible to use SQL:

df.createOrReplaceGlobalTempView("df")
spark.sql("select entries[0].name from global_temp.df").show()


问:
"Unable to determine aws-region" when running on-premises Cloudwatch agent
I'm trying to configure the AWS Cloudwatch agent to run on vanilla Ubuntu 18.04, outside of AWS. Every time I run it, I get this error:

```<code># /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m onPremise -c "file:/path/to/cloudwatch/cloudwatch.json" -s
/opt/aws/amazon-cloudwatch-agent/bin/config-downloader --output-dir /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d --download-source file:/path/to/cloudwatch/cloudwatch.json --mode onPrem --config /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml --multi-config default
Got Home directory: /root
I! Set home dir Linux: /root
Unable to determine aws-region.
Please make sure the credentials and region set correctly on your hosts.
Refer to http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
Fail to fetch the config!
</code>```

Running the program under strace -f reveals that it is trying to read /root/.aws/credentials and then exiting. Per the guide, here are the contents of /root/.aws/credentials:

```<code>[AmazonCloudWatchAgent]
aws_access_key_id = key
aws_secret_access_key = secret
region = us-west-2
</code>```

If I run aws configure get region, it is able to retrieve the region correctly. However, the Cloudwatch Agent is unable to read it. Here's the contents of common-config.toml (which also gets read, per strace).

```<code>## Configuration for shared credential.
## Default credential strategy will be used if it is absent here:
##  Instance role is used for EC2 case by default.
##  AmazonCloudWatchAgent profile is used for onPremise case by default.
[credentials]
   shared_credential_profile = "AmazonCloudWatchAgent"
   shared_credential_file = "/root/.aws/credentials"

## Configuration for proxy.
## System-wide environment-variable will be read if it is absent here.
## i.e. HTTP_PROXY/http_proxy; HTTPS_PROXY/https_proxy; NO_PROXY/no_proxy
## Note: system-wide environment-variable is not accessible when using ssm run-command.
## Absent in both here and environment-variable means no proxy will be used.
# [proxy]
#    http_proxy = "{http_url}"
#    https_proxy = "{https_url}"
#    no_proxy = "{domain}"
</code>```

Here are other things I have tried:

enclosing region (and all values) in the configuration in double quotes, per https://forums.aws.amazon.com/thread.jspa?threadID=291589. This did not make a difference.

adding /home/myuser/.aws/config, /home/myuser/.aws/credentials, and /root/.aws/config and populating them with the appropriate values. Per strace these files are not being read.

searching for the source code for the CloudWatch Agent (it is not open source)

setting AWS_REGION=us-west-2 explicitly in the program environment (same error)

changing [AmazonCloudWatchAgent] to [profile AmazonCloudWatchAgent] everywhere and all permutations of the above (no difference)

adding a [default] section in all config files (makes no difference)

invoking the config-downloader program directly, setting AWS_REGION etc. (same error)

becoming a non-root user and then invoking the program using sudo instead of invoking the program as the root user without sudo.

I get the same error no matter what I try. I installed the CloudWatch agent by downloading the "latest" deb on March 23, 2020, per these instructions. https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/download-cloudwatch-agent-commandline.html

答:
The aws config defaults to C:\Users\Administrator instead of the user you installed the CloudWatch Agent as. So you may need to move the /.aws/ folder to the CLoudWatch user. Or...more straightforward:

```<code>aws configure --profile AmazonCloudWatchAgent
</code>```

as described here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html#install-CloudWatch-Agent-iam_user-first

You can also specify the region using common-config.toml as described here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html#CloudWatch-Agent-profile-instance-first

On a server running Windows Server, this file is in the C:\ProgramData\Amazon\AmazonCloudWatchAgent directory. The default common-config.toml is as follows:

```<code># This common-config is used to configure items used for both ssm and cloudwatch access

## Configuration for shared credential.
## Default credential strategy will be used if it is absent here:
##            Instance role is used for EC2 case by default.
##            AmazonCloudWatchAgent profile is used for onPremise case by default.
# [credentials]
#    shared_credential_profile = "{profile_name}"
#    shared_credential_file= "{file_name}"

## Configuration for proxy.
## System-wide environment-variable will be read if it is absent here.
## i.e. HTTP_PROXY/http_proxy; HTTPS_PROXY/https_proxy; NO_PROXY/no_proxy
## Note: system-wide environment-variable is not accessible when using ssm run-command.
## Absent in both here and environment-variable means no proxy will be used.
# [proxy]
#    http_proxy = "{http_url}"
#    https_proxy = "{https_url}"
#    no_proxy = "{domain}"
</code>```

You can also update the common-config.toml with a new location if needed.

Body:
I'm trying to configure the AWS Cloudwatch agent to run on vanilla Ubuntu 18.04, outside of AWS. Every time I run it, I get this error:

# /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m onPremise -c "file:/path/to/cloudwatch/cloudwatch.json" -s
/opt/aws/amazon-cloudwatch-agent/bin/config-downloader --output-dir /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d --download-source file:/path/to/cloudwatch/cloudwatch.json --mode onPrem --config /opt/aws/amazon-cloudwatch-agent/etc/common-config.toml --multi-config default
Got Home directory: /root
I! Set home dir Linux: /root
Unable to determine aws-region.
Please make sure the credentials and region set correctly on your hosts.
Refer to http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html
Fail to fetch the config!

Running the program under strace -f reveals that it is trying to read /root/.aws/credentials and then exiting. Per the guide, here are the contents of /root/.aws/credentials:

[AmazonCloudWatchAgent]
aws_access_key_id = key
aws_secret_access_key = secret
region = us-west-2

If I run aws configure get region, it is able to retrieve the region correctly. However, the Cloudwatch Agent is unable to read it. Here's the contents of common-config.toml (which also gets read, per strace).

## Configuration for shared credential.
## Default credential strategy will be used if it is absent here:
##  Instance role is used for EC2 case by default.
##  AmazonCloudWatchAgent profile is used for onPremise case by default.
[credentials]
   shared_credential_profile = "AmazonCloudWatchAgent"
   shared_credential_file = "/root/.aws/credentials"

## Configuration for proxy.
## System-wide environment-variable will be read if it is absent here.
## i.e. HTTP_PROXY/http_proxy; HTTPS_PROXY/https_proxy; NO_PROXY/no_proxy
## Note: system-wide environment-variable is not accessible when using ssm run-command.
## Absent in both here and environment-variable means no proxy will be used.
# [proxy]
#    http_proxy = "{http_url}"
#    https_proxy = "{https_url}"
#    no_proxy = "{domain}"

Here are other things I have tried:

enclosing region (and all values) in the configuration in double quotes, per https://forums.aws.amazon.com/thread.jspa?threadID=291589. This did not make a difference.

adding /home/myuser/.aws/config, /home/myuser/.aws/credentials, and /root/.aws/config and populating them with the appropriate values. Per strace these files are not being read.

searching for the source code for the CloudWatch Agent (it is not open source)

setting AWS_REGION=us-west-2 explicitly in the program environment (same error)

changing [AmazonCloudWatchAgent] to [profile AmazonCloudWatchAgent] everywhere and all permutations of the above (no difference)

adding a [default] section in all config files (makes no difference)

invoking the config-downloader program directly, setting AWS_REGION etc. (same error)

becoming a non-root user and then invoking the program using sudo instead of invoking the program as the root user without sudo.

I get the same error no matter what I try. I installed the CloudWatch agent by downloading the "latest" deb on March 23, 2020, per these instructions. https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/download-cloudwatch-agent-commandline.html

Body:
The aws config defaults to C:\Users\Administrator instead of the user you installed the CloudWatch Agent as. So you may need to move the /.aws/ folder to the CLoudWatch user. Or...more straightforward:

aws configure --profile AmazonCloudWatchAgent

as described here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html#install-CloudWatch-Agent-iam_user-first

You can also specify the region using common-config.toml as described here: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html#CloudWatch-Agent-profile-instance-first

On a server running Windows Server, this file is in the C:\ProgramData\Amazon\AmazonCloudWatchAgent directory. The default common-config.toml is as follows:

# This common-config is used to configure items used for both ssm and cloudwatch access

## Configuration for shared credential.
## Default credential strategy will be used if it is absent here:
##            Instance role is used for EC2 case by default.
##            AmazonCloudWatchAgent profile is used for onPremise case by default.
# [credentials]
#    shared_credential_profile = "{profile_name}"
#    shared_credential_file= "{file_name}"

## Configuration for proxy.
## System-wide environment-variable will be read if it is absent here.
## i.e. HTTP_PROXY/http_proxy; HTTPS_PROXY/https_proxy; NO_PROXY/no_proxy
## Note: system-wide environment-variable is not accessible when using ssm run-command.
## Absent in both here and environment-variable means no proxy will be used.
# [proxy]
#    http_proxy = "{http_url}"
#    https_proxy = "{https_url}"
#    no_proxy = "{domain}"

You can also update the common-config.toml with a new location if needed.


问:
Parsing string to protobuf enum with no case-sensitivy
With C++ API, Enum_Parse() seems to be case sensitive, is there way to make it ignore case? With the enum definition at the bottom, Enum_Parse accepts "Http", but it rejects "http". I have searched enum related options in the link below, but did not find one about this.

https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto

```<code>enum MyEnum
{
    Tcp = 0;
    Http = 1;
    Https = 2;
}
</code>```

答:
If its possible for you to rename enums to the small case like this -

```<code>enum MyEnum
{
    tcp = 0;
    http = 1;
    https = 2;
}
</code>```

Then you could convert the input string to the small case first and then use Enum_Parse()

Body:
With C++ API, Enum_Parse() seems to be case sensitive, is there way to make it ignore case? With the enum definition at the bottom, Enum_Parse accepts "Http", but it rejects "http". I have searched enum related options in the link below, but did not find one about this.

https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/descriptor.proto

enum MyEnum
{
    Tcp = 0;
    Http = 1;
    Https = 2;
}

Body:
If its possible for you to rename enums to the small case like this -

enum MyEnum
{
    tcp = 0;
    http = 1;
    https = 2;
}

Then you could convert the input string to the small case first and then use Enum_Parse()


问:
Is there a way I can configure Netlify Forms in my React App to send both me and the user an email?
I am looking to configure Netlify forms, or at least have a front end solution only that acts similar to Contact Form 7 in WordPress where when a form is submitted it will go to both me and the person who submitted it.

Is this possible in Netlify and if not, which solutions do you recommend. (Front End/Client Side only please)

答:
Not currently.

You could instead create a Netlify/AWS/Azure serverless function to handle your form submissions and route emails via Sendgrid. You would be able to send any emails you wanted in response to a form submission then.


问:
Send huge data bytes approx 1000 MB from Module A to Module B in Azure IoT Edge
I need to send a huge data bytes approx 1000 MB from Module A to Module B in Azure IoT Edge. (Module A and Module B are in same edge device)
Message Routes allows max 262143 bytes and Direct method allows approx 160 KB. Is there any other options to send huge data bytes between modules, Performance is a primary concern and I do not want to split the data and send it as a chunks.

Thanks

答:
Edge routing is not the only way for modules to communicate. Afterall these are docker containers and there is nothing preventing you from implementing your own TCP link between two of them. Since docker provides a virtual network with a DNS server you will also be able to avoid any variation in IP addresses of your containers. You can look up the container's address by name and, by default, the container will use docker's DNS service to do that thus you will be able to resolve it to an IP address. All Azure IoT Edge modules except edgeAgent run on a docker network called azure-iot-edge. You would need to implement the code to move the data. You could do this from scratch or perhaps you could use a predefined protocol such as ftp or scp. You also need to consider that, unless you take steps to secure this transfer, it will not be encrypted (something Edge does do for you when routing).

I'm not suggesting this is going to give you the best performance. I am simply offering you other avenues for your research.


问:
How to eliminate elements with certain characters or phrases from a list in python?
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

```<code>def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)
</code>```

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.

答:
This should do it:

```<code>import re
new = []
test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
for s in test_list:
    for n in s.split():
        if n == re.sub(r'[^\w\s]','',n) and n.lower() != 'a' and n.lower() != 'the': # Adds word to new list if word is not 'a', 'the', and doesn't contain punctuations
            new.append(n)
print(list(set(new))) # Convert to a set to remove duplicates, then back to alis
</code>```

Output:

```<code>['Pumpkin']
</code>```

Body:
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.

Body:
This should do it:

import re
new = []
test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
for s in test_list:
    for n in s.split():
        if n == re.sub(r'[^\w\s]','',n) and n.lower() != 'a' and n.lower() != 'the': # Adds word to new list if word is not 'a', 'the', and doesn't contain punctuations
            new.append(n)
print(list(set(new))) # Convert to a set to remove duplicates, then back to alis

Output:

['Pumpkin']


问:
How to create a seperate dataframe of rows that contain NaN with pandas
Is it possible to create a new dataFrame using pandas that contains any row that has NaN in any column from an existing datafram to be reviewed by a person?

I'm able to get rows that contain NaN in a specific column with:
    df_nan = df[pd.isna(df["sales_person"])]

but is there a way to do this without having to list out each column name?

答:
This works:</p>

```<code>>>> import pandas as pd
>>> import numpy as np
>>>
>>> #making fake data, we want rows 0 and 1 to be output
>>> df = pd.DataFrame()
>>> df['Col1'] = [1,np.nan,4,1,10]
>>> df['Col2'] = [np.nan,3,4,5,1]
>>>
>>> nas = df.apply(pd.isnull, axis=1) #boolean dataframe showing np.nan positions
>>> any_nas = nas.any(axis=1)         #rows where there are any True values
>>> only_nas = df[any_nas].copy()     #original dataframe sliced by the rows with True values
>>>
>>> print(df.head());
   Col1  Col2
0   1.0   NaN
1   NaN   3.0
2   4.0   4.0
3   1.0   5.0
4  10.0   1.0

>>> print(only_nas.head())
   Col1  Col2
0   1.0   NaN
1   NaN   3.0
</code>```

Body:
This works:

>>> import pandas as pd
>>> import numpy as np
>>>
>>> #making fake data, we want rows 0 and 1 to be output
>>> df = pd.DataFrame()
>>> df['Col1'] = [1,np.nan,4,1,10]
>>> df['Col2'] = [np.nan,3,4,5,1]
>>>
>>> nas = df.apply(pd.isnull, axis=1) #boolean dataframe showing np.nan positions
>>> any_nas = nas.any(axis=1)         #rows where there are any True values
>>> only_nas = df[any_nas].copy()     #original dataframe sliced by the rows with True values
>>>
>>> print(df.head());
   Col1  Col2
0   1.0   NaN
1   NaN   3.0
2   4.0   4.0
3   1.0   5.0
4  10.0   1.0

>>> print(only_nas.head())
   Col1  Col2
0   1.0   NaN
1   NaN   3.0


问:
SwiftUI 2 View Models in a View
I have this view which takes as a param its own View Model. Inside this view I need to show another view which in order for it to be displayed, needs its own View Model. So I present the Purchase view and then inside the Purchase view I need to display the details of the actual item which was purchased. So I pass as a parameter also the ItemViewModel. Both PurchaseViewModel and ItemViewModel are used on other views also.

It could happen in the feature that I would also need ClientViewModel which would be used to display data about the actual buyer of this item. Does this mean that I would need to pass also @ObservedObject var clientViewModel: ClientViewModel as a parameter?

My question is: Is this approach good or there is a better way to do this ?

```<code>struct PurchaseView: View {
    @ObservedObject var purchaseViewModel: PurchaseViewModel
    @ObservedObject var itemViewModel: ItemViewModel

    var body: some View {
        VStack {
            Text(purchaseViewModel.title)
            ItemView(itemViewModel: itemViewModel)
        }
    }
}

class Purchase {
    let senderID: String
    let receiverID: String
    var status: PurchaseStatus
    var item: Item?
}
</code>```

答:
You could make the PurchaseViewModel contain the ItemViewModel and ClientViewModel as properties in the same way that the PurchaseView contains the ItemView and ClientView.

That would make PurchaseViewModel responsible for creating the instances of the other view models. The parent of PurchaseView would no longer need to know about the implementation of PurchaseView.

Title: SwiftUI 2 View Models in a View

Body:
I have this view which takes as a param its own View Model. Inside this view I need to show another view which in order for it to be displayed, needs its own View Model. So I present the Purchase view and then inside the Purchase view I need to display the details of the actual item which was purchased. So I pass as a parameter also the ItemViewModel. Both PurchaseViewModel and ItemViewModel are used on other views also.

It could happen in the feature that I would also need ClientViewModel which would be used to display data about the actual buyer of this item. Does this mean that I would need to pass also @ObservedObject var clientViewModel: ClientViewModel as a parameter?

My question is: Is this approach good or there is a better way to do this ?

struct PurchaseView: View {
    @ObservedObject var purchaseViewModel: PurchaseViewModel
    @ObservedObject var itemViewModel: ItemViewModel

    var body: some View {
        VStack {
            Text(purchaseViewModel.title)
            ItemView(itemViewModel: itemViewModel)
        }
    }
}

class Purchase {
    let senderID: String
    let receiverID: String
    var status: PurchaseStatus
    var item: Item?
}