Software Update does not work?

Question: By some reason software update does not work at all. When I try to update the system it starts and freeze for a long time.
Every time when I try to update or install some package I see the following messsages:
Results:` No apport report written because MaxReports is reached already
Errors were encountered while processing:
java-common
openjdk-8-jre-headless:amd64
update-notifier-common
flashplugin-installer
openjdk-8-jre:amd64
openjdk-8-jdk-headless:amd64
openjdk-8-jdk:amd64
update-notifier
update-manager
ubuntu-release-upgrader-gtk
ca-certificates-java E:
Sub-process /usr/bin/dpkg returned an error

Something wrong with my Java, but I do not know how to fix it.
Any ideas ?
I have tried "sudo apt update". The results are:
Hit:1 http://ua.archive.ubuntu.com/ubuntu xenial InRelease
Get:2 http://ua.archive.ubuntu.com/ubuntu xenial-updates InRelease [102 kB]
Get:3 http://security.ubuntu.com/ubuntu xenial-security InRelease [102 kB]
Get:4 http://ua.archive.ubuntu.com/ubuntu xenial-backports InRelease [102 kB]
Hit:5 http://ppa.launchpad.net/yannubuntu/boot-repair/ubuntu xenial InRelease
Get:6 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 Packages [472 kB]
Get:7 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main i386 Packages [463 kB]
Get:8 http://security.ubuntu.com/ubuntu xenial-security/main amd64 DEP-11 Metadata [68,0 kB]
Get:9 http://security.ubuntu.com/ubuntu xenial-security/main DEP-11 64x64 Icons [43,1 kB]
Get:10 http://security.ubuntu.com/ubuntu xenial-security/universe amd64 DEP-11 Metadata [32,1 kB]
Get:11 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 DEP-11 Metadata [305 kB]
Get:12 http://security.ubuntu.com/ubuntu xenial-security/universe DEP-11 64x64 Icons [37,0 kB]
Get:13 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main DEP-11 64x64 Icons [192 kB]
Get:14 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 Packages [397 kB]
Get:15 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe i386 Packages [392 kB]
Get:16 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 DEP-11 Metadata [133 kB]
Get:17 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe DEP-11 64x64 Icons [162 kB]
Get:18 http://ua.archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 DEP-11 Metadata [2 520 B]
Get:19 http://ua.archive.ubuntu.com/ubuntu xenial-backports/main amd64 DEP-11 Metadata [3 328 B]
Fetched 3 009 kB in 1s (2 127 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
32 packages can be upgraded. Run 'apt list --upgradable' to see them.

I have tried "sudo apt upgrade". The results are:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Calculating upgrade... Done
The following package was automatically installed and is no longer required:
  ubuntu-core-launcher
Use 'sudo apt autoremove' to remove it.
The following NEW packages will be installed:
  linux-headers-4.4.0-62 linux-headers-4.4.0-62-generic
  linux-image-4.4.0-62-generic linux-image-extra-4.4.0-62-generic
The following packages will be upgraded:
  bind9-host dnsutils flashplugin-installer gir1.2-javascriptcoregtk-4.0
  gir1.2-webkit2-4.0 libavcodec-ffmpeg56 libavfilter-ffmpeg5
  libavformat-ffmpeg56 libavresample-ffmpeg2 libavutil-ffmpeg54 libbind9-140
  libdns-export162 libdns162 libgc1c2 libisc-export160 libisc160 libisccc140
  libisccfg140 libjavascriptcoregtk-4.0-18 liblwres141 libpostproc-ffmpeg53
  libssh2-1 libswresample-ffmpeg1 libswscale-ffmpeg3 libwebkit2gtk-4.0-37
  libwebkit2gtk-4.0-37-gtk2 linux-generic linux-headers-generic
  linux-image-generic snap-confine snapd ubuntu-core-launcher
32 upgraded, 4 newly installed, 0 to remove and 0 not upgraded.
11 not fully installed or removed.
Need to get 108 MB of archives.
After this operation, 298 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 http://ua.archive.ubuntu.com/ubuntu xenial-updates/multiverse amd64 flashplugin-installer amd64 126.96.36.199ubuntu0.16.04.1 [6 812 B]
Get:2 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 gir1.2-webkit2-4.0 amd64 2.14.5-0ubuntu0.16.04.1 [64,2 kB]
Get:3 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 gir1.2-javascriptcoregtk-4.0 amd64 2.14.5-0ubuntu0.16.04.1 [21,5 kB]
Get:4 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libwebkit2gtk-4.0-37-gtk2 amd64 2.14.5-0ubuntu0.16.04.1 [8 316 kB]
Get:5 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libwebkit2gtk-4.0-37 amd64 2.14.5-0ubuntu0.16.04.1 [10,2 MB]
Get:6 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libjavascriptcoregtk-4.0-18 amd64 2.14.5-0ubuntu0.16.04.1 [3 710 kB]
Get:7 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 snapd amd64 2.22.2 [8 567 kB]
Get:8 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 ubuntu-core-launcher amd64 2.22.2 [1 580 B]
Get:9 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 snap-confine amd64 2.22.2 [41,6 kB]
Get:10 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libisc-export160 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [153 kB]
Get:11 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libdns-export162 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [665 kB]
Get:12 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 bind9-host amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [38,4 kB]
Get:13 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 dnsutils amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [88,9 kB]
Get:14 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libisc160 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [214 kB]
Get:15 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libdns162 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [877 kB]
Get:16 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libisccc140 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [16,2 kB]
Get:17 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libisccfg140 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [40,4 kB]
Get:18 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 liblwres141 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [33,5 kB]
Get:19 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libbind9-140 amd64 1:9.10.3.dfsg.P4-8ubuntu1.5 [23,6 kB]
Get:20 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libavresample-ffmpeg2 amd64 7:2.8.11-0ubuntu0.16.04.1 [51,9 kB]
Get:21 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libswresample-ffmpeg1 amd64 7:2.8.11-0ubuntu0.16.04.1 [51,7 kB]
Get:22 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libpostproc-ffmpeg53 amd64 7:2.8.11-0ubuntu0.16.04.1 [49,0 kB]
Get:23 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libswscale-ffmpeg3 amd64 7:2.8.11-0ubuntu0.16.04.1 [146 kB]
Get:24 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libavformat-ffmpeg56 amd64 7:2.8.11-0ubuntu0.16.04.1 [807 kB]
Get:25 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libavfilter-ffmpeg5 amd64 7:2.8.11-0ubuntu0.16.04.1 [530 kB]
Get:26 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libavcodec-ffmpeg56 amd64 7:2.8.11-0ubuntu0.16.04.1 [4 081 kB]
Get:27 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libavutil-ffmpeg54 amd64 7:2.8.11-0ubuntu0.16.04.1 [166 kB]
Get:28 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libgc1c2 amd64 1:7.4.2-7.3ubuntu0.1 [82,1 kB]
Get:29 http://ua.archive.ubuntu.com/ubuntu xenial-updates/universe amd64 libssh2-1 amd64 1.5.0-2ubuntu0.1 [70,2 kB]
Get:30 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-4.4.0-62-generic amd64 4.4.0-62.83 [21,3 MB]
Get:31 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-extra-4.4.0-62-generic amd64 4.4.0-62.83 [36,3 MB]
Get:32 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-generic amd64 188.8.131.52.65 [1 784 B]
Get:33 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-image-generic amd64 220.127.116.11.65 [2 290 B]
Get:34 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-4.4.0-62 all 4.4.0-62.83 [9 907 kB]
Get:35 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-4.4.0-62-generic amd64 4.4.0-62.83 [773 kB]
Get:36 http://ua.archive.ubuntu.com/ubuntu xenial-updates/main amd64 linux-headers-generic amd64 188.8.131.52.65 [2 256 B]
Fetched 108 MB in 43s (2 464 kB/s)
Extracting templates from packages: 100%
Preconfiguring packages ...
(Reading database ... 240302 files and directories currently installed.)
Preparing to unpack .../flashplugin-installer_22.214.171.124ubuntu0.16.04.1_amd64.deb ...
Unpacking flashplugin-installer (220.127.116.11ubuntu0.16.04.1) over (126.96.36.199ubuntu0.16.04.1) ...
Preparing to unpack .../gir1.2-webkit2-4.0_2.14.5-0ubuntu0.16.04.1_amd64.deb ...
Unpacking gir1.2-webkit2-4.0:amd64 (2.14.5-0ubuntu0.16.04.1) over (2.14.3-0ubuntu0.16.04.1) ...
Preparing to unpack .../gir1.2-javascriptcoregtk-4.0_2.14.5-0ubuntu0.16.04.1_amd64.deb ...
Unpacking gir1.2-javascriptcoregtk-4.0:amd64 (2.14.5-0ubuntu0.16.04.1) over (2.14.3-0ubuntu0.16.04.1) ...
Preparing to unpack .../libwebkit2gtk-4.0-37-gtk2_2.14.5-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libwebkit2gtk-4.0-37-gtk2:amd64 (2.14.5-0ubuntu0.16.04.1) over (2.14.3-0ubuntu0.16.04.1) ...
Preparing to unpack .../libwebkit2gtk-4.0-37_2.14.5-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libwebkit2gtk-4.0-37:amd64 (2.14.5-0ubuntu0.16.04.1) over (2.14.3-0ubuntu0.16.04.1) ...
Preparing to unpack .../libjavascriptcoregtk-4.0-18_2.14.5-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libjavascriptcoregtk-4.0-18:amd64 (2.14.5-0ubuntu0.16.04.1) over (2.14.3-0ubuntu0.16.04.1) ...
Preparing to unpack .../snapd_2.22.2_amd64.deb ...
Warning: Stopping snapd.service, but it can still be activated by:
  snapd.socket
Unpacking snapd (2.22.2) over (2.21) ...
Preparing to unpack .../ubuntu-core-launcher_2.22.2_amd64.deb ...
Unpacking ubuntu-core-launcher (2.22.2) over (2.21) ...
Preparing to unpack .../snap-confine_2.22.2_amd64.deb ...
Unpacking snap-confine (2.22.2) over (2.21) ...
Preparing to unpack .../libisc-export160_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libisc-export160 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libdns-export162_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libdns-export162 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../bind9-host_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking bind9-host (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../dnsutils_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking dnsutils (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libisc160_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libisc160:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libdns162_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libdns162:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libisccc140_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libisccc140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libisccfg140_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libisccfg140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../liblwres141_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking liblwres141:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libbind9-140_1%3a9.10.3.dfsg.P4-8ubuntu1.5_amd64.deb ...
Unpacking libbind9-140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) over (1:9.10.3.dfsg.P4-8ubuntu1.4) ...
Preparing to unpack .../libavresample-ffmpeg2_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libavresample-ffmpeg2:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libswresample-ffmpeg1_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libswresample-ffmpeg1:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libpostproc-ffmpeg53_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libpostproc-ffmpeg53:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libswscale-ffmpeg3_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libswscale-ffmpeg3:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libavformat-ffmpeg56_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libavformat-ffmpeg56:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libavfilter-ffmpeg5_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libavfilter-ffmpeg5:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libavcodec-ffmpeg56_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libavcodec-ffmpeg56:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libavutil-ffmpeg54_7%3a2.8.11-0ubuntu0.16.04.1_amd64.deb ...
Unpacking libavutil-ffmpeg54:amd64 (7:2.8.11-0ubuntu0.16.04.1) over (7:2.8.10-0ubuntu0.16.04.1) ...
Preparing to unpack .../libgc1c2_1%3a7.4.2-7.3ubuntu0.1_amd64.deb ...
Unpacking libgc1c2:amd64 (1:7.4.2-7.3ubuntu0.1) over (1:7.4.2-7.3) ...
Preparing to unpack .../libssh2-1_1.5.0-2ubuntu0.1_amd64.deb ...
Unpacking libssh2-1:amd64 (1.5.0-2ubuntu0.1) over (1.5.0-2) ...
Selecting previously unselected package linux-image-4.4.0-62-generic.
Preparing to unpack .../linux-image-4.4.0-62-generic_4.4.0-62.83_amd64.deb ...
Examining /etc/kernel/preinst.d/
run-parts: executing /etc/kernel/preinst.d/intel-microcode 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
Done.
Unpacking linux-image-4.4.0-62-generic (4.4.0-62.83) ...
Selecting previously unselected package linux-image-extra-4.4.0-62-generic.
Preparing to unpack .../linux-image-extra-4.4.0-62-generic_4.4.0-62.83_amd64.deb ...
Unpacking linux-image-extra-4.4.0-62-generic (4.4.0-62.83) ...
Preparing to unpack .../linux-generic_220.127.116.11.65_amd64.deb ...
Unpacking linux-generic (184.108.40.206.65) over (184.108.40.206.60) ...
Preparing to unpack .../linux-image-generic_126.96.36.199.65_amd64.deb ...
Unpacking linux-image-generic (220.127.116.11.65) over (220.127.116.11.60) ...
Selecting previously unselected package linux-headers-4.4.0-62.
Preparing to unpack .../linux-headers-4.4.0-62_4.4.0-62.83_all.deb ...
Unpacking linux-headers-4.4.0-62 (4.4.0-62.83) ...
Selecting previously unselected package linux-headers-4.4.0-62-generic.
Preparing to unpack .../linux-headers-4.4.0-62-generic_4.4.0-62.83_amd64.deb ...
Unpacking linux-headers-4.4.0-62-generic (4.4.0-62.83) ...
Preparing to unpack .../linux-headers-generic_220.127.116.11.65_amd64.deb ...
Unpacking linux-headers-generic (220.127.116.11.65) over (220.127.116.11.60) ...
Processing triggers for libc-bin (2.23-0ubuntu5) ...
Processing triggers for man-db (2.7.5-1) ...
Setting up java-common (0.56ubuntu2) ...
mkdir: cannot create directory '/etc/.java/.systemPrefs': File exists
dpkg: error processing package java-common (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of openjdk-8-jre-headless:amd64:
 openjdk-8-jre-headless:amd64 depends on java-common (>= 0.28); however:
  Package java-common is not configured yet.

dpkg: error processing package openjdk-8-jre-headless:amd64 (--configure):
 dependency problems - leaving unconfigured
Setting up update-notifier-common (3.168.3) ...
No apport report written because the error message indicates its a followup error from a previous failure.
                          Traceback (most recent call last):
  File "/usr/lib/update-notifier/package-data-downloader", line 24, in <module>
    import debian.deb822
ModuleNotFoundError: No module named 'debian'
dpkg: error processing package update-notifier-common (--configure):
 subprocess installed post-installation script returned error exit status 1
dpkg: dependency problems prevent configuration of flashplugin-installer:
 flashplugin-installer depends on update-notifier-common (>= 0.119ubuntu2); however:
  Package update-notifier-common is not configured yet.

dpkg: error processing package flashplugin-installer (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of openjdk-8-jre:amd64:
 openjdk-8-jre:amd64 depends on openjdk-8-jre-headless (= 8u121-b13-0ubuntu1.16.04.2); however:
  Package openjdk-8-jre-headless:amd64 is not configured yet.

dpkg: error processing package openjdk-8-jre:amd64 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of openjdk-8-jdk-headless:amd64:
 openjdk-8-jdk-headless:amd64 depends on openjdk-8-jre-headless (= 8u121-b13-0ubuntu1.16.04.2); however:
  Package openjdk-8-jre-headless:amd64 is not configured yet.

dpkg: error processing package openjdk-8-jdk-headless:amd64 (--configure):
 dependency prNo apport report written because MaxReports is reached already
                                                                            No apport report written because MaxReports is reached already
                                                          No apport report written because MaxReports is reached already
                                        No apport report written because MaxReports is reached already
                      oblems - leaving unconfigured
dpkg: dependency problems prevent configuration of openjdk-8-jdk:amd64:
 openjdk-8-jdk:amd64 depends on openjdk-8-jre (= 8u121-b13-0ubuntu1.16.04.2); however:
  Package openjdk-8-jre:amd64 is not configured yet.
 openjdk-8-jdk:amd64 depends on openjdk-8-jdk-headless (= 8u121-b13-0ubuntu1.16.04.2); however:
  Package openjdk-8-jdk-headless:amd64 is not configured yet.

dpkg: error processing package openjdk-8-jdk:amd64 (--configure):
 dependency problems - leaving unconfigured
Setting up gir1.2-javascriptcoregtk-4.0:amd64 (2.14.5-0ubuntu0.16.04.1) ...
Setting up libjavascriptcoregtk-4.0-18:amd64 (2.14.5-0ubuntu0.16.04.1) ...
Setting up libwebkit2gtk-4.0-37:amd64 (2.14.5-0ubuntu0.16.04.1) ...
Setting up gir1.2-webkit2-4.0:amd64 (2.14.5-0ubuntu0.16.04.1) ...
dpkg: dependency problems prevent configuration of update-notifier:
 update-notifier depends on update-notifier-common (= 3.168.3); however:
  Package update-notifier-common is not configured yet.

dpkg: error processing package update-notifier (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of update-manager:
 update-manager depends on update-notifier; however:
  Package update-notifier is not configured yet.

No apport report written because MaxReports is reached already
                                                              No apport report written because MaxReports is reached already
                                            dpkg: error processing package update-manager (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of ubuntu-release-upgrader-gtk:
 ubuntu-release-upgrader-gtk depends on update-manager; however:
  Package update-manager is not configured yet.

dpkg: error processing package ubuntu-release-upgrader-gtk (--configure):
 dependency problems - leaving unconfigured
No apport report written because MaxReports is reached already
                                                              Setting up libwebkit2gtk-4.0-37-gtk2:amd64 (2.14.5-0ubuntu0.16.04.1) ...
Setting up snap-confine (2.22.2) ...
Setting up snapd (2.22.2) ...
Setting up ubuntu-core-launcher (2.22.2) ...
Setting up libisc-export160 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libdns-export162 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libisc160:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libdns162:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libisccc140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libisccfg140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libbind9-140:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up liblwres141:amd64 (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up bind9-host (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up dnsutils (1:9.10.3.dfsg.P4-8ubuntu1.5) ...
Setting up libavutil-ffmpeg54:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libavresample-ffmpeg2:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libswresample-ffmpeg1:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libpostproc-ffmpeg53:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libswscale-ffmpeg3:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libavcodec-ffmpeg56:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libavformat-ffmpeg56:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libavfilter-ffmpeg5:amd64 (7:2.8.11-0ubuntu0.16.04.1) ...
Setting up libgc1c2:amd64 (1:7.4.2-7.3ubuntu0.1) ...
Setting up libssh2-1:amd64 (1.5.0-2ubuntu0.1) ...
Setting up linux-image-4.4.0-62-generic (4.4.0-62.83) ...
Running depmod.
update-initramfs: deferring update (hook will be called later)
Examining /etc/kernel/postinst.d.
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
update-initramfs: Generating /boot/initrd.img-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.4.0-62-generic
Found initrd image: /boot/initrd.img-4.4.0-62-generic
Found linux image: /boot/vmlinuz-4.4.0-57-generic
Found initrd image: /boot/initrd.img-4.4.0-57-generic
Found linux image: /boot/vmlinuz-4.4.0-53-generic
Found initrd image: /boot/initrd.img-4.4.0-53-generic
Found linux image: /boot/vmlinuz-4.4.0-31-generic
Found initrd image: /boot/initrd.img-4.4.0-31-generic
Found Windows 10 (loader) on /dev/sda1
Found Ubuntu 16.04.1 LTS (16.04) on /dev/sda9
Found Ubuntu 14.04.4 LTS (14.04) on /dev/sdb1
Found Windows 10 (loader) on /dev/sdc2
done
Setting up linux-image-extra-4.4.0-62-generic (4.4.0-62.83) ...
run-parts: executing /etc/kernel/postinst.d/apt-auto-removal 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/initramfs-tools 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
update-initramfs: Generating /boot/initrd.img-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/pm-utils 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/unattended-upgrades 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/update-notifier 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
run-parts: executing /etc/kernel/postinst.d/zz-update-grub 4.4.0-62-generic /boot/vmlinuz-4.4.0-62-generic
Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.4.0-62-generic
Found initrd image: /boot/initrd.img-4.4.0-62-generic
Found linux image: /boot/vmlinuz-4.4.0-57-generic
Found initrd image: /boot/initrd.img-4.4.0-57-generic
Found linux image: /boot/vmlinuz-4.4.0-53-generic
Found initrd image: /boot/initrd.img-4.4.0-53-generic
Found linux image: /boot/vmlinuz-4.4.0-31-generic
Found initrd image: /boot/initrd.img-4.4.0-31-generic
Found Windows 10 (loader) on /dev/sda1
Found Ubuntu 16.04.1 LTS (16.04) on /dev/sda9
Found Ubuntu 14.04.4 LTS (14.04) on /dev/sdb1
Found Windows 10 (loader) on /dev/sdc2
done
Setting up linux-image-generic (188.8.131.52.65) ...
Setting up linux-headers-4.4.0-62 (4.4.0-62.83) ...
Setting up linux-headers-4.4.0-62-generic (4.4.0-62.83) ...
Setting up linux-headers-generic (184.108.40.206.65) ...
Setting up linux-generic (126.96.36.199.65) ...
dpkg: dependency problems prevent configuration of ca-certificates-java:
 ca-certificates-java depends on openjdk-7-jre-headless (>= 7~u3-2.1.1~pre1-1) | java7-runtime-headless; however:
  Package openjdk-7-jre-headless is not installed.
  Package java7-runtime-headless is not installed.
  Package openjdk-8-jre-headless:amd64 which provides java7-runtime-headless is not configured yet.

dpkg: error processing package ca-certificates-java (--configure):
 dependency problems - leaving unconfigured
No apport report written because MaxReports is reached already
                                                              Processing triggers for libc-bin (2.23-0ubuntu5) ...
Errors were encountered while processing:
 java-common
 openjdk-8-jre-headless:amd64
 update-notifier-common
 flashplugin-installer
 openjdk-8-jre:amd64
 openjdk-8-jdk-headless:amd64
 openjdk-8-jdk:amd64
 update-notifier
 update-manager
 ubuntu-release-upgrader-gtk
 ca-certificates-java
E: Sub-process /usr/bin/dpkg returned an error code (1)

Comment: Please open a terminal. Run the following commands `sudo apt update` and `sudo apt upgrade`. Copy-and-paste the complete output into your question above. Format the output properly.
Comment: @user535733: I've added results of these commands. But anyway some problems with java appear
Answer: The cause of your problem is in the first error message:
Setting up java-common (0.56ubuntu2) ...
mkdir: cannot create directory '/etc/.java/.systemPrefs': File exists
dpkg: error processing package java-common (--configure):
 subprocess installed post-installation script returned error exit status 1

The java-common package gets stuck because you did not clean up after previous attempts to install Java.
Delete /etc/.java, then the install should work properly.

Software Update does not work?


Convert lists of lists of string into a list of string efficently

Question: I have a lists of lists of strings which I would like to convert to a list of strings adding a space between each list item. eg.
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]

desired_output = ['the cat in the hat', 'fat cat sat on the mat']

I understand that I can do it using this:
desired_output
for each in original_list:
    desired_output.append(' '.join(each))

but as I am working with large amounts of data am ideally looking for a more efficient way to do this.
Comment: @KaushikNP Cheers - it was a typo.
Comment: It should be `' '.join(each)` instead of `''.join(each)` in your code
Answer: Use str.join with a full space ' ':
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]
final_list = [' '.join(i) for i in original_list]

Output:
['the cat in the hat', 'fat cat sat on the mat']

Comment: Um, how is this an optimisation? The OP has already done this, just not using `list comprehension`.
Comment: @KaushikNP `str.join` is much faster than string concatenation because  strings are immutable and thus cannot be changed in place.
Comment: But that's not what the user has done. The OP too has used `join`. But yeah, one thing I overlooked. The user used `append` and `list comprehension` has a slight advantage there. So works out. +1
Comment: @KaushikNP it also optimised LOCs, reducing dev time ;)
Answer: Another pythonic and simple way, in Python 3, could be using map, says another SO discussion it should be faster, it would go like this:
original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']]

#              (------where magic happens--------)
desired_list = list(map(' '.join, original_list ))

#print
#output ['the cat in the hat', 'fat cat sat on the mat']


SOLVED upgrade error: illegal package name `systemd/noawait'

Question: when I run this sudo apt upgrade command I get this:
Reading package list ... Done
Creating dependency tree
Reading status information ... Done
Calculating the update ... Done
The following packages will be updated:
  linux-libc-dev

1 updates, 0 new ones will be installed, 0 to remove and 0 not to update.

39 not fully installed or removed.
0 B / 1,141 kB of files need to be downloaded.
12.3 kB of additional disco space will be used after this operation.
do you wish to continue? [Y / n] yes

dpkg: error: trigger log file mentions a package name
Illegal you `systemd / noawait '(in the file` / usr / lib / systemd / catalog'): name
Illegal packet in value 'systemd / noawait': character `/ 'is not allowed
gone (only letters, digits characters `- + ._ 'are allowed)
E: The / usr / bin / dpkg thread returned an error code (2)

And i can't upgrade :((
Please help. i use ubuntu 20.04
Comment: I fixed the syntax error, it was just an empty space, when removing the space now I have this error ```dpkg: error: duplicate file trigger interest for file `/ usr / li
b / gtk-2.0 / 2.10.0 / immodules 'and the package `libgtk2.0-0: i386'
E: Sub-process / usr / bin / dpkg returned an error code (2)```
Comment: I fixed my bug, I just removed /usr/lib/gtk-2.0/2.10.0/immodules libgtk2.0-0:i386/noawait and I was able to request the dpkg already, thank you very much
Comment: first aid `wget -c http://mirrors.kernel.org/ubuntu/pool/main/s/systemd/systemd_245.4-4ubuntu3.6_amd64.deb` and try to install it with dpkg `sudo dpkg -i systemd_245.4-4ubuntu3.6_amd64.deb`  `sudo dpkg --configure -a && sudo apt -f install`
Comment: So, i run the command ```sudo dpkg -i systemd_245.4-4ubuntu3.6_amd64.deb``` and show this ```dpkg: error: the trigger logs file mentions an illegal package name `systemd / noawait '(in the file` / usr / lib / systemd / catalog'): illegal package name in the value 'systemd / noawait': the character `/ 'is not allowed (only letters, digits characters` - + ._' are allowed)```
Comment: Okay `file /usr/lib/systemd/catalog`  please.
Comment: root@ubuntu:/# ```file /usr/lib/systemd/catalog```    (i run the command and show this)   ```/usr/lib/systemd/catalog: directory```
Comment: I do this. I run this ```sudo gedit /var/lib/dpkg/triggers/File``` and i delete this ```/usr/lib/ systemd/catalog system/noawait``` and i run ```sudo apt update & sudo apt upgrade``` and show this   ```dpkg: error: syntactic error in trigger file /var/lib/dpkg/trigg
ers / File '```
Comment: @LinkMales Would you share your current contents of `/var/lib/dpkg/triggers/File` file?
Comment: /usr/lib/mime/packages mime-support/noawait
/usr/share/applications mime-support/noawait
/etc/dbus-1/system.d dbus/noawait
/usr/share/dbus-1/system.d dbus/noawait
/usr/share/dbus-1/system-services dbus/noawait
/etc/rsyslog.d rsyslog/noawait
Comment: Is a long list, i don't know how i can send it
Comment: @LinkMales Nice. would you write an answer then set as accepted. So other may find the solution quickly. Btw, you can use http://paste.ubuntu.com if you needed another time to share long txt.
Comment: I new in askubuntu. What do i that¿?
Comment: @LinkMales See [about] for quick start. In this page, look at the bottom there is a box for "your answer". Ask Ubuntu is a Q/A site.
Answer: The solution is in the document /var/lib/dpkg/triggers/File, you have to look for this trigger with sudo gedit /var/lib/dpkg/triggers/File, then we look for /usr/lib/systemd/catalog system/noawait, then we remove it and we have already resolved the error, if an error appears like this dpkg: error: syntactic error in trigger file /var/lib/dpkg/triggers/File '... The error is in an empty space of the document /var/lib/dpkg/triggers/File.


enable disable jquery tab

Question: I have a jquery tab container, in which there are two tabs. Now what I want is initially second tab will be disabled. On clicking a button on the first tab second tab will be enabled and open automatically.

overview

details

                here is the list of the overview

                Particular Details

Answer: You can use the following
$("#tabs").tabs({disabled: [0,1]});

And use the zero-indexed numbers to choose which are disabled. To enable your tabs you can use this:
$("#tabs").tabs({disabled: false });

For setting the selected tab, you can use this example from jQuery Tabs:
var $tabs = $('#tabs').tabs(); // first tab selected

$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});

Comment: For the disable to take effect, make sure this tab is not currently selected from previous display. I had to un-select the tab I was going to disable in order to show properly (if the tab was active (selected) it will still show even if programmatically disabled `             $( "#tabs" ).tabs( "option", "selected", 0 );
                $("#tabs").tabs({disabled: [1]});`
Answer: I would disable all of them by default, and then enable the first one. After that, the button should be pretty simple. All of this should be pretty simple.
First: jQuerys tabs('disable') just doesn't work. So I built my own function to disable them all. Here that is:
function disableTabs(obj){
    var c = obj.find("ul li").size();
    for(var i=0;i<c;i++){
        obj.tabs("disable", i);
    }
}

You can use it like this: disableTabs($('#myTabs')). jQuery doesn't allow you to disable the current tab - and since this is going on page load, it's going to be the first one. Then, you will need to make some variables to store some data...
var openTab = 0;
var currTab = 0;

Then, a couple of functions to handle it...
function enableTab(obj, num){
    obj.tabs("enable", num);
}
function next(){
    openTab++;
    currTab++;
    enableTab($(".tabs"), currTab);
    $(".tabs").tabs("select", currTab);
}
function prev(){
    openTab--;
    currTab--;
    $(".tabs").tabs("select", currTab);
}

Then , we just attach some event handlers:
$('#myTab').bind('tabsshow', function(event, ui) {
    currTab = ui.index;
});
$(".next").click(function(){
    next();
});
$(".prev").click(function(){
    prev();
});

The HTML for those buttons is really simple:
Previous
Next

Hope this helps - and good luck!
BTW: I have some full working tabs up here that you might want to look at.
Answer: The way I would tackle this is to use a variable that tracks whether the button has been clicked, setting it to 'false' by default and 'true' when the button has clicked.
Checking the value of this variable within the click event of the tab links will then allow you to decide whether to show the new tab, do nothing, or perhaps show a message.
Here's a working example: http://jsbin.com/ijoco5
Comment: Exactly this is the requirement. But I have not used the default jquery tab, in my case tabLinks.eq(0) or tabLinks.eq(1) is not working. So how should I select the second tab?
Comment: There isn't any default jQuery tab functionality, unless you used jQuery UI Tabs, but sometimes that is overkill.

The 'tabLinks' is simply a variable I've set that contains the elements from the selector $('#tabs a'), so that I don't have to repeatedly call this selector. A way of caching if you will.

'.eq()' is just another way of filtering elements, similar to ':first', starting with 0 meaning the first element (http://api.jquery.com/eq/).

I've amended the example to use your markup, so perhaps it makes a little more sense: http://jsbin.com/ijoco5/2/
Answer: Assuming you are clicking a button which is not a inside tab class and want 2nd tab to open then you can add trigger event like :
$('.tabs > #tab2').trigger('click');

And give id to li > a :

enable disable jquery tab


How do I start Super Melee mode in The Ur-Quan Masters?

Question: I've figured out how to configure team names, membership, and control.  But beyond that screen, I can't seem to find how to initiate battle.
After clicking the "BATTLE!" button, I'm presented with a screen that has a black background and two blue boxes.  Each box has a team name, and icons representing the ships in each team and their values.  Each box also has two buttons - a question mark and a red X.
At this point, my normal controls (Up/Down/Left/Right/Control/Shift/Escape) seem to not function.  Is there something wrong with the game, or my system?  Or, does the control set change specially for Super Melee mode at this point?  How should I proceed?
This is on a Windows 7 Ultimate x64 system, with UQM version 0.7.0.
Comment: That sounds like the ship selection screen, where both players select the ships they want to use in the upcoming battle. Probably the solution is indeed to find the right controls ... but I don't remember what they are.
Answer: Before clicking the battle button, on the setup screen you'll see which team is controlled by which player.

By default, the first team is controlled by the AI while the second team is controlled by the player. This is where things can get a bit confusing, if the bottom player is set to human control then the controls for "player 1" will be used, while if the top player is set to human the controls for "player 2" will be used. The exact keys which can be used by player 1 or player 2 can be set in the UQM setup menu.
By default, player one should be able to select a ship using the arrow keys and the enter key to select something, while player two is able to use ESDF and the Q button to select a ship.
Comment: This drove me nuts on a few occasions too. I find the player 2 controls almost unusable, so you'll usually want to set the human player to player 1 (the bottom of the screen).


T-SQL stored procedure returns null in code, but works in console

Question: I have a stored procedure
CREATE procedure [dbo].[get_unique_identifier]
AS
DECLARE @ret_val INT
UPDATE seq SET @ret_val = id = id + 1
RETURN @ret_val

that queries a table (seq) that has a single int column and single row, increments the value and then then returns it. Don't ask why I'm doing this, but in short, the idea is to simulate a PostgreSQL sequence and no, an identity column would not do the job. Anyway, this works fine in SQL Management Studio, where sequential executions of
DECLARE @returned INT
EXEC @returned = get_unique_identifier
SELECT @returned

produce the expected output. Unfortunately, I can't seem to get the returned value in the application I'm working on
OdbcCommand command = new OdbcCommand("get_unique_identifier");
command.CommandType = CommandType.StoredProcedure;
OdbcParameter return_param = new OdbcParameter("@RETURN_VALUE", OdbcType.BigInt);
return_param.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(return_param);
Util.SQLExecuteParameterizedNonQuery(command);
Console.WriteLine(command.Parameters["@RETURN_VALUE"].Value.ToString());

The output is an empty string, but the value itself is DBNull.Value. The OdbcType.BigInt is left over from some testing I was doing. It was initially Int.
Edit: This is clearly a bug with ODBC. A workaround is posted below. Don't use ODBC if you don't have do.
Answer: I am sorry to have to say, but this might be due to using the Odbc
I tried this using out SqlClient database object and it returned the values as expected.
SqlCommand command = new SqlCommand("ZZZ_get_unique_identifier");
command.CommandType = CommandType.StoredProcedure;

SqlParameter return_param = new SqlParameter("@RETURN_VALUE",SqlDbType.BigInt);
return_param.Direction = ParameterDirection.ReturnValue;
command.Parameters.Add(return_param);

SqlConnection con = new SqlConnection(dbM.DefaultConnectionString);
con.Open();

command.Connection = con;
command.ExecuteNonQuery();

int i = Convert.ToInt32(command.Parameters["@RETURN_VALUE"].Value.ToString());
con.Close();

Comment: Looks like you're right. :( I just tried with SqlClient and it worked. Now I have to find a workaround for ODBC.
Comment: I managed to get it working by changing the `RETURN @ret_val` to `SELECT @ret_val` in the sp.
Comment: That should then return a table result.
Comment: Indeed. Now I can use ExecuteScalar(), which is arguably more elegant on the client side. Thanks for your help!
Answer: The return value of stored procedures is Int (32-bit), not BigInt (64-bit), but I'm not sure that this would be the problem with your code.
Answer: Have you not tried using an output variable instead...I am jogging my memory and think that the line command.Parameters["@RETURN_VALUE"].Value.ToString() could be this...The reason it worked in SQL Management Studio because you declared a variable and used it in an TSQL EXEC statement. I hope this answer somehow gives you a hint..
Hope this helps,
Best regards,
Tom.
Comment: Looking at it again, have you also tried Console.WriteLine(return_param.Value()) or equivalent? Why did you use ODBC and not the native SqlClient namespace?
Comment: The app was originally ported from PostgreSQL. We intend to switch to SqlClient but don't have time right now.


Combine multiple aliases of the same @Entity in one result with HQL

Question: I have the following pattern
@Entity
Class Fruit {
   String name;
}

@Entity
Class FruitAddition {
   @ManyToOne
   Basket basket;

   @ManyToOne
   Fruit fruit;

   String additionType;
}

@Entity
Class Basket {
   String owner;

   @ManyToMany
   List<Fruit> fruits;

   @ManyToMany(mappedBy="basket")
   List<FruitAddition> fruitAdditions;
}

So the Basket is made out of a list of Fruits (one fruit can be in many baskets at the same time) and of a list of FruitAdditions, which is almost a list of Fruits, but each fruit in the basket has additional data additionType associated to it.
This seems to work.
Now I want to query all the fruits in a basket and thus I try to combine two aliases into one result as follows:
SELECT fruitAlone, fruitAdded
FROM Basket bask
JOIN bask.fruits fruitAlone
JOIN bask.fruitAdditions addition
JOIN addition.fruit fruitAdded
WHERE bask.owner = 'JOE'

And then interpret the result as a List<Fruit>, since both fruitAlone and fruitAdded are of type Fruit.
But I get a java.lang.ClassCastException.
How is this correctly done?
Answer: You can just receive a List<Object[]>, where the first position will be the fruitAlone and the second the fruitAdded. Like:
Query query = em.createQuery("SELECT fruitAlone, fruitAdded ...");
List<Object[]> results = query.getResultList();
for (Object[] obj : results) {
    Fruit fruitAlone= obj[0];
    Fruit fruitAdded = obj[1];
}

Comment: Thanks, I will test it tomorrow. Do you know what will happen to paging (LIMIT) ? Will the size be applied to both aliases?


How do I get the cropping frame of the address book image data?

Question: The AddressBook framework provides ABPersonCopyImageData for getting the contact image for each address book entry.  This is great for the image data, but the user also sizes and crops the image for framing purposes.  When I get the image data, I get the full image, and not the cropped image.  How do I get the frame the user used to crop the image (or in lieu of that, how do I get access to the cropped image/data)?
Answer: iOS 4.1 adds a new method: ABPersonCopyImageDataWithFormat in ABPerson.
I'm using it like this:
NSData *imageData = [(NSData *)ABPersonCopyImageDataWithFormat(recordRef, kABPersonImageFormatThumbnail) autorelease];

The formats allowed are:
kABPersonImageFormatThumbnail
kABPersonImageFormatOriginalSize

This allows you to get the original image or the cropped image (thumbnail).
Answer: To some extent, it's a bug in iOS4.  Previously, the address book API returned cropped data, and in iOS4 it returns the whole image data.  Some people want one, some people want the other.  I tend to think the whole image data is useless without the cropping frame, so hopefully that will get fixed...
Answer: I think it's impossible to get the crop rect.
The crop rect information is stored inside the sqlite database that managed by addressbook framework.
But client's application cannot read another application's sqlite database, according to the sandbox structure.
Comment: Frameworks are not apps. "Sandboxing" is largely just process/UID-based. However, it turns out that /var/mobile/Library/AddressBook/AddressBookImages.sqlitedb is readable so it should be possible to get the crop rect out, even if it might be considered "private".
Comment: If the sqlite database could be queried, then so many things can be solved. Something like custom labels, the crop rect problem here, and the store (ABStore) problem before iOS SDK 4.0, ... etc. My partner had tried and he said that it cannot execute commands on the sqlite database which managed by addressbook framework. Maybe you can try again.


Can $\mathrm{tan}$ be defined by an IVP with rational functions as coefficients?

Question: We can define $\sin$ and $\cos$ as the solutions to the DE $$f''(x) = -f(x)$$ subject to certain initial conditions.
The above DE has constant coefficients, but I'd like to use a similar approach to defining $\tan$, and I'm happy generalize to rational functions, for example $$f''(x) = x^3 f'(x) -\frac{3x}{1-x^2} f(x)$$ would be a valid candidate.
Anyway:

Question. Can $\mathrm{tan}$ be defined by an IVP with rational functions as coefficients?

Note that $$f'(x) = \frac{1}{1+x^2}$$ is solved by $f(x) = \mathrm{arctan}(x),$ so that's a near miss.
Comment: Something like $1+(f)^2=f'$ would be out of the question as it's nonlinear right?
Comment: @ZacharySelk, yes, but that's a nice solution to a related problem. Nice one :)
Comment: I answered and I'm pretty sure my answer is in spirit right but the details I messed up. Basically, derivatives of $\tan(x)$ are just polynomials in $\tan(x)$ with integer coefficients. See my deleted half answer.
Comment: @ZacharySelk, interesting link! It hadn't occurred that this was possible.
Comment: [This question](https://math.stackexchange.com/questions/2314942/finding-the-nth-derivative-of-functions-in-particular-y-tanx) finds non-linear DE for $n\in\{1,\dots,9\}$. It doesn't seem promising from that and [this pdf](https://arxiv.org/pdf/1202.1205v1.pdf) that there's a linear DE for it, but I'm unclear how you'd prove that.
Answer: No. Functions which can be defined in this way are said to be holonomic, and $\tan x$ is known not to be holonomic. This is because holonomic functions have finitely many singularities (the singularities of the denominators of the rational functions involved), while $\tan x$ has infinitely many singularities.
Comment: Thanks, that makes perfect sense.


Leaflet - Icon-Layer-Switch

Question: I am currently creating an interactive map for a class at my University. As I am just a beginner in coding, I have some trouble achieving what I have in mind. I would like to create a layer-switch such as the one presented here : https://github.com/ScanEx/Leaflet-IconLayers.
I unfortunately don't understand everything in this example, and so I have trouble adding it to my own map.
When I tried just copying the code and adding it to my map, most of what I had won't appear anymore (such as the markers and the infopopup).
Here is my project : https://github.com/TheBearMan93/Projet-1.
If someone could help me resolve my problem I would be really grateful.
Thank you for your time
Comment: Can you include some of the code that you attempted to add that is causing you problems?
Comment: I added this

I also added the different .js and .css from the example to my . Unfortunately, when I did that, the layer switcher appeared and is working, but everything else I need disappeared (markers, popup, ...).
Answer: To use the leaflet Icon layer switch, you are are going to want to create an object of baseLayers which includes the name, icon, and layer like this.
var providers = {};

providers['OpenStreetMap_Mapnik'] = {
    title: 'osm',
    icon: './images/icons/openstreetmap_mapnik.png',
    layer: L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    })
};

Then rather than using the standard leaflet layer control, you will use the icon-layer-switch library. This loops through all of the providers you define creates the layer control and adds to the map.
var layers = [];
for (var providerId in providers) {
    layers.push(providers[providerId]);
}
layers.push({
    layer: {
        onAdd: function() {},
        onRemove: function() {}
    },
    title: 'empty'
})
var ctrl = L.control.iconLayers(layers).addTo(mymap);

I've created a pull request on your github project to see how this could work for you.  I hope this helps.
Comment: @Nicolas You're welcome. If the answer worked for you, can you please mark it as accepted :)

Leaflet - Icon-Layer-Switch


How do I limit how far from a stockpile a dwarf is allowed to go to fetch items?

Question: Ideally, for a particular stockpile I want to be able to specify how far from the stockpile a dwarf is allowed to go for items.  Alternatively, it would be nice to be able to assign a stockpile to a burrow, and only allow it to collect items from that burrow.
For example, Say I'm excavating several veins of the same ore, and I want a localized stockpile at each one, but I don't want my Dwarves hauling ore across the map from one vein to another if the closer stockpile is full.
Is there a way to limit the range of a stockpile like this in v0.34.11?  Are there any mods out there that might do something similar?
Comment: Not in the mood to make a full answer, but have you considered quantum stockpiles using minecarts? This will prevent (partially) stockpiles from filling up.
Answer: Short of creating burrows and confining dwarves to their respective burrows, each with its own stockpiles, there is no such feature in vanilla DF -- stockpiles will accept whatever they're set to accept from anywhere on the map (notwithstanding Forbidden or otherwise inaccessible items). Sorry. :(
I know of no mods that add this, either.
Answer: For the example that you give (consolidating freshly mined ore), you can start by creating your local stockpile near the vein, and then create as many additional stockpiles as necessary to cover the area containing the mined ore. Add a "give to" link from each of those stockpiles to the first stockpile, and set all stockpiles including the first to take from links only.


How to use IVI-C instruments-drivers (not IVI-COM)

Question: I want to use IVI-C instruments-drivers (not IVI-COM) in Visual Studio 2012
Someone ever did this?
I only found examples for Visual Basic.
Drivers are downloadable on keysight.com-website which are free to use.
For VISA i installed Keysight IO-Libraries.
Answer: I'm doing something similar in Visual Studio 2013 using VB, but the basic principles will be similar for all languages. You probably know all of this already, but the question is a bit vague so here goes:
You need to install the drivers plus an SDK (which comes as a dll).  Hopefully the SDK will come with a manual of commands in your language of choice, but if not study the manufacturer's coding examples in VB or whatever.
It is easiest to use the languages provided in the SDK (usually VB and C#, maybe C++) otherwise you will have to write an interface between your language and the actual command syntax and work in a multi-language environment.
The drivers and the SDK need to be referenced in your project after you have installed them.  (MyProject, Reference Tab, use the Add command and Browse for the files.)  Sometimes its hard to find the correct files but VS 2013 is quite good at telling you when you get the wrong ones.
You may have to target your build (Build|Configuration Manager) on x86 processors because there are no x64 drivers for much of this kit - check with Keysight.
Then, in your code you will need to:

instantiate a copy of the driver for the specific instrument:
Dim MyDriver As New InstrumentManufacturersDriverName
initialize it using the manufacturer's commands (on my kit initialization connects the driver to the physical interface via USB):
MyDriver.Initialize(ParametersIfAny),
set up the ports you want to use (very dependent on the specific hardware)
program your commands.
Use a lot of patience and trial and error at first.

Best of luck - it's not so difficult.


Unable to Boot into Windows 7 After Installing Ubuntu 16.04

Question: I have a HP Pavilion HPE desktop with 3 harddrives installed.
Windows 7 was originally installed on the machine. I then installed Ubuntu 16.04,onto the second drive attempting to dualboot both OS. Since installing Ubuntu, I have been unable to boot into windows 7.

On boot, the GRUB loader shows only the Ubuntu 16.04 options. No Windows options.
I have tried a few GRUB update and detection commands
Going to BIOS and selecting boot options to boot from Windows HD shows the message - "Boot disk not found please check"
When I boot into Ubuntu 16.04, In Files, I can see the Windows Drive with all previous files showing.
You can see an attached image of the drive configuration from my fdisk output in ubuntu

Does anyone have potential steps to enable booting into Windows?
I am looking to boot into or recover windows files and configuration. I am willing to uninstall or remove Ubuntu if that can solve this issue.
Harddrives:

HD 1 - Windows 7 was installed on
HD 2 - Ubuntu 16.04
HD 3 - Should be empty
Comment: Have you tried `sudo update-grub` to see if it's recognizing the windows 7 when `grub` configs are re-created?  If windows was hibernated, or fast-boot was enabled; it may be ignored (*as file-system won't be clean*)
Comment: Ubuntu 16.04 will reach end of life on April 30, at which point you will need to upgrade.  Windows 7 already reached end of life over a year ago.  If I were you, I would say that now is a good time to install supported versions of both operating systems. After April 30, new questions about 16.04 will be off topic.
Comment: @guiverc I have tried `sudo update-grub` unfortunately that does not add Windows to the menu.
Comment: @Nmath Updating may be an idea. I have some specific Ableton and music production configuration I would like to ensure I can transfer over to any updated OS. Any recommendation on migrating Windows data? Or at least making it bootable again before I make changes?
Comment: In my prior comment I'd suggested one reason it won't be recognized by `update-grub`, if you `mount` the partition, have you looked up the logs to see if error conditions were mentioned (such as a RO only mount occurring).  Mounting at terminal is probably faster than looking up logs (the messages that reach logs appear on screen)
Comment: Is Windows 7 on sda? That is gpt, so Windows would only be UEFI install? But most Windows 7 installs were BIOS/MBR. Did you install Ubuntu in UEFI boot mode? UEFI and BIOS are not compatible, once you start booting from UEFI boot menu, you cannot switch modes. Or grub can only boot other installs in same boot mode.
Answer: Run this command in Terminal :  sudo update-grub2
`


Do unsigned functions have to return something?

Question: I'm working on an exercise where I have to program an unsigned function in C. Do I have to return something because of the type of the function? Or is it optional?
Comment: Always return something if non-void.
Comment: You're supposed to return a value. If the calling code uses the value you didn't return, then there is undefined behaviour.  But you're on thin ice. Best to return a value when you say you will.  Or change the return type to `void`.
Comment: You talk about "the type of the function" and "an unsigned function in C". In C, the type of a function describes both the types of input-argument and the type of the return value. Is it the input, output or both maybe that are unsigned?
Comment: If you turn warnings of your compiler on, you can try it and then see what your compiler tells you...
Comment: Laura Cooper, Why would you want code to not return something?
Comment: Okay, thank you so much, everyone. ;)
Answer: In normal use, any function declared to return a value ought to return a value. This is largely a matter of good programming practice. Failing to return a value is often a sign of an error. However, this is not required by the C standard, and there are two exceptions.
C 2018 6.9.1 12 allows a function to terminate by reaching the end of its code without returning a value, provided the caller does not use the value of the function:

Unless otherwise specified, if the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

One case where a function might return a value in some situations and not in others is where it is designed to perform various different actions upon command. For example:
unsigned DoSomething(int command, int parameters[])
{
    switch (command)
    {
        case GetSomething:
            …
            return Something;
        case RememberSomething;
            Something = parameters[0];
            …
            break;
    }
}

Such designs may be error-prone and ought to be considered carefully. Since the function is declared to return a value, a programmer might expect it to do so and inadvertently assign the value of the function to another object in a situation where no value is returned, resulting in undefined behavior.
Additionally, a function may not return at all, and there is a function specifier for explicitly telling the compiler this is so, _Noreturn, as specified in 6.7.4. This behavior is typically used only in abnormal situations. For example, the standard functions abort and exit terminate the program, so they do not return. Of course, they are declared with void, so they never return anything. However, you might have a function that calls exit in some circumstances and returns an integer in others.
Comment: @PaulOgilvie: The C standard licenses programs to discard code after a call to a `_Noreturn` function by the ["as if' rule](https://stackoverflow.com/a/46455917/298225) and by 6.7.4 8, which says "A function declared with a `_Noreturn` function specifier shall not return to its caller."
Comment: As far as the caller is concerned, a function declared as returning e.g. `int` will return an int _when_ it returns. So `exit()` is declared as `void`.
Comment: `_Noreturn` is used to tell the compiler that a function being compiled will or may not return and so any return statement (e.g. `exit()`), present or not, may be discarded. It does __not__ say that when the function is used, there will be no return value. Neither is `_Noreturn` part of a prototype. Hence the caller does not know about the `_Noreturn`.
Comment: Hmm I'm not sure if the quoted statement actually **allows** a function not to return any values...
Comment: @PaulOgilvie: What do you mean `_Noreturn` is not part of a prototype. It may be part of a function declaration whether or not it is a definition, is shown as such in some places in the standard, and hence is visible to the when used thusly.
Comment: @PaulOgilvie: My answer does not say that `_Noreturn` says there will be no return value when the function is used. It is discussed in a paragraph discussing when the function does not return at all.
Comment: @PaulOgilvie: `exit` is declared as a void, but a program may have a function that **does** return a value when it returns but that sometimes calls `exit`. Your comment appears to have missed this. I am answer OP's question completely; they asked whether functions have to return something, and they did not exclude the case where the function does not return at all, so I am covering both the situation where the function returns and the situation where the function does not return in my answer.
Comment: I mean that the compiler does not use the attribute when compiling a function that uses a function declared as `_Noreturn`.
Comment: @PaulOgilvie: Why would you think the compiler does not use the attribute? If we have `_Noreturn void foo(void); unsigned bar(int x) { if (x) { foo(); printf("Hello.\n"); } else return 0; }`, why would the compiler bother to put the `printf` or even `"Hello.\n"` in its output when they would never be used? I just tried it, and Apple LLVM 9.1.0, clang-902.0.39.2 omits them.
Comment: OK Eric. I think the answer means that a function decalred to return something, must return that something. Only a void function does not return anything. Your exception implies that only a function declared to return something but that does not return at all, by implication does not even return that thing.
Comment: @PaulOgilvie: I have listed two exceptions. One is the function reaches its terminating `}`, upon which it returns to the caller without returning a value. The other is the function never returns to its caller.
Comment: @Eric, The compiler may not assume `foo` will not return. The function specifiers `_Noreturn` and `inline` are not part of the type of a function, they are part of the declaration. See https://stackoverflow.com/questions/51746897/noreturn-in-a-struct-in-c-error-expected-specifier-qualifier-list-before-no and C11, 22.214.171.124:, which only requires a diagostic message but does not require anything when compiling a function using a `_Noreturn` function.
Comment: @nodakai: It permits it. A function call causes the function to be executed, which 6.9.1 11 says is done by executing the body of the function definition. That body is a *compound-statement*. When it is done, the function returns to its caller. Nothing in the C standard prohibits a function that returns a value from finishing its *compound-statement* by reaching the end of it rather than by executing a `return` statement.
Comment: Reaching `}` of anon-void function without a return statement is an error/warning, right?
Comment: @PaulOgilvie: The question you point to asks about `_Noreturn` on a declaration of a function **pointer**, not on a declaration of a function. `_Noreturn` is permitted on a function declaration, as shown in the grammar at 6.7.4, and the constraints there do not say otherwise. Further, as I wrote, I just tested this in clang. `_Noreturn` was permitted, and it was used by the compiler to remove code that would never be executed.
Comment: @PaulOgilvie: The C standard does not require a warning or error for a non-void function without a `return` statement. A compiler may choose to give warnings.
Comment: @EricPostpischil ...but if it is part of the function type, then you can declare a pointer to a function to be of type `_Noreturn`, but you can't.
Comment: @PaulOgilvie: That has no relevance to my answer, as my answer does not discuss types of functions, at least in regard to `_Noreturn`. If you have questions about it, you can post a question to Stack Overflow.
Answer: It is a good idea to have all your non-void functions return something, but if you exit a function without return statment (i.e. with the } character) and try to access its result, the behavior is undefined.
If you explore different compilers on Godbolt, with the following code as the C source:
int n()
{
    int a = 1234;
}

You will notice that some compilers issue a warning on this behavior depending on their warning levels.
The value you get if you try to use the result function as an int, for example, in printf("%d\n", n()); is undefined: there is no guarantee about what value you will get or if your program will crash, or do something else entirely.
That said, depending on the architecture you're compiling for, you may get a local value from your function as the return value. For example, on the x86 architecture, just about every calling convention specifies that the return value is whatever is in the register eax when the function returns.  So, if the generated code for the function n above stores the local variable a in eax, the "return value" (quote-unquote) will be 1234.
This is not something you should ever rely on, though.


PHP: time increment

Question: In my PHP code I have an array1 that has 2 columns, i.e.:
ID | startDate
1  | 2012-02-03 11:50
2  | 2012-02-03 11:50
3  | 2012-02-03 11:50
4  | 2012-02-03 11:50

I need to transform array1 into the following array2:
ID | startDate
1  | 2012-02-03 11:50:00
2  | 2012-02-03 11:50:30
3  | 2012-02-03 11:51:00
4  | 2012-02-03 11:51:30

So, I should just increment a time by 30 seconds starting from the second entry. This increment should be cumulatively propagated as you may see in example. I'm not very fluent in PHP. Does anybody know time-related PHP functions that could do this job in few lines of code?
Comment: You're adding 50 sec, 0 sec, 50 sec, 0 sec etc? They're not 50 sec more each... The 3rd one didn't have 100 sec added. What's the algorithm?
Comment: @Rudie: No, if you look once again at my example, then you see that each record is incremented cumulatively starting from 50 seconds. There is no 0 sec increment for rows 2 and 4.
Comment: The difference between `11:50:50` and `11:51:00` is not 50 seconds, or am I stupid?
Comment: Oh,sorry, Rudie. You are right. Let me update the post.
Comment: Ah, so you do mean 50 seconds each =) That makes it simpler... J.Money is right then.
Answer: I would look at date() and strtotime()
$array2 = array();
$incr = 0;
foreach ($array1 as $value) {
    $time = strtotime($value);
    $array2[] = date('Y-m-d H:i:s', $time + $incr);
    $incr += 30;
}

Comment: It's not 50 sec extra each though... It's 0, 50, 60, 110... So +50, +10, +50.
Comment: @SamDufel In this case, $value will always be the same and therefore $time will always be the same, but if the array values were different you would need to call strtotime every time.
Comment: @Gusgus There are 10 seconds between 11:50:50 and 11:51:00
Comment: What's the difference between 11:50:50 and 11:51:00? It's not 50 seconds, is it? Do you know how many seconds a minute has?
Comment: @Rudie: Sorry once again. I was looking at too many numbers today;)
Comment: No problem. I was actually having doubts... 0, 5, 50, 0, -10 aaaaaaaargh
Comment: @J.Money - I'm not saying to just run the loop with that line omitted.  There are a couple other ways to increment a timestamp.
Comment: @SamDufel - Care to elaborate?
Comment: PHP timestamps are expressed in seconds - you can directly add seconds to a timestamp, or use the DateTime object to add an interval.
Comment: Also, if you're pulling from a mysql database you can use UNIX_TIMESTAMP to get the timestamp directly from a date / timestamp field.
Comment: Creating a DateTime object will still convert the date to a unix timestamp and adding 30 seconds to it won't be as simple as addition. A date can be pulled from the database as a timestamp, but nothing in this question says anything about a database and it would still require converting a date string to a timestamp. I do not agree that you would not want to use strtotime in a loop in this case.

PHP: time increment


Add dummy column to flag as the row is randomly selected or not

Question: Suppose I have the following data set (named data).
id var1 var2
1   A   33
2   B   23
3   A   45
4   A   55
5   B   22
6   A   33
7   B   90
8   A   78
9   B   12
10  A   11

My intention is to add a new column to the original data set that indicates whether each row of data set is randomly selected or not (1/0). I tried the following.
library(sampling)
data1 <- strata(data,"var1", size=c(4,3),method="srswor") #stratified random sampling
data2 <- getdata(data,data1)  # this gives a separate data set

Any help, please? Thanks!
Comment: Could you replace your data sample by the output of dput(data)? Makes it much easier to reproduce your example...
Answer: If you look in the documentation of sampling::strata() you'll find the following information:
The function produces an object, which contains the following information:

ID_unit
the identifier of the selected units.

Stratum
the unit stratum.

Prob
the unit inclusion probability.

ID_Unit can used to subset the original data and assign the boolean you asked for:
data<-structure(list(id=c(1,2,3,4,5,6,7,8,9,10),var1=c("A",
"B","A","A","B","A","B","A","B","A"),var2=c(33,23,
45,55,22,33,90,78,12,11)),row.names=c(NA,-10L),class=c("tbl_df",
"tbl","data.frame"))

library(sampling)
data1 <- strata(data,"var1", size=c(4,3),method="srswor") #stratified random sampling
data2 <- getdata(data,data1)  # this gives a separate data set

data$sampled <- FALSE
data[data1$ID_unit, "sampled"] <- TRUE
data
#>    id var1 var2 sampled
#> 1   1    A   33   FALSE
#> 2   2    B   23    TRUE
#> 3   3    A   45   FALSE
#> 4   4    A   55    TRUE
#> 5   5    B   22   FALSE
#> 6   6    A   33    TRUE
#> 7   7    B   90    TRUE
#> 8   8    A   78    TRUE
#> 9   9    B   12    TRUE
#> 10 10    A   11    TRUE

Created on 2020-07-28 by the reprex package (v0.3.0)


pick an image and upload it automatically

Question: I want to click on a button and open the file browser from a local disc and automatically upload the selected file to remote server.
<input hidden type="file" id="loader" accept="image/*">

js
$('#m1new').click(function(){
    $('#loader').click();
});
$('#loader').change(function(){
var img = this.files[0];
$.ajax({
    url: 'upload.php',
    type: 'post',
    data: {'img': img},
    success: function() {
        console.log('ok');
    }
});
});

upload.php  (updated)
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["img"]["name"]);
move_uploaded_file($_FILES["img"]["tmp_name"], $target_file);

Console:
Uncaught TypeError: Illegal invocation
Any help?
Answer: Use FormData to send multipart requests and you should set processData option to false  to preven automatic processing
$('#loader').change(function(event){
  var img = event.target.files[0];
  var formData = new FormData();
  formData.append('img', img);
  $.ajax({
      url: 'upload.php',
      processData: false,
      type: 'post',
      data: formData,
      success: function() {
        console.log('ok');
      }
  });
});

Hope this will be helpful
Comment: there is no error in console now, and console says `ok`, but still there is no img in `uploads` folder. Could you check my php code, pls?
Comment: @bonaca files should be in `$_FILES` array now , just change `$_POST['img'];` to `$_FILES['img'];`
Comment: I changed `$img = $_POST['img'];` to `$img = $_FILES['img'];` but still there is no img uploaded in `uploads` folder. `ok` in the console is there.
Comment: Are you sure that you request successfully sent to server ?
Comment: sucess function works - `ok` is in written in console - should be ok with sending request.


containment in a cantor set

Question: I said that the following statement was false: If a belongs to the Cantor set and I is an open interval containing a, then I contains at least one other member of the Cantor set.
Unfortunately I am unable to know for sure if I am right or wrong as I do not have the answer key, and am hoping that you could tell me. Thank you.
Comment: You are correct: the Cantor set has no isolated points.
Comment: No, he's not correct, since he said it was false.
Answer: You can show that every point of the cantor set is an accumulation point with the triadic presentation of the cantor set, so that $$x\in C \iff x=\sum_{k=1}^\infty \frac{a_k}{3^k}$$
with $a_k\in\{0,2\}$. Now you take a sequence converging to this $x$ which is in the cantor set.
By showing that every point is an accumulation point you see that there are no isolated points, so it is right.

containment in a cantor set


Rails migrations for postgreSQL schemas

Question: I'm working on a multi-tenant rails application using PostgreSQL schemas for different clients. Rails migrations don't work with multiple schemas out of the box, so I made the following rake task to migrate all schemas and it seems to work. My question is if others have implemented better and more elegant solutions. I would also be really happy with a good tutorial including rails code examples for PostgreSQL using multiple schemas. So far I have only found a good presentation on the subject http://aac2009.confreaks.com/06-feb-2009-14-30-writing-multi-tenant-applications-in-rails-guy-naor.html and an example of what I'm aiming for tomayko.com/writings/rails-multiple-connections
desc 'Migrates all postgres schemas'
task :schemas do
  # get all schemas
  env = "#{RAILS_ENV}"
  config = YAML::load(File.open('config/database.yml'))
  ActiveRecord::Base.establish_connection(config[env])
  schemas = ActiveRecord::Base.connection.select_values("select * from pg_namespace where nspname != 'information_schema' AND nspname NOT LIKE 'pg%'")
  puts "Migrate schemas: #{schemas.inspect}"
  # migrate each schema
  schemas.each do |schema|
    puts "Migrate schema: #{schema}"
    config = YAML::load(File.open('config/database.yml'))
    config[env]["schema_search_path"] = schema
    ActiveRecord::Base.establish_connection(config[env])
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
  end
end

Comment: @Janning Liquibase is not a solution that works with the ActiveRecord modle that rails uses.
Comment: Liquibase does work with schemas as far as i know
Answer: I have a schema_utils library which I use and has the following method for handling migrations:
  def self.with_schema(schema_name, &block)
    conn = ActiveRecord::Base.connection
    old_schema_search_path = conn.schema_search_path
    conn.schema_search_path = schema_name
    begin
      yield
    ensure
      conn.schema_search_path = old_schema_search_path
    end
  end

I then use migrations as normal so I can continue to call rake:migrate
Now, in your migrations you can use:
...
schemas.each do |schema|
  SchemaUtils.with_schema(schema) do
    #Put migration code here
    #e.g. add_column :xyz, ...
  end
end

Because I tend to be mapping schemas to account codes I do the following:
Account.for_each do |account|
  SchemaUtils.with_schema(account.code) do
    #Put migration code here
  end
end

Answer: Check the apartment gem that's been built just for that purpose. It's brilliant.
Answer: I'm not sure if I got the question right but don't you just need to declare a few more environments in your database.yml with different "database" specified in each?
Comment: Schemas in postgres are within a database. I.E one database can have many schemas.
Answer: I wrote pg_migrate because of these scenarios, i.e., situations in which multiple applications share the same database.  There is probably a Rails way to handle this (engines?) but I too often have another app that's not Rails that needs the database too... then what?
In this case, the key feature of pg_migrate is it can generate a ruby gem; so it becomes possible to maintain your database schema separately from all the downstream applications, but all can reference it.
In your Rails Gemfile, after you've built the ruby gem using pg_migrate's 'package' command, you can do:
gem 'my_db', gem 'jam_db', :path=> "../my_db/gem_package"

Rails migrations for postgreSQL schemas


Python: Creating a multicolumn series with Pandas

Question: I am trying to create a multicolumn series using pandas library:
<code>import pandas as pd
import numpy as np
StartTime = '2015-10-01'
EndTime = '2016-01-01'
step = '1min'

Time= pd.date_range(StartTime,EndTime,freq=step)
Value1 = np.random.choice(range(0,100),len(Time))
Value2 = np.random.choice(range(0,100),len(Time))
Value3 = np.random.choice(range(0,100),len(Time))
#Time series of one variable
TimeSeries = pd.Series(Time,Value1)
</code>
What I want is that every time point to have 3 variables. I tried the following but it didn't work:
<code> TimeSeries = pd.Series(Time,Value1,Value2,Value3)
</code>
Any idea how to implement this?
Answer: While this would work:
<code>>>> TimeSeries = pd.Series(tuple(zip(*(Value1, Value2, Value3))), index=Time)
>>> TimeSeries.head()
2015-10-01 00:00:00    (71, 58, 69)
2015-10-01 00:01:00     (59, 1, 94)
2015-10-01 00:02:00     (50, 65, 6)
2015-10-01 00:03:00     (16, 50, 7)
2015-10-01 00:04:00    (20, 36, 41)
Freq: T, dtype: object
</code>
it would be better to use data frame:
<code>>>> df = pd.DataFrame({'Value1': Value1, 'Value2': Value2, 'Value3':Value3}, index=Time)
>>> df.head()
                     Value1  Value2  Value3
2015-10-01 00:00:00      71      58      69
2015-10-01 00:01:00      59       1      94
2015-10-01 00:02:00      50      65       6
2015-10-01 00:03:00      16      50       7
2015-10-01 00:04:00      20      36      41
</code>
Comment: Yes, that is what data frames are made for.
Comment: Thanks for the asnwer. Yea, it seems that your second answer is more easy for later use of the data.
Comment: @MpizosDimitris Looks like you can [upvote](http://stackoverflow.com/help/privileges/vote-up) ;).
Comment: Sorry for not upvoting earlier. I guess I was over-excited to go through my task :)


Execute another installer silently within your Nsis installer

Question: I am trying to execute ffdshow.exe silently within my nsis installer but ffdshow doesnt seem to work with my method but MatroskaSplitter.exe and other installers have run silently with the same method.
File "..\Prerequisites\ffdshow_rev4515_20130612_clsid.exe"
  ExecWait '"$INSTDIR\ffdshow_rev4515_20130612_clsid.exe" /S'
Comment: Do you have any warning/error in the `makensis.exe` output log during compilation? Do you have any error at runtime? if you start the same command manualy, does it work?
Comment: @Seki Thanks for your effort, no errors though but I have got an answer.
Answer: Are you sure ffdshow uses NSIS?
It looks to me like they are using Inno so you could try  /silent or /sp- /silent /norestart.


Enabling Server Side Includes in IIS Express/Visual Studio

Question: I'm using VS2015 with the built-in IIS Express server...
Is it possible to enable Server Side Includes (SSI), eg this sort of thing:

I know I can use SSI on full IIS but I can't find any info about using SSI on IIS Express.
(I can't use alternative methods of including snippets (eg asp) as this code also has to run on non-IIS servers.)
Comment: IIS Express ships with Server Side Includes module, so you might try it out.
Answer: It has nothing to do with the file being .asp or not. You just need proper configuration.
I had the SSI module already installed and configured as part of IIS Express (I'm using Visual Studio 2017 Community Edition), although I found some articles suggesting that it needs to be installed separately.
In applicationHost.config file, there's this entry in the handlers section:
<add name="SSINC-shtml" path="*.shtml" verb="GET,HEAD,POST" modules="ServerSideIncludeModule" resourceType="File" />

This means that your file needs to be of .shtml extension to be handled by the SSI module. Add an entry for yourself in your web.config file:
<configuration>
<system.webServer>
    <handlers>
        <add name="SSINC-html" path="*.html" verb="*" modules="ServerSideIncludeModule" resourceType="File" />
    </handlers>
</system.webServer>

Now SSI will work with ordinary HTML files.
Answer: It seems that the only way to get SSI to work is to rename my '.htm' and '.html' files to '.asp'.  Then the SSI syntax works.
Which is a bit of a pain because I need to run the same code on non-IIS servers...
Answer: Have a look at:
http://vlads-hideout.blogspot.com/2013/05/server-side-include-in-iis-express.html
It is somewhat dated. The configuration file now can be found in the invisible ".vs" folder which is created by Visual Studio automatically inside your project folder. ".vs\config\applicationhost.config".
It already contains the globalModules entry:
        <add name="ServerSideIncludeModule" image="%IIS_BIN%\iis_ssi.dll" />

and the following entries in /:
            <add name="SSINC-stm" path="*.stm" verb="GET,HEAD,POST" modules="ServerSideIncludeModule" resourceType="File" />
            <add name="SSINC-shtm" path="*.shtm" verb="GET,HEAD,POST" modules="ServerSideIncludeModule" resourceType="File" />
            <add name="SSINC-shtml" path="*.shtml" verb="GET,HEAD,POST" modules="ServerSideIncludeModule" resourceType="File" />

So SSI is activated automatically for "*.SHTML", For example.
If you do want to modify your default document or HTML files extensions, you can just put a clone of one of these configuration statements into the / section of your web.config and change the extension appropriately.
Answer: After a long and arduous search for a fix for this problem on several occasions over the last two years, I figured out the problem many of us were having.
ASHRAF has the correct answer but I did not read carefully enough. His config file addition/change is for the .HTML file. I was adding it for the file BEING INCLUDED (*.inc) not the file doing the including (.html). Notice this line is for .html files

Thanks ASHRAF.


Compute the norm of bounded operators

Question: Compute the norm of the following operators.

a) Let $\hat{A}: \ell^2 \to \ell^2 $ be the operator given as follows
\begin{equation}
\hat{A} (x_1, x_2, ..., x_n, ...)^t \mapsto (x_1+x_2, x_2+x_3, ... , x_n+x_{n+1}, ...)^t
\end{equation}
For some $x = (x_1, x_2, ...)^t \in \ell^2$.

My attempt:
I want to find a relation between the norms $\| Ax \|$ and $\| x \|$, s.t. $\| Ax \| \leq K\| x \|$. Then conclude that
\begin{equation}
K = \sup_{x\in \ell^2} \frac{\| Ax \|}{\| x \|}
\end{equation}
So for some $x \in \ell^2$
\begin{align}
\| Ax \|^2 &= \sum_{i=1}^{\infty} |x_i+x_{i+1}|^2 \\
&= \sum_{i=1}^{\infty} \left( |x_i|^2 + |x_{i+1}|^2 + 2\ \Re [x_i^{\ast} x_{i+1}] \right) \\
\end{align}
where $^{*}$ is the conjugate operation.
I couldn't manage to find a bound for that real part.

b) Let $\hat{B}:\mathcal{H} \to \mathcal{H} $ be an operator defined in a finite Hilbert space ($\text{dim}\ \mathcal{H} =N$), s.t.
\begin{equation}
M^2 = \text{max} \left( \sum_{i=1}^{N} B_{ij}^{\ast} B_{ik} \right), \quad \forall j,k
\end{equation}
where $B_{ij}$ are the entries of the matrix in a orthonormal basis.

My attempt:
I tried to do a similar procedure. So for some $x \in \mathcal{H}$
\begin{align}
\| Bx \|^2 &= (Bx \ | \ Bx) \\
&= \sum_{j,k=1}^{N} \left( \sum_{i=1}^{N} B_{ij}^{\ast} B_{ik} \right) x_j^{\ast} x_k \\
&\leq M^2 \sum_{j,k=1}^{N} x_j^{\ast} x_k
\end{align}
Since
\begin{align}
0 &\leq \Bigg| \sum_{j=1}^{N} x_j - \sum_{k=1}^{N} x_k\ \Bigg|^2  \\
&\leq \Bigg|\sum_{j=1}^{N} x_j\ \Bigg|^2 + \Bigg|\sum_{k=1}^{N} x_k\ \Bigg|^2 - 2\ \Re \left[ \sum_{j=1}^{N} x_j^{\ast} \sum_{k=1}^{N} x_k \right]
\end{align}
we have
\begin{align}
2  \sum_{j=1}^{N} x_j^{\ast} \sum_{k=1}^{N} x_k \leq \Bigg|\sum_{j=1}^{N} x_j\ \Bigg|^2 + \Bigg|\sum_{k=1}^{N} x_k\ \Bigg|^2
\end{align}
But I don't know how to put all together.
I hope someone can go through it and help me for the points which are left. Thanks!!
Comment: How do you define the operator in the finite dimensional case. Perhaps this way $$Ax=(x_1+x_2,x_2+x_3,\ldots, x_n+x_1)$$
Comment: I just want to compute the infinite dimensional case.
Answer: For the infinite dimensional case the operator is if the form $A=I+S,$ where $S$ is the shift operator $$Sx=(x_2,x_3,\ldots )$$ We have $$\|A\|\le 1+\|S\|=2$$
On the other hand for $$x^{(n)}=(1,1,\ldots,1,0,0,\ldots)$$ with $n$ entries equal $1$ we get $$Ax^{(n)}=2x^{(n-1)}+e_n,$$ where $e_n$ denotes the sequence with $0$ entries except for the $n$th one equal $1.$ Thus
$$\|Ax^{(n)}\|\ge 2\sqrt{n-1}\quad \|x^{(n)}\|=\sqrt{n}$$
Hence $\|A\|\ge 2,$ i.e.$\|A\|=2.$
For the finite dimensional case we have $A=I+S$ where $$Sx=(x_2,x_3,\ldots, x_n,x_1)$$ Then $\|A\|\le 2.$ Moreover $$A(1,1,\ldots,1)=2(1,1,\ldots,1)$$ hence $\|A\|=2.$
Comment: Very helpful! However, by "in finite and infinte dimensions" I meant that $A$ and $B$ are infinite and finite dimensions, respectively.

Compute the norm of bounded operators


How to get the name of a key in array

Question: This sounds quite simple, but i can't make it work. I'm trying to group keys with same value. I can get the key number but i cant get the name of the Key. i.e "London, Berlin".
This is my code:
$countries = array (
   'London' => 'Europe/London',
   'Istanbul' => 'Europe/Istanbul',
   'Rome' => 'Europe/Rome',
   'Berlin' => 'Europe/Berlin',
   'Athens' => 'Europe/Athens',
);

$offsets = Array();
foreach ($countries as $country_offset) {
   $offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );

   array_push($offsets, $offset);
}

$result = array_unique($offsets);
asort($result);

$keys = array_keys($result);
foreach($keys as $key) {
   $numb = array_keys($offsets, $offsets[$key]);

   echo $offsets[$key] . ' - ' . implode(', ', $numb ) . '
';
}

Comment: i dont understand what the desired output of this should be
Comment: Maybe you are looking for this: http://php.net/manual/en/function.array-search.php
Comment: @Dagon The name of the Key `'London' => 'Europe/London'`. The desired output `London`.
Comment: you can't map the keys anymore from the output, you've transformed it into another form, just create another container which contains all pertinent data so that you can have all info
Comment: The hole output is something like this `7200 - 2, 3`.
What i'm trying to do is to have names instead of index number i.e.
`7200 - Rome, Berlin`
Answer: I'd suggest just create the full info array grouping first that includes the key that you want, instead of creating the presentation mapping the key of the original input.
Idea:
$offsets = array(); // initialize
foreach($countries as $key => $country_offset) { // grouping
    $offset = timezone_offset_get( new DateTimeZone( $country_offset ), new DateTime() );
    $offsets[$offset][] = array(
        'name'      => $key, // include me instead!
        'offset'    => $offset,
        'timezome'  => $country_offset,
    );
}
ksort($offsets); // sort

The important bit here is that, group them inside a container using the offset as your key:
$offsets[$offset][] = array(
//       ^ reassignment grouping using the offset as key

Then, in your presentation, decide what you want:
// presentation
foreach($offsets as $offset => $info) {
    echo $offset . ' - ';
    $temp = array();
    foreach($info as $t) {
        $temp[] = $t['name'];
    }
    echo implode(', ', $temp);
    echo '
';
}

If array_column is available, just use it:
foreach($offsets as $offset => $info) {
    echo $offset . ' - ' . implode(', ', array_column($info, 'name')) . '
';
}

Sample Output
Comment: Bingo! Work like a charm. I've tried different ways but couldn't find this way. Thank you very much. :)
Comment: @Avel sure glad this helped
Answer:  <?php
$countries = array (
   'London' => 'Europe/London',
   'Istanbul' => 'Europe/Istanbul',
   'Rome' => 'Europe/Rome',
   'Berlin' => 'Europe/Berlin',
   'Athens' => 'Europe/Athens',
);

$out=array();
foreach ($countries as $country_offset=>$c) {
   $offset = timezone_offset_get( new DateTimeZone( $c ), new DateTime() );

$out[$offset][]=$country_offset;
}
//print_r($out);

foreach($out as $x=>$y){

echo $x.': '.implode(',',$y).'
';
}

//output:
3600: London
10800: Istanbul,Athens
7200: Rome,Berlin
Comment: Works either this way. Thank you very much. :)

How to get the name of a key in array


Func with out parameter

Question: Can I pass a method with an out parameter as a Func?
public IList<Foo> FindForBar(string bar, out int count) { }

// somewhere else
public IList<T> Find(Func<string, int, List<T>> listFunction) { }

Func needs a type so out won't compile there, and calling listFunction requires an int and won't allow an out in.
Is there a way to do this?
Answer: ref and out are not part of the type parameter definition so you can't use the built-in Func delegate to pass ref and out arguments. Of course, you can declare your own delegate if you want:
delegate V MyDelegate<T,U,V>(T input, out U output);

Comment: In C# 4 (2010) and later (was not released when you wrote your answer) it is possible to mark `T` as contravariant, and `V` as covariant. However, since a parameter (`output`) of type `U` is passed ***by reference***, `U` cannot be marked co- or contravariant and must remain "invariant". So consider `public delegate V MyDelegate(T input, out U output);` if you use C# 4 or later.
Comment: See [this example for using `ref` parameter with `in` and `out` parameters](http://stackoverflow.com/a/24044772/175679).
Answer: Why not create a class to encapsulate the results?
public class Result
{
     public IList<Foo> List { get; set; }
     public Int32 Count { get; set; }
}

Comment: Because `new`ing-up a `class` object for every result will incur the GC tax, which is significant for high-frequency operations (so consider using `ValueTuple` instead).
Answer: The Func family of delegates (or Action for that matter) are nothing but simple delegate types declared like
//.NET 4 and above
public delegate TResult Func<out TResult>()
public delegate TResult Func<in T, out TResult>(T obj)

//.NET 3.5
public delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 obj1, T2 obj2, T3 obj3)

etc. Delegates as such can have out/ref parameters, so in your case its only a matter of custom implementation by yourself as other answers have pointed out. As to why Microsoft did not pack this by default, think of the sheer number of combinations it would require.
delegate TResult Func<T1, T2, TResult>(T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, T2 obj2)
delegate TResult Func<T1, T2, TResult>(T1 obj1, out T2 obj2)
delegate TResult Func<T1, T2, TResult>(out T1 obj1, out T2 obj2)

for just two parameters. We have not even touched ref. It would actually be cumbersome and confusing for developers.
Comment: Note that C# function overloading cannot distinguish between `delegate TResult Func(T1 obj, T2 obj)` and `delegate TResult Func(out T1 obj, T2 obj)`.  So besides the number of overloads symbol name are an other reason for why Microsoft could not add these overloads of `Func`.
Comment: Can someone refer me to an MSDN article on the delegates above?
Comment: @SuLlewellyn I couldnt find the original msdn article, but you could try: https://learn.microsoft.com/en-us/dotnet/api/system.func-2?view=netframework-4.7.2, https://learn.microsoft.com/en-us/dotnet/api/system.action?view=netframework-4.7.2
Answer: You could wrap it in a lambda/delegate/function/method that exposed the right interface and called FindForBar, but I suspect that FindForBar has count as an out parameter as a reason, so you'd need to be sure throwing that information away was ok/safe/desirable/had the right results (you'd need to be sure of this even if you could just directly pass in FindForBar).

Func with out parameter


Best way to convert all strings in List to a single comma separated string

Question:
Possible Duplicate:
Most efficent way of joining strings

I have a List.  What would be the best possible way to create a single sting having all the strings in  List but separated by ','.
Thanks in advance
Answer: Probably:
var str = string.Join(",", yourList);

If you aren't using .NET Framework 4, the overload for IEnumerable is missing so you need to convert it to an array first:
var str = string.Join(",", yourList.ToArray());

You can read more about string.Join at MSDN.
Comment: Very nice that they finally included this overload in .NET 4. Prior to that, the only option was to pass in a `string[]` ...which is essentially explained in this answer...therefore there is no reason for my comment. :)
Answer: One of several options:
var concat = String.Join(",", mylist.ToArray());

Answer: public string getStringFromList(List<string> inputList){
    string returnString = "";
    if(inputList.length < 1)return returnString;
    foreach(string s in inputList){
      returnString += s + ",";
    }
    returnString = returnString.Substring(returnString.length - 2);//remove extra ","
    return returnString
}

Comment: `returnString -= ","` is not valid.
Comment: Oops! Thank you @vcsjones, I fixed the solution.
Answer: Fun with Iterators!
Define a Delimit extension method (shown below) and you can do this:
result = string.Concat(values.Delimit(","));

(All extension methods are contained in a code sample at the bottom)
Why would you want to have a Delimit extension method, when string.Join would work perfectly fine in this sceanrio?
Well, you could take it a step further by adding an overload that takes prefix and suffix parameters.  You could use this to produce a CSV string, for example, as shown below:
// replace " with ""
var escapedValues = values.Select(x => x.Replace("\"", "\"\""));
result = string.Concat(escapedValues.Delimit(",", "\"", "\""));

Take it yet another step further and add an overload with "intelligent" (i.e. delegate) delimiters.  For example, below shows the same CSV approach as above, but this time values are only surrounded by quotes if they contain whitespace or a comma:
char[] quotables = new char[] { ' ', '\t', '\r', '\n', ',' };
var result3 = string.Concat(escapedValues.Delimit(
    (previous, current) => ",", // always separate with a comma
    // but only surround with quotes if the value contains whitespace or an embedded comma
    current => current.IndexOfAny(quotables) < 0 ? null : "\"",
    current => current.IndexOfAny(quotables) < 0 ? null : "\""));

Ok, all of these previous examples can still be accomplished by some combination of existing Linq methods and the string.Join method.  The following examples demonstrate some things that, I think, can't be done with those built-in methods.
You can have variable separators. The following example separates integers with either "<", ">", or "=" depending on the two values being separated.  This example also uses an overload that takes a Func<int, string> convert parameter:
var rng = new Random();
int[] integers = new int[100];
for (int i = 0; i < integers.Length; i++)
    integers[i] = rng.Next(0, 100);

result = string.Concat(integers.Delimit(
    (current) => current.ToString(), // convert int to string
    // separate with either "<", ">", or "="
    (previous, current) => (previous < current) ? " < " : (previous > current) ? " > " : " = ",
    // no prefix or suffix
    null,
    null));

Output:  9 < 46 = 46 < 76 < 98 > 63 < 93 > 70 ...
Finally, not that this is something that one should necessarily do, but for the purposes of demonstration, suppose you have a list of web UI controls (List<System.Web.UI.Control>), and you want to insert an HTML  control before each TextBox control:
result = controls.Delimit(
    null, // no separator
    (current) => {
        var textbox = current as System.Web.UI.WebControls.TextBox;
        if (textbox == null)
            return null;
        // prefix all TextBox controls with a  element
        var label = new System.Web.UI.HtmlControls.HtmlGenericControl("label");
        label.Attributes["for"] = textbox.ClientID;
        label.InnerText = textbox.Attributes["name"];
        return label; },
    null); // no suffix

Below are the extension methods used by the code examples above:
static class DelimitExtensions
{
    public static IEnumerable<T> Delimit<T>(this IEnumerable<T> source, T separator)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                yield return enumerator.Current;

                while (enumerator.MoveNext())
                {
                    yield return separator;

                    yield return enumerator.Current;
                }
            }
        }
    }

    public static IEnumerable<T> Delimit<T>(this IEnumerable<T> source, T separator, T prefix, T suffix)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                yield return prefix;
                yield return enumerator.Current;
                yield return suffix;

                while (enumerator.MoveNext())
                {
                    yield return separator;

                    yield return prefix;
                    yield return enumerator.Current;
                    yield return suffix;
                }
            }
        }
    }

    public static IEnumerable<T> Delimit<T>(this IEnumerable<T> source, Func<T, T, T> separator, Func<T, T> prefix, Func<T, T> suffix)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                if (prefix != null)
                    yield return prefix(enumerator.Current);

                yield return enumerator.Current;

                if (suffix != null)
                    yield return suffix(enumerator.Current);

                T previous = enumerator.Current;

                while (enumerator.MoveNext())
                {
                    if (separator != null)
                        yield return separator(previous, enumerator.Current);

                    if (prefix != null)
                        yield return prefix(enumerator.Current);

                    yield return enumerator.Current;

                    if (suffix != null)
                        yield return suffix(enumerator.Current);

                    previous = enumerator.Current;
                }
            }
        }
    }

    public static IEnumerable<TOut> Delimit<TIn, TOut>(this IEnumerable<TIn> source, Func<TIn, TOut> convert, Func<TIn, TIn, TOut> separator, Func<TIn, TOut> prefix, Func<TIn, TOut> suffix)
    {
        using (var enumerator = source.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                if (prefix != null)
                    yield return prefix(enumerator.Current);

                yield return convert(enumerator.Current);

                if (suffix != null)
                    yield return suffix(enumerator.Current);

                TIn previous = enumerator.Current;

                while (enumerator.MoveNext())
                {
                    if (separator != null)
                        yield return separator(previous, enumerator.Current);

                    if (prefix != null)
                        yield return prefix(enumerator.Current);

                    yield return convert(enumerator.Current);

                    if (suffix != null)
                        yield return suffix(enumerator.Current);

                    previous = enumerator.Current;
                }
            }
        }
    }
}