Selecting the correct software licence suited to my needs?

Question: I have a few applications that I will be uploading to CodePlex in the very near future.
Anybody is free to look at the source code and use it in their own applications but all I ask is that I am recognised as the original developer of the code and that it cannot be used in any commercial application without my permission.
I have looked at Jeff's overview of licences but i'm still a bit confused as to which licence is best suited for my requirements.
There may be a time where I wish the code to only be used with my permission only, is it possible to change the terms of the licence after the code has been published?
Thanks
Comment: I'm voting to close this question as off-topic because it is about licensing and legal issues, not programming or software development. [See here](http://meta.stackoverflow.com/a/274964/1402846) for details, and the [help/on-topic] for more.
Answer:
is it possible to change the terms of
  the licence after the code has been
  published?

This is a subject of some debate, but the consensus seems to be that you cannot revoke a license. In other words, if you change or add licences, the users who obtained and  use your work under the original license are not affected.
Answer: When you add a project to codeplex it will let you choose a license. Infact you wont be able to publish without choosing a license for you project. Best thing would be to read through every license listed and choose the best.
I always choose the Microsoft Public License (Ms-PL)
Answer: As far as I know, there isn't a license barring commercial usage; even the super-strict GPL lets derivatives be sold.
Although it's not recommended for software, I might go with a Creative Commons license in this situation, specifically the Attribution-Noncommercial license (here's a license with U.K. as the jurisdiction).
This license will require people give credit to you, while giving them the freedom to use it for a noncommercial project. It also has a clause allowing people to ask for your permission to override the license (i.e. use commercially).
Comment: P.S. I found out that you can't use any license you want; I'm leaving my answer though, in case the OP decides to use a different project hosting site that lets you use any license of your choosing, like GitHub.
Comment: Thank you for the nice explanation, I have decided to use the Ms-PL licence for the time being and if I decide to change my hosting site i'll be sure to take your points in consideration.


Change the color of an object with class

Question: I want to change the color of all elements with class='nav-button' using JS. I've tried the code below, but it doesn't seem to work. I think it doesn't recognize 'style' in the 4th line. Not sure why, I've seen plenty of examples where people use it.
var elements = document.getElementsByClassName('nav-button')

for (i = 0; i < elements.length; i++) {
    elements[i].firstChild.style.color = 'red';
}

Any solutions?
Edit: the first child item is necessary because there is an  element inside of the nav-button
Comment: Remove `firstChild` and your code will work. Like this `elements[i].style.color = 'red';`
Answer: I don't think you need firstChild as the code below worked for me.
var elements = document.getElementsByClassName('nav-button')

Array.from(elements).forEach(el => el.style.color = 'red')

Comment: I needed firstChild, because there was a  element inside the 'nav-button'
Answer: The getElementsByClassName function returns an HTMLCollection instead of an array, so you can't iterate through it. You can achieve it by spreading the collection values in an array, like this:
[...elements]

And then you can use it like this: [...elements].forEach(el => el.style.color = 'red')
Comment: And that collection has length and is array-like so this is not accurate. Nothing wrong with OP's `for` loop approach
Comment: True, I mistook it for the NodeList, which I thought you couldn't loop through, but you can too, my bad
Comment: People were looping through them long before spread, forEach and `for of` all came along
Answer: Assuming you want to change the color of the firstChild of each element with class nav-button, try using firstElementChild instead of firstChild:
var elements = document.getElementsByClassName('nav-button')

for (let e of elements) {
    e.firstElementChild.style.color = 'red';
}

Answer: You can iterate on the collection and you don't need to use a variable for that:
for (let el of document.getElementsByClassName('nav-button')) {
    el.style.color = 'red'
}

Answer: I don't know if you have a purpose using "firstChild" or maybe you copy pasted from somewhere.
But, simply you have to remove firstChild on line 4!

const elements = document.getElementsByClassName('nav-button');

for (let i = 0; i < elements.length; i++) {
    elements[i].style.color = 'red';
};
<button class="nav-button">1</button>
<button class="nav-button">2</button>
<button class="nav-button">3</button>


Can you make all Wordpress pages Private simultaneously without a plugin?

Question: I have a Wordpress installation with thousands of pages that are all public which I need to make private. I can't use a plugin to help me; I need to do it using Wordpress' built in Public/Protected/Private paradigm.
Ideally, I would run a search and replace on an SQL export of the database. Alternatively, I would be willing to write a PHP script to handle it.
It is not an option to make all pages private manually - I am looking for a programmatic method for dealing with this problem.
Can anyone help?
Answer: Just set them to private in the database, using the following query:
UPDATE `wp_posts` SET `post_status` = 'private';

This would set all posts to private, I guess you won't really use that query.
Instead, to only set articles to 'private' use:
UPDATE `wp_posts` SET `post_status` = 'private' WHERE `post_type` = 'post';

and to only disable pages, use:
UPDATE `wp_posts` SET `post_status` = 'private' WHERE `post_type` = 'page';

Post-revisions have the status 'inherit' and thus get the right inherited from the parent page or article.
Comment: @Khior I guess that's the same. I've tried to set an article from 'public' to 'private' in the backend and the status switched in the database.
Comment: Is there any such way I can edit the 'Visibility' of a page without editing it's 'Status'? (http://en.support.wordpress.com/pages/page-visibility/)
Comment: It would be good to know exactly how Visibility is set (there must be some distinction in the data between the two) but the status method will work for my purposes. Thank you =)
Answer: As Feeela said: you can run query directly on the table, or you can use WP function like:
using have_post and the_post
    $my_posts['ID'] = get_the_ID();
    $my_posts['post_status']  = 'private';
    $my_posts['post_type'] = 'page';
    wp_update_post( $my_post );

Answer: UPDATE `wp_posts` SET `post_status` = 'private' WHERE `post_type`='page';

This query will only set  the pages to private
Answer: Here the Steps to make WordPress page private.

Go to Page. Click Add New option. For editing the old Pages, go to    pages> All Posts and find the existing Page you'd like to edit.
Find the Visibility and click on Edit. Select the Private option and Click    OK.
Click on Publish.


Can people who own the Necromancer and people who don't play together?

Question: My friends have the Diablo 3 Battle Chest version of the game and I want to play as the Necromancer in the Eternal Collection version.
So I was wondering: would I be able to use the character even though the others don't have it?
(Just wanted to make sure so I don't waste my money)
Answer: According to Reddit, yes.
Your friends won't have access to the class, that's about it.
Comment: I can also confirm this as a player that is playing as Necromancer along with a long time Demon Hunter main friend who (obviously) doesn't own the Necromancer DLC. The only thing player needs to play multi player coop is Reaper of Souls DLC.
Comment: That steam quote appears to be for a different game.


can't build my app apk with buildozer in Google Colab?

Question: I watched a short tutorial with deploying kivy/kivymd apps to apk, i have done everything but mine won't build,
<code>[DEBUG]:    <-------------> 0% INITIALIZING [35ms]
[DEBUG]:    <-------------> 0% CONFIGURING [135ms]> root project > Resolve dependencies of :classpath<-------------> 0% CONFIGURING [235ms]> root project > Resolve files of :classpath<-------------> 0% CONFIGURING [335ms]> root project<-------------> 0% CONFIGURING [436ms]<-------------> 0% CONFIGURING [535ms]<-------------> 2% EXECUTING [635ms]> :preDebugBuild<===----------> 28% EXECUTING [736ms]> :mergeDebugResources<====---------> 34% EXECUTING [835ms]> :processDebugManifest<=====--------> 40% EXECUTING [935ms]> :processDebugResources<======-------> 48% EXECUTING [1s]> :compileDebugJavaWithJavac<======-------> 48% EXECUTING [2s]
[DEBUG]:    > Task :compileDebugJavaWithJavac
[DEBUG]:    Note: Some input files use or override a deprecated API.
[DEBUG]:    Note: Recompile with -Xlint:deprecation for details.
[DEBUG]:    Note: Some input files use unchecked or unsafe operations.
[DEBUG]:    Note: Recompile with -Xlint:unchecked for details.
[DEBUG]:
[DEBUG]:
[DEBUG]:    <========-----> 65% EXECUTING [2s]> :mergeDebugAssets<========-----> 65% EXECUTING [3s]<========-----> 65% EXECUTING [4s]<========-----> 65% EXECUTING [5s]<========-----> 65% EXECUTING [6s]<========-----> 68% EXECUTING [6s]> :transformClassesWithDexBuilderForDebug<========-----> 68% EXECUTING [7s]<=========----> 74% EXECUTING [7s]> :transformDexArchiveWithDexMergerForDebug<==========---> 77% EXECUTING [7s]> :mergeDebugJniLibFolders<==========---> 80% EXECUTING [8s]> :transformNativeLibsWithMergeJniLibsForDebug<==========---> 82% EXECUTING [8s]> :transformNativeLibsWithStripDebugSymbolForDebug
[DEBUG]:    > Task :transformNativeLibsWithStripDebugSymbolForDebug
[DEBUG]:    /root/.buildozer/android/platform/android-ndk-r19c/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-strip:/content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/build/intermediates/transforms/mergeJniLibs/debug/0/lib/armeabi-v7a/gdb.setup: File format not recognized
[DEBUG]:
[DEBUG]:    Unable to strip library '1' due to error /root/.buildozer/android/platform/android-ndk-r19c/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-strip returned from '/content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/build/intermediates/transforms/mergeJniLibs/debug/0/lib/armeabi-v7a/gdb.setup', packaging it as is.
[DEBUG]:
[DEBUG]:
[DEBUG]:    <============-> 94% EXECUTING [8s]> :packageDebug<============-> 94% EXECUTING [9s]
[DEBUG]:    > Task :packageDebug FAILED
[DEBUG]:
[DEBUG]:    FAILURE: Build failed with an exception.
[DEBUG]:
[DEBUG]:    * What went wrong:
[DEBUG]:    Execution failed for task ':packageDebug'.
[DEBUG]:    > org.gradle.tooling.BuildException (no error message)
[DEBUG]:
[DEBUG]:    * Try:
[DEBUG]:    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
[DEBUG]:
[DEBUG]:    * Get more help at https://help.gradle.org
[DEBUG]:
[DEBUG]:    Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
[DEBUG]:    Use '--warning-mode all' to show the individual deprecation warnings.
[DEBUG]:    See https://docs.gradle.org/6.4.1/userguide/command_line_interface.html#sec:command_line_warnings
[DEBUG]:
[DEBUG]:    BUILD FAILED in 10s
[DEBUG]:    27 actionable tasks: 27 executed
[DEBUG]:
[DEBUG]:
[DEBUG]:    <-------------> 0% WAITING> IDLE
Exception in thread background thread for pid 156314:
Traceback (most recent call last):
  File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.7/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/usr/local/lib/python3.7/dist-packages/sh.py", line 1637, in wrap
    fn(*rgs, **kwargs)
  File "/usr/local/lib/python3.7/dist-packages/sh.py", line 2561, in background_thread
    handle_exit_code(exit_code)
  File "/usr/local/lib/python3.7/dist-packages/sh.py", line 2265, in fn
    return self.command.handle_command_exit_code(exit_code)
  File "/usr/local/lib/python3.7/dist-packages/sh.py", line 865, in handle_command_exit_code
    raise exc
sh.ErrorReturnCode_1:

  RAN: /content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/gradlew assembleDebug

  STDOUT:

<-------------> 0% INITIALIZING [35ms]
<-------------> 0% CONFIGURING [135ms]> root project > Resolve dependencies of :classpath<-------------> 0% CONFIGURING [235ms]> root project > Resolve files of :classpath<-------------> 0% CONFIGURING [335ms]> root project<-------------> 0% CONFIGURING [436ms]<-------------> 0% CONFIGURING [535ms]<-------------> 2% EXECUTING [635ms]> :preDebugBuild<===----------> 28% EXECUTING [736ms]> :mergeDebugResources<====---------> 34% EXECUTING [835ms]> :processDebugManifest<=====--------> 40% EXECUTING [935ms]> :processDebugResources<======-------> 48% EXECUTING [1s]> :compileDebugJavaWithJavac<======-------> 48% EXECUTING [2s]
> Task :compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

<========-----> 65% EXECUTING [2s]> :mergeDebugAssets<========-----> 65% EXECUTING [3s]<========-----> 65% EXECUTING [4s]<========-----> 65% EXECUTING [5s]<========-----> 65% EXECUTING [6s]<========-----> 68% EXECUTING [6s]> :transformClassesWithDexBuilderForDebug<========-----> 68% EXECUTING [7s]<=========----> 74% EXECUTING [7s]> :transformDexArchiveWithDexMergerForDebug<==========---> 77% EXECUTING [7s]> :mergeDebugJniLibFolders<==========---> 80% EXECUTING [8s]> :transformNativeLibsWithMergeJniLibsForDebug<==========---> 82% EXECUTING [8s]> :transformNativeLibsWithStripDebugSymbolForDebug
> Task :transformNativeLibsWithStripDebugSymbolForDebug
/root/.buildozer/android/platform/android-ndk-r19c/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-strip:/content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/build/intermediates/transforms/mergeJniLibs/debug/0/lib/armeabi-v7a/gdb.setup: File format not recognized

Unable to strip library '1' due to error /root/.buildozer/android/platform/android-ndk-r19c/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/bin/arm-linux-androideabi-strip returned from '/content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/build/intermediates/transforms/mergeJniLibs/debug/0/lib/armeabi-v7a/gdb.setup', packaging it as is.

<============-> 94% EXECUTING [8s]> :packageDebug<============-> 94% EXECUTING [9s]
> Task :packageDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':packageDebug'.
> org.gradle.tooling.BuildException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 10s
27 actionable tasks: 27 executed

<-------------> 0% WAITING> IDLE

  STDERR:

[INFO]:    STDOUT (last 20 lines of 40):
    FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':packageDebug'.
> org.gradle.tooling.BuildException (no error message)

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.4.1/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 10s
27 actionable tasks: 27 executed

<-------------> 0% WAITING> IDLE
[INFO]:    STDERR:

[INFO]:    COMMAND:
cd /content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a && /content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/gradlew assembleDebug

[WARNING]: ERROR: /content/.buildozer/android/platform/build-armeabi-v7a/dists/sto__armeabi-v7a/gradlew failed!
WARNING: Received a --sdk argument, but this argument is deprecated and does nothing.
No setup.py/pyproject.toml used, copying full private data into .apk.
Applying Java source code patches...
Applying patch: src/patches/SDLActivity.java.patch
WARNING: Received a --sdk argument, but this argument is deprecated and does nothing.
No setup.py/pyproject.toml used, copying full private data into .apk.
Applying Java source code patches...
Applying patch: src/patches/SDLActivity.java.patch
# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain apk --debug --bootstrap=sdl2 --dist_name sto --name STO --version 0.1 --package org.test.sto --minsdk 21 --ndk-api 21 --private /content/.buildozer/android/app --android-entrypoint org.kivy.android.PythonActivity --android-apptheme @android:style/Theme.NoTitleBar --orientation portrait --window --copy-libs --arch armeabi-v7a --color=always --storage-dir="/content/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21
# ENVIRONMENT:
#     CUDNN_VERSION = '188.8.131.52'
#     PYDEVD_USE_FRAME_EVAL = 'NO'
#     LD_LIBRARY_PATH = '/usr/local/nvidia/lib:/usr/local/nvidia/lib64'
#     CLOUDSDK_PYTHON = 'python3'
#     LANG = 'en_US.UTF-8'
#     HOSTNAME = '4bc76ba1c227'
#     OLDPWD = '/'
#     CLOUDSDK_CONFIG = '/content/.config'
#     NVIDIA_VISIBLE_DEVICES = 'all'
#     DATALAB_SETTINGS_OVERRIDES = '{"kernelManagerProxyPort":6000,"kernelManagerProxyHost":"172.28.0.3","jupyterArgs":["--ip=\\"172.28.0.2\\""],"debugAdapterMultiplexerPath":"/usr/local/bin/dap_multiplexer"}'
#     ENV = '/root/.bashrc'
#     PAGER = 'cat'
#     NCCL_VERSION = '2.7.8'
#     TF_FORCE_GPU_ALLOW_GROWTH = 'true'
#     JPY_PARENT_PID = '47'
#     NO_GCE_CHECK = 'True'
#     PWD = '/content'
#     HOME = '/root'
#     LAST_FORCED_REBUILD = '20210323'
#     CLICOLOR = '1'
#     DEBIAN_FRONTEND = 'noninteractive'
#     LIBRARY_PATH = '/usr/local/cuda/lib64/stubs'
#     GCE_METADATA_TIMEOUT = '0'
#     GLIBCPP_FORCE_NEW = '1'
#     TBE_CREDS_ADDR = '172.28.0.1:8008'
#     TERM = 'xterm-color'
#     SHELL = '/bin/bash'
#     GCS_READ_CACHE_BLOCK_SIZE_MB = '16'
#     PYTHONWARNINGS = 'ignore:::pip._internal.cli.base_command'
#     MPLBACKEND = 'module://ipykernel.pylab.backend_inline'
#     CUDA_VERSION = '11.0.3'
#     NVIDIA_DRIVER_CAPABILITIES = 'compute,utility'
#     SHLVL = '1'
#     PYTHONPATH = '/env/python'
#     NVIDIA_REQUIRE_CUDA = ('cuda>=11.0 brand=tesla,driver>=418,driver<419 '
 'brand=tesla,driver>=440,driver<441 brand=tesla,driver>=450,driver<451')
#     COLAB_GPU = '0'
#     GLIBCXX_FORCE_NEW = '1'
#     PATH = '/root/.buildozer/android/platform/apache-ant-1.9.4/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/tools/node/bin:/tools/google-cloud-sdk/bin:/opt/bin'
#     LD_PRELOAD = '/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4'
#     GIT_PAGER = 'cat'
#     _ = '/usr/local/bin/buildozer'
#     PACKAGES_PATH = '/root/.buildozer/android/packages'
#     ANDROIDSDK = '/root/.buildozer/android/platform/android-sdk'
#     ANDROIDNDK = '/root/.buildozer/android/platform/android-ndk-r19c'
#     ANDROIDAPI = '27'
#     ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full
</code>
Here's my build spec:
<code>[app]

# (str) Title of your application
title = Myapp

# (str) Package name
package.name = app

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,wav,gif

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin

# (list) List of exclusions using pattern matching
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy,kivymd,python-for-android,libffi

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (list) Garden requirements
#garden_requirements =

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 1.9.1

#
# Android specific
#

# (bool) Indicate if the application should be fullscreen or not
fullscreen = 0

# (string) Presplash background color (for new android toolchain)
# Supported formats are: #RRGGBB #AARRGGBB or one of the following names:
# red, blue, green, black, white, gray, cyan, magenta, yellow, lightgray,
# darkgray, grey, lightgrey, darkgrey, aqua, fuchsia, lime, maroon, navy,
# olive, purple, silver, teal.
#android.presplash_color = #FFFFFF

# (list) Permissions
#android.permissions = INTERNET

# (int) Target Android API, should be as high as possible.
#android.api = 27

# (int) Minimum API your APK will support.
#android.minapi = 21

# (int) Android SDK version to use
#android.sdk = 20

# (str) Android NDK version to use
#android.ndk = 19b

# (int) Android NDK API to use. This is the minimum API your app will support, it should usually match android.minapi.
#android.ndk_api = 21

# (bool) Use --private data storage (True) or --dir public storage (False)
#android.private_storage = True

# (str) Android NDK directory (if empty, it will be automatically downloaded.)
#android.ndk_path =

# (str) Android SDK directory (if empty, it will be automatically downloaded.)
#android.sdk_path =

# (str) ANT directory (if empty, it will be automatically downloaded.)
#android.ant_path =

# (bool) If True, then skip trying to update the Android sdk
# This can be useful to avoid excess Internet downloads or save time
# when an update is due and you just want to test/build your package
# android.skip_update = False

# (bool) If True, then automatically accept SDK license
# agreements. This is intended for automation only. If set to False,
# the default, you will be shown the license when first running
# buildozer.
# android.accept_sdk_license = False

# (str) Android entry point, default is ok for Kivy-based app
#android.entrypoint = org.renpy.android.PythonActivity

# (str) Android app theme, default is ok for Kivy-based app
# android.apptheme = "@android:style/Theme.NoTitleBar"

# (list) Pattern to whitelist for the whole project
#android.whitelist =

# (str) Path to a custom whitelist file
#android.whitelist_src =

# (str) Path to a custom blacklist file
#android.blacklist_src =

# (list) List of Java .jar files to add to the libs so that pyjnius can access
# their classes. Don't add jars that you do not need, since extra jars can slow
# down the build process. Allows wildcards matching, for example:
# OUYA-ODK/libs/*.jar
#android.add_jars = foo.jar,bar.jar,path/to/more/*.jar

# (list) List of Java files to add to the android project (can be java or a
# directory containing the files)
#android.add_src =

# (list) Android AAR archives to add (currently works only with sdl2_gradle
# bootstrap)
#android.add_aars =

# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
#android.gradle_dependencies =

# (list) add java compile options
# this can for example be necessary when importing certain java libraries using the 'android.gradle_dependencies' option
# see https://developer.android.com/studio/write/java8-support for further information
# android.add_compile_options = "sourceCompatibility = 1.8", "targetCompatibility = 1.8"

# (list) Gradle repositories to add {can be necessary for some android.gradle_dependencies}
# please enclose in double quotes
# e.g. android.gradle_repositories = "maven { url 'https://kotlin.bintray.com/ktor' }"
#android.add_gradle_repositories =

# (list) packaging options to add
# see https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.PackagingOptions.html
# can be necessary to solve conflicts in gradle_dependencies
# please enclose in double quotes
# e.g. android.add_packaging_options = "exclude 'META-INF/common.kotlin_module'", "exclude 'META-INF/*.kotlin_module'"
#android.add_gradle_repositories =

# (list) Java classes to add as activities to the manifest.
#android.add_activities = com.example.ExampleActivity

# (str) OUYA Console category. Should be one of GAME or APP
# If you leave this blank, OUYA support will not be enabled
#android.ouya.category = GAME

# (str) Filename of OUYA Console icon. It must be a 732x412 png image.
#android.ouya.icon.filename = %(source.dir)s/data/ouya_icon.png

# (str) XML file to include as an intent filters in <activity> tag
#android.manifest.intent_filters =

# (str) launchMode to set for the main activity
#android.manifest.launch_mode = standard

# (list) Android additional libraries to copy into libs/armeabi
#android.add_libs_armeabi = libs/android/*.so
#android.add_libs_armeabi_v7a = libs/android-v7/*.so
#android.add_libs_arm64_v8a = libs/android-v8/*.so
#android.add_libs_x86 = libs/android-x86/*.so
#android.add_libs_mips = libs/android-mips/*.so

# (bool) Indicate whether the screen should stay on
# Don't forget to add the WAKE_LOCK permission if you set this to True
#android.wakelock = False

# (list) Android application meta-data to set (key=value format)
#android.meta_data =

# (list) Android library project to add (will be added in the
# project.properties automatically.)
#android.library_references =

# (list) Android shared libraries which will be added to AndroidManifest.xml using <uses-library> tag
#android.uses_library =

# (str) Android logcat filters to use
#android.logcat_filters = *:S python:D

# (bool) Copy library instead of making a libpymodules.so
#android.copy_libs = 1

# (str) The Android arch to build for, choices: armeabi-v7a, arm64-v8a, x86, x86_64
android.arch = armeabi-v7a

# (int) overrides automatic versionCode computation (used in build.gradle)
# this is not the same as app version and should only be edited if you know what you're doing
# android.numeric_version = 1

#
# Python for android (p4a) specific
#

# (str) python-for-android fork to use, defaults to upstream (kivy)
#p4a.fork = kivy

# (str) python-for-android branch to use, defaults to master
#p4a.branch = master

# (str) python-for-android git clone directory (if empty, it will be automatically cloned from github)
#p4a.source_dir =

# (str) The directory in which python-for-android should look for your own build recipes (if any)
#p4a.local_recipes =

# (str) Filename to the hook for p4a
#p4a.hook =

# (str) Bootstrap to use for android builds
# p4a.bootstrap = sdl2

# (int) port number to specify an explicit --port= p4a argument (eg for bootstrap flask)
#p4a.port =

#
# iOS specific
#

# (str) Path to a custom kivy-ios folder
#ios.kivy_ios_dir = ../kivy-ios
# Alternately, specify the URL and branch of a git checkout:
ios.kivy_ios_url = https://github.com/kivy/kivy-ios
ios.kivy_ios_branch = master

# Another platform dependency: ios-deploy
# Uncomment to use a custom checkout
#ios.ios_deploy_dir = ../ios_deploy
# Or specify URL and branch
ios.ios_deploy_url = https://github.com/phonegap/ios-deploy
ios.ios_deploy_branch = 1.7.0

# (str) Name of the certificate to use for signing the debug version
# Get a list of available identities: buildozer ios list_identities
#ios.codesign.debug = "iPhone Developer: <lastname> <firstname> (<hexstring>)"

# (str) Name of the certificate to use for signing the release version
#ios.codesign.release = %(ios.codesign.debug)s

[buildozer]

# (int) Log level (0 = error only, 1 = info, 2 = debug (with command output))
log_level = 2

# (int) Display warning if buildozer is run as root (0 = False, 1 = True)
warn_on_root = 1

# (str) Path to build artifact storage, absolute or relative to spec file
# build_dir = ./.buildozer

# (str) Path to build output (i.e. .apk, .ipa) storage
# bin_dir = ./bin

#    -----------------------------------------------------------------------------
#    List as sections
#
#    You can define all the "list" as [section:key].
#    Each line will be considered as a option to the list.
#    Let's take [app] / source.exclude_patterns.
#    Instead of doing:
#
#[app]
#source.exclude_patterns = license,data/audio/*.wav,data/images/original/*
#
#    This can be translated into:
#
#[app:source.exclude_patterns]
#license
#data/audio/*.wav
#data/images/original/*
#

#    -----------------------------------------------------------------------------
#    Profiles
#
#    You can extend section / key with a profile
#    For example, you want to deploy a demo version of your application without
#    HD content. You could first change the title to add "(demo)" in the name
#    and extend the excluded directories to remove the HD content.
#
#[app@demo]
#title = My Application (demo)
#
#[app:source.exclude_patterns@demo]
#images/hd/*
#
#    Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug

    log with log_level = 2
</code>
please help! at first their was a warning that lld was not found, so i went ahead and installed it, now there's a new warning about Context python recipe found, please help
Comment: Did you found any solution
Answer: If are using a 32-bit version of python it won't work and make sure the file is named main.py and in build.spec file don't name the application as my app I just changed the name of the app and it worked.
upload your main.py file to google colab and run these commands:
<code>!pip install buildozer

!pip install cython==0.29.19

!pip install kivymd

!pip install python-for-android

!sudo apt install lld

!sudo apt-get install -y \
    python3-pip \
    build-essential \
    git \
    python3 \
    python3-dev \
    ffmpeg \
    libsdl2-dev \
    libsdl2-image-dev \
    libsdl2-mixer-dev \
    libsdl2-ttf-dev \
    libportmidi-dev \
    libswscale-dev \
    libavformat-dev \
    libavcodec-dev \
    zlib1g-dev

!sudo apt-get install -y \
    libgstreamer1.0 \
    gstreamer1.0-plugins-base \
    gstreamer1.0-plugins-good

!sudo apt-get install build-essential libsqlite3-dev sqlite3 bzip2 libbz2-dev
zlib1g-dev libssl-dev openssl libgdbm-dev libgdbm-compat-dev liblzma-dev
libreadline-dev libncursesw5-dev libffi-dev uuid-dev libffi6

!sudo apt-get install libffi-dev

!buildozer init

!buildozer -v android debug deploy run

!buildozer android clean
</code>


vb.net - problem making a call from one usercontrol to another form

Question: I have a tabcontrol that creates tab pages from a "User Control" I created (a separate form in vb.net) using this code: (MainTab is the separate user control I created which has text boxes etc in it)
Dim tmpTab As New MainTab
myTabControl.TabPages.Add()
Dim tmpTabCount As Integer = myTabControl.TabPages.Count
myTabControl.TabPages.Item(tmpTabCount - 1).Controls.Add(tmpTab)
myTabControl.TabPages.Item(tmpTabCount - 1).Text = "Untitled"

I'm using the devexpress xtratab control so the code might look a bit different than the default vb.net tab control.
Now in my MainTab user control file file, I can't for the life of me figure out how to call a control in the form1 where the xtra tab control is placed on. "Me.Parent.Dispose" works for closing the tab when executed via the MainTab control, but that's as far as I can get for communicating with the parent from.
Does anyone know the solution? I'm not sure if I have to reference something in the MainTab user control or what in order to communicate with any objects on the default form1.
Answer: Generally speaking, I avoid making my child controls cognizant of the parent. It leads to unpleasant coupling more often than I care for.
Consider adding a custom event to your MainTab class that your form can subscribe to. When you want to pass a message to the form, your user control can invoke the method, and your form's event handler can process it accordingly. This pattern helps keep your user control pluggable into other forms by reducing its dependency on its parent.
Creating a user control event in a windows form is discussed in this MSDN article:
http://msdn.microsoft.com/en-us/library/aa302342.aspx
Comment: After some more trial/error I managed to get the following to work, is this "safe" to use?
        Dim tmpParentForm As Form = Me.FindForm()
        If Not tmpParentForm Is Nothing Then
Comment: Should be fine. Depending on your circumstances, you may choose also go cast `tmpParentForm` to the form's type in order to gain access to your custom public methods.


C++ I don't know what it means to use "this" and "std::placeholders::_1" when using the callback function

Question: I am trying to make a server by looking at the sample code of cpprestSDK.
But I don't know why I bind in the sample code.
Below is the sample code.
stdafx.h
class Handler{
public:
    Handler() {};
    Handler(utility::string_t url);

    pplx::task<void> open() { return m_listener.open(); }
    pplx::task<void> close() { return m_listener.close(); }

private:
    void handle_get(http_request request);
    void handle_put(http_request request);
    void handle_post(http_request request);
    void handle_del(http_request request);
};

hander.cpp

#include "stdafx.hpp"

Handler::Handler(utility::string_t url) : m_listener(url)
{

    m_listener.support(methods::GET, std::bind(&Handler::handle_get, this, std::placeholders::_1));
    m_listener.support(methods::PUT, std::bind(&Handler::handle_put, this, std::placeholders::_1));
    m_listener.support(methods::POST, std::bind(&Handler::handle_post, this, std::placeholders::_1));
    m_listener.support(methods::DEL, std::bind(&Handler::handle_del, this, std::placeholders::_1));
}

Looking at the reference for support, it is defined as follows.
void support (const http::method &method, const std::function< void(http_request)> &handler)
I thought I could define it like this:
m_listener.support(methods::GET, &Handler::handle_get);
But it failed.
Can you tell me why I use "this" and "std::placeholders::_1" when doing a bind?
sample code : https://learn.microsoft.com/ko-kr/archive/blogs/christophep/write-your-own-rest-web-server-using-c-using-cpp-rest-sdk-casablanca
cpprestSDK listener reference : https://microsoft.github.io/cpprestsdk/classweb_1_1http_1_1experimental_1_1listener_1_1http__listener.html
Comment: _"I thought I could define it like this_" - and, if you could, how would the compiler know what instance to call that method on? it can't. that's why binding is required, to create a callable that encapsulates not only the identify of a member but also an instance on which to use it.
Answer: The member function
void support (const http::method &method,
              const std::function< void(http_request)> &handler)

expects handler to be a callable which has

an argument of type http_request
a return type void.

A plain function void handle(http_request) would match this required signature.
If you want to register a (non-static) member function this is also possible but you have to provide the object as well (as non-static member functions may not be called without object).
The std::bind(&Handler::handle_get, this, std::placeholders::_1) acts as (a kind of) adapter to fit your member function (with this as bound object) into that requirement.
The std::placeholders::_1 denotes, where to bind the argument (of type http_request) into the wrapped member function call.
A simpler way would be to use a lambda as adapter (instead of the bind):
m_listener.support(methods::GET, [this](http_request http_req) { this->handle_get(http_req); });

or even:
m_listener.support(methods::GET, [this](http_request http_req) { handle_get(http_req); });

Further readings:

std::bind
std::placeholders


Are these steps for refreshing a patio floor correct?

Question: My patio floor needs refreshing. While at it, I'd like to avoid the boring gray and use a hint of color, either gray-blue or gray-green.

Here are the steps that I have planned:

Lower the nails (by turning a little) to avoid that they rip the sanding paper.
Sand the surface with grit 80-100 using a floor sander.
Insert either the tip or the edge of a belt sander to sand the rounded edges, however far I can reach, with grit 120.
Sand the top surface with grit 200-220 using a floor sander. Don't bother fine-sanding the rounded parts since even someone walking barefoot will not notice the difference.
Apply one coat of "Low-Lustre Enamel Porch & Patio Floor Paint".

Do I have these steps right? Is there any surprise waiting for me?
One additional worry is that I will not even touch the (inaccessible) back side. Is there any chance that the planks would buckle from the different treatment after I'm done?
Answer: Tightening the screws is really important you might want to replace some with slightly longer as the holes over time will not hold well (if they hold you are golden). sanding with a coarse grit to get the paint off is a good idea to help reduce the high spots also the heavy weathering After sanding you will wand to clean the deck to remove the dust from the grain and screw heads. I have used a product that home depot sells called Restore. this looks nice but I think it comes in brown and Tan. Restore will help hide the heavy weathering and you really don't need to finish sand only rough sand or pressure wash to get rid of the loose paint. I have refinished horribly weathered decks with Restore that came out looking really nice. The first one was 6-8 years ago and it still looks close to the way it did when I put it down. No matter what you use the boards are "dry" other than minor water penetration and you should have no problems with cupping or warping. Exposed boards really warp and or cup much faster than sealed boards.
Comment: If I understand correctly from a sample video on Home Depot's web site, Restore will make a wooden deck look like it's a concrete deck. It will in any case hide all the grains. I'd actually like to go in the opposite direction. If the wood grain can be salvaged, I'd like to highlight it rather than conceal it.
Comment: With some of the wether checking I see you will need to replace at least 1 plank in the deck I did not think it looked like cement because the 2x6 planks were there on the first and 3rd decks I did. Even the second that was a white wood Doug fur/ hemlock with no spaces turned out well and the owner was thrilled and has asked me to do more jobs. If you want wood grain you will have more work than sanding and sanding. Weathered and or very rough wood is hard to restore , it usually requires the rough/ rotten wood to be removed . With an old deck in rough shape this is not possible


How to cast 'Any?' to a struct with flexible generic properties?

Question: I'm using a 3rd party library that in my use case is handing me down a '[Any?]' array. This array contains equatable struct objects which are defined as follows:
struct SplitValue<L: Equatable, R: Equatable> {
    public var left: L?
    public var right: R?

    public init(left: L?, right: R?){
        self.left = left
        self.right = right
    }
}

extension SplitValue: Equatable {
    public static func ==(lhs: SplitValue, rhs: SplitValue) -> Bool {
        return lhs.left == rhs.left && lhs.right == rhs.right
    }
}

And this is a simple example of the array I'm dealing with:
var values = [Any?]()
values.append(SplitValue<String, Int>(left: "a", right: 12))
values.append(SplitValue<Double, String>(left: 33.1, right: "b"))

Now let's say I cannot predict which value types are found in the SplitValue.left and SplitValue.right properties. It could be a String, Int, NSManagedObject, or anything else equatable. All I have is the values array.
Next I want to loop through this array and read out the left and right values. For this I believe I have to cast 'Any?' to 'SplitValue' because the following doesn't work:
print(values.first!.left)
// error: value of type 'Any?' has no member 'left'

I also tried things like this, but that obviously doesn't work either:
print(values.first! as SplitValue<Any, Any>)
// error: type 'Any' does not conform to protocol 'Equatable'

So the problem is that I can't cast 'Any?' to the right type since I don't know what it will be. What might be the solution to this, preferably without having to change the definition of the struct or values array?
Answer: What you can do is to create a protocol without the generic types and have SplitValue implement that:
protocol AnySplitValue {
    var l: Any? { get }
    var r: Any? { get }
}

Then, conform SplitValue to the protocol:
extension SplitValue: AnySplitValue {
    var l: Any? {
        return self.left
    }

    var r: Any? {
        return self.right
    }
}

Now, you can do this to print all the left values out:
values.forEach { print(($0 as! AnySplitValue).l!) }

We have kind of "erased" the generic types!


what does memtest86+ serial console mean

Question: In the GRUB, there are 2 options for memory test, memtest86+ and memtest86+ serial console 115200. What the first one means is obvious, it just runs memtest86+, but what does that serial console mean in the second option?
Comment: if running memtest86 on a *headless* device, you're able to access the memtest from a remote screen connected to serial port using speed 115,200bps.
Comment: Thanks guiverc, can you please post that as an answer?
Answer: Two options.

memtest86+; used for boxes that have a screen attached

memtest86+ serial console 115200; used for headless boxes that have a serial terminal/console attached; the 115,200 is the speed (115,200 bps) or the fastest old serial connections (think RS232; well before USB) could reliably achieve before needing to modulate-demodulate signal etc


Graph of a continuous function has measure zero

Question: I need help to solve the following problem:
Let $f: \mathbb{R}^n \rightarrow \mathbb{R}$ be a continuous function. Prove that the graph $G(f)=\{(x,f(x)):x\in\mathbb{R}^n\}$ has measure zero in $\mathbb{R}^{n+1}$.
I suppose that I have to use that f es uniformly continuous, but I don't know what rectangle which sum of volumes is less than $\varepsilon > 0$ should I take.
Comment: You should state your restrictions in the question, otherwise you will waste the time of answerers!
Comment: I must prove it without using Fubini. Only the definition of measure zero and the properties of a continuous function.
Comment: Since it is continuous, you can enclose the graph in a collection of rectangles with arbitrarily small area. Split the domain into compact rectangles and use uniform continuity. Stitch the answer together.
Comment: Try Fubini. ${}{}{}$
Comment: First show (or use, if accepted as known) that a continuous function on a compact space is uniformly continuous. Then show this proves the graph of the restriction of $f$ to a compact ball has measure zero. Finally, $\mathbb R^n$ is a countable union of compact balls.
Answer: It is sufficient to show that the set $G'=\{(x,f(x)) | x \in [0,1)^n \}$ has measure zero.
Let $\epsilon>0$, then since $f$ is uniformly continuous on the compact set
$[0,1]^n$, there is some $\delta>0$ such that if $\forall x,x' \in [0,1): \|x-x'\|_\infty < \delta$ (note convenient choice of norm) then
$|f(x)-f(x')| < \epsilon$.
Now choose $n$ such that ${ 1\over n} < \delta$ and, with $k = (k_1,...,k_n)$, let $x_k = {k \over n}$ and
$R_k = \{x_k\} + [0,{1 \over n})^n$,
where each of the $k_i$ range through $0,...,n-1$. Note that
$\sum_k m R_k = m [0,1)^n = 1$.
Note that
for $x \in R_k$, we have $|f(x)-f(x_k)| < \epsilon$, hence
$\{ (x,f(x)) \}_{x \in R_k} \subset R_k \times [f(x_k)-\epsilon, f(x_k) + \epsilon]$
and so
$m \{ (x,f(x)) \}_{x \in R_k} \le m R_k \cdot m [f(x_k)-\epsilon, f(x_k) + \epsilon]  = 2 \epsilon \, m R_k$.
Hence $m G' \le 2 \epsilon \sum_k  \, m R_k = 2 \epsilon$.
Since $\epsilon>0$ was arbitrary, we have $m G' = 0$.
Comment: @Invisible Yes & yes. ${k \over n}$ is the 'bottom left' corner of the boxes.
Comment: could I ask why it suffices to show that the $G'$ you defined has measure 0?
Comment: @HossienSahebjame The same analysis will apply to any cube of the form $[a,b)^n$. We can cover $\mathbb{R}^n$ with a countable number of cubes of this form and the measure of the union of a countable collection of measure zero sets will itself have measure zero.
Comment: ahh got it thanks! like a countable way of covering the reals?
Comment: @copper.hat Sorry for ma follow-up, but may I ask, does $m$ denote measure and do you/we claim every point in $[0,1)^n$ can be written in form of $$\frac{k}n+v, k\in\{0,\ldots,n-1\}^n,v\in \left[0,\frac1n\right)^n$$?
Answer: Here's another argument. Assuming the graph is measurable, use Fubini-Tonelli to show that its measure is equal to an iterated integral:
$$ m(G) = \int_{{\mathbb R}^n} \int_{{\mathbb R}} {\bf 1}_{\{f(x)\}}(y) dy dx = \int_{{\mathbb R}^n} 0 dx =0,$$
where the second equality is due to the fact that the Lebesgue measure of the singleton $\{y:y=f(x)\}$ is zero for any $x$.
Now for the measurability of $G$. It's a closed set.  Why ? Take $(x,y)$ not in $G$. Then $f(x)\ne y$. Therefore by continuity of $f$, there exists a neighborhood $I$ of  $x$ and a neighborhood of  $J$ of $y$ such that for all $x \in I$, $f(x)\not\in J$. That is, $I\times J\subset G^c$.
Answer: I thought of a more simpler solution I think. So assume $\epsilon > 0$ to be given. Choose $0<\epsilon_0<\dfrac{\epsilon}{b-a}$. Now, by uniform continuity,
$$
\forall \epsilon_0 > 0,  \exists \delta(\epsilon_0): \forall x,y \in [a,b], |x-y| < \delta(\epsilon_0) \rightarrow |f(x)-f(y)| < \epsilon_0
$$
so for our chosen $\epsilon_0$, we get a corresponding $\delta(\epsilon_0)$ that satisfies the above.
Now, we want to stack countable number of rectangles on our graph so that they cover the graph and have a total volume less than $\epsilon$. To do this, we would need $n=\dfrac{b-a}{\delta(\epsilon_0)}$ number of rectangles of width $\delta(\epsilon_0)$ arranged edge to edge. Now, we choose the height of each rectangle to be $\epsilon_0$.
Then, all these would cover the entire graph and would have a total volume
$$=n \cdot \epsilon_0 \cdot \delta(\epsilon_0)= \dfrac{b-a}{\delta(\epsilon_0)} \cdot \delta(\epsilon_0) \cdot \epsilon_0 = (b-a)\cdot \epsilon_0 < \epsilon$$
Where the last inequality works by our choice of $\epsilon_0$. This satifies the definiton of measure zero. Hence the graph has measure zero.


Variable used as iterator doesn't change its value within nested loops in Python

Question: I have the following piece of code within my script and I'm using the variable cubecnt as iterator to parse through all the files I have. It should go from 0 to parts_total, but it doesn't seem to be working. How can I modify the code in order to have the iterator working properly?
parts_total = 5
rgx_start = re.compile(r'End of powder drop')  # Line just before the start of the layer code: "; End of powder drop"
for cubecnt in range(0, (parts_total + 1)):
    for layercnt in range(0, (layers_total + 1)):
        f_path = ("{}{}{}{}".format(f_folder, f_name, cubecnt, f_ext))  # Complete path of the part to be loaded
        if layercnt == 0:
            start_i = 0
        else:
            start_i = int(prev_start[cubecnt][layercnt - 1])
        with open(f_path, 'r') as gcodesep:  # Opening each file separately
            part_gcode = gcodesep.readlines()
            for i, line in enumerate(part_gcode[start_i + 1:]):  # Searching for the beginning of given layer
                if rgx_start.search(line):
                    if (cubecnt == 0):
                        layer_start = start_i + i + 1
                    else:
                        layer_start = start_i + i + 2 # Avoid the step down for the layer thickness twice
                    prev_start[cubecnt][layercnt] = layer_start
                    break
        layercnt =+ 1
    cubecnt =+ 1

Comment: And why do you think it doesn't increment? This is not a minimal reproducible example, so you need to provide more info
Comment: @JoanLaraGanau: converting a not answer ffrom a user that does not has enough reputation to comment in a true comment is a nice thing. When I do, I just try to give credit to the original poster, because I find it more fair...
Comment: The very last statement of your code, `cubecnt =+ 1`. What do you think that is supposed to do? If you think it increments `cubecnt`, it doesn't. And why would you want to anyway since the `for cubecnt in range ...` automatically does the incrementing for you? Try evaluating `x = 10; x =+ 1` and see what `x` is.
Answer: The range function also has a 'step' argument, so maybe that's what you actually want to use. There is no point in using cubecnt =+ 1, as at the start of each iteration of the loop, cubecnt is given the value in the range object.


Why does the second build screen only display "more..." in original Civilization?

Question: When I click of "change" in a city in original Civilization and then "more...", I have the following screen :

There should be the list of city improvement.  Is that a known bug?
Is there a work around?
This is version 475.01.
Comment: Looks like a bug to me.
Comment: Have you tried pressing either/both of the "More..." prompts on the blank screen?  I kind of remember seeing this, but it's been a long time.
Comment: @agent86 clicking on the first "More..." does nothing.  The second one close the gray square (same as clicking outside of the gray square).
Comment: Whoa, *this* is what the original Civilization looked like? Civ II came leaps and bounds!
Answer: I went back in my save game and checked at each turn, it is caused by the number of element in the second screen being too high (about 32).
Answer: Because the problem is caused by having too many choices of improvements to build in the city, the work-around is to build wonders in cities that have not yet run into this problem.
The most effective wonder to build is Hoover Dam on the same continent, because it substitutes for Power Plant, Hydro Plant, and Nuclear Plant.  It thus reduces the improvement choices by 3 or 4.
As shown in the original post, the wonder that is most likely to trigger this bug is Apollo Program, because it enables SS Structural, SS Component, and SS Module.  It thus increases the improvement choices by a net of 2.


Win 8 App fails suspend cert when running from 'Project - Store' but passes when running WACK separately

Question: When I run the Windows App Cert Kit (WACK) against my 'Release' install of my app on my machine, all the tests pass fine, when I go to: Project -> Store -> Create App Packages... and run the WACK at the end of that, it always fails on the Performance Test, specifically the 'Suspend' process.
What is the difference?
Is it the same WACK version that is running in VS2012 RTM compared to the one started via the SDK?
Answer: They are the same version of WACK. All "Project -> Store -> Create App Packages" does is run the kit on your application. My assumption would be that Visual Studio is causing your computer to run a bit sluggishly, and as such is causing the application to fail WACK while it's running. I've seen the same thing happen while running WACK in a Virtual Machine.
Is Visual Studio running when you run with a passing result? Are there any other differences on your system when you get the passed rating? My assumption would be that the application is fine with a passed rating, but if you submit it for certification and it fails because of Suspend/Resume, I'd inquire further.
Comment: I don't think it's the computer, when I run WACK independently, typically I have 4-5 instances of VS running at the same time.. This is the only difference I get, everything else passes.

However, I presumed along similar lines to you, that the problem is to do with VS, I submitted it, and it has just passed the Technical Compliance, so it seems ok


Sync Desktop with online account?

Question: I am using Ubuntu 16.04, Is there a way to keep my desktop synced with an online account (like Dropbox or google drive) so any file I create/edit on my desktop gets updated automatically to the online account and vice versa ?
Answer: I use Sparkleshare for that. Think of Sparkle as "auto git". All file modifications are committed and sent to remote. Works well, with the power of git version management you have full history. You'll need another system that allows ssh connections with sparkle also.
We tried a multiuser Sparkle and setup collapsed because one user anned a copy of a git project by accident and a mysterious recursion developed that filled up a hard disk.
No such trouble happened with one user setups.
We have also had good results with OwnCloud. Server side config is slightly more elaborate there. Behaves almost exactly like Dropbox for workstations.
Comment: Good answer actually but looks like what I need is not possible for free.
You inspired me though, I am thinking about a python script that would run on intervals or something to sync the desktop content with some other folder some where else and that other folder may be synced in turn with Dropbox; thus free, private, auto sync.

Sync Desktop with online account?


How come this print function for linked list works?

Question: I have a struct defined as:
typedef struct node Node;
struct node {
  char val;
  Node* tail;
};

I initiate a linked list like so:
Node* header;
Node node_one;
node_one.val = 'a';
node_one.tail = 0;
header = &node_one;

And then I keep adding nodes to this list. Now when I use the below print function for this linked list, it works the way it is expected to work:
void printlist(Node* header) {
    do{
        printf("%c ", header->val);
        header = header->tail; // aren't we modifying the header itself here?
    } while(header->tail!=0);

    printf("%c --> NULL", header->val);
}

Called from main() as printlist(header);
So far so good. What I don't get is, without making any changes to the list, when I call this print function the second, third, fourth time, it always works. It prints the elements of the list. But what I was expecting was that this function would only work once because I am modifying the header pointer itself so shouldn't I lose the list in the memory after running this print function once? How come it works more than once?
Comment: Have a look at Binky Pointer Fun Video C++: https://www.youtube.com/watch?v=i49_SNt4yfk
Answer: Probably the header in the function below is a local variable(local to the function printlist). So your original header (header in the main) is not changing at all. So, whenever you call this function it is still printing the list.
void printlist(Node* header){
    do{
        printf("%c ", header->val);
        header = header->tail; // aren't we modifying the header itself here?
    }while(header->tail!=0);
    printf("%c --> NULL", header->val);
 }

Answer: It's because the header you use in the printlist() body is not the same header than the one you refer to in main().  These are to different variables that just happen to have the same name.
You can experiment with this principle by chaning the name of header in printlist(): call it for example mylist, and the whole programme will still work.
Comment: Yes, `header` is not a global variable and the pointer I declare in `main()` has the name `header`. So is it like this? When I call `printlist(header);` it makes a copy of `header` which is a pointer, and making a copy of that pointer will mean that the copy is pointing to the same location as `header` itself. So in `printlist()` what I am modifying is not `header` itself but its copy? That's how I am able to run that function over and over?
Comment: Yes exactly !  You got it !
Comment: I totally skipped the fact that even if it's a pointer I'm passing to a function, unless I'm passing the address of it, I am just passing a copy. Thank you and Shantanu for your answers.


GSuite Alert Center API returns 'customer id could not be inferred from the request or caller identity.' error

Question: I am trying to get a list of alerts from the GSuite Alert Center API in a Node JS application.
I created a Service Account at the IAM & Admin page, checked the Enable G Suite Domain-wide Delegation checkbox, and generated a JSON file with access keys set.
Then I went to the Admin Console -> Security -> API controls -> Domain-wide Delegation and registered the Service Account by its Client ID with the https://www.googleapis.com/auth/apps.alerts scope.
The code was taken from the example provided in google-api-nodejs-client and basically looks like
const { google } = require('googleapis');
const alertcenter = google.alertcenter('v1beta1');

const auth = new google.auth.GoogleAuth({
   keyFile: 'Path/to/my/file/with/accessKeys'
   scopes: ['https://www.googleapis.com/auth/apps.alerts'],
});
const client = await auth.getClient();
google.options({auth: client});

const res = await alertcenter.alerts.list();

What I am getting back from the API is the 'customer id could not be inferred from the request or caller identity.' error message.
I tried to pass the customer ID as a parameter to the list() method since it is described as its legit parameter. Like this
const res = await alertcenter.alerts.list({ customerId: 'my-customer-id' });

As a result, I only got another error message: Request contains an invalid argument.
What do I do wrong?
Answer: Hey I had this same issue and it drove me a bit mad.
I found that the authorisation needs a user email associated with the 'customer' that is required in the credentials. This email needs to be from an account of a user that has access to the alert center.
This is required in the 'subject' parameter of the authorisation credentials.
I couldn't do this through the GoogleAuth object as it doesnt, but through using the JWT, which is similar
I followed my nose from the python issue people had here
https://github.com/googleapis/google-api-python-client/issues/777
const {google} = require('googleapis');

const scopes = ['https://www.googleapis.com/auth/apps.alerts'];
const credentials = require("Path/to/my/file/with/accessKeys");

// email with access to alert center
const auth_email = 'firstname.lastname@example.com';

async function runSample() {
    const authClient = new google.auth.JWT({
        email:credentials.client_email,
        key: credentials.private_key,
        scopes: scopes,
        subject: auth_email
    });

    authClient.authorize(function(err, tokens) {
        if (err) {
            console.log(err);
            return;
        } else {
            authClient.setCredentials(tokens);
        }
    });

    google.options({
        auth: authClient
    });

    const alertcenter = google.alertcenter('v1beta1');

    const res = await alertcenter.alerts.list();

    console.log(res.data);

    return res.data;
}

if (module === require.main) {
    runSample().catch(console.error);
  }

  // Exports for unit testing purposes
  module.exports = {runSample};

This is working for me now - there may be another way to assign the subject/email to the authorisation with GoogleAuth  but I can't figure it out.


Can i use Id in DAI IMA SDK instead of video Url and adTag Url in android

Question: DAI IMA SDK in android uses adTag Url instead of ID as fetched from sample apps provided by google from
"https://support.google.com/dfp_premium/answer/7298842?hl=en".
"https://github.com/googleads/googleads-ima-android/releases/tag/3.6"
While in iOS and ROKU, DIA IMA SDK uses ID to fetch adTag Url. Can we fetch adTagUrl from ID through DAI IMA SDK in android also? Please advice.
Answer: Refer: "https://github.com/googleads/googleads-ima-android-dai"
Here example is given of ima-SDK using DAI


Why Kotlin do not allow any code in primary constructor?

Question: It cause inconvenience when work with code blelow
abstract class View {
    abstract fun findViewById(id: Int): View
    abstract fun setOnClickListener(listener: (View) -> Boolean)
}

class ViewHolder(itemView: View) {
    init {
        child1.setOnClickListener { false }
    }
    val child1 = itemView.findViewById(1)
    val child2 = itemView.findViewById(2)
}

The compiler complains that:
Kotlin: Variable 'child1' must be initialized

So I have to add an additional function and call it every time after construction:
class ViewHolder(itemView: View) {
    val child1 = itemView.findViewById(1)
    val child2 = itemView.findViewById(2)

    fun bindEventHandlers() {
        child1.setOnClickListener { false }
    }
}

val vh = ViewHolder(v)
vh.bindEventHandlers()

So, is there any convenient way to do init things like this? This often happens when work with Android RecyclerView & ListView.
Comment: Marvin, the answer below appears to answer your question, did you try this?
Answer: Define your properties before your init block -
class ViewHolder(itemView: View) {
    val child1 = itemView.findViewById(1)
    val child2 = itemView.findViewById(2)

    init {
        child1.setOnClickListener { false }
    }
}

Comment: Marvin did not have an init block -- it seems he did not realize that init blocks are the Kotlin Way. But that solves his problem without answering the question: why does Kotlin require forbidding code in the body of the constructor, requiring the programmer to put it all in an init block instead?


service not as advertised

Question: I am trying to add a new sysV service on an Ubuntu 18.04 host. However the service command does not behave as described in the manual - despite the presence of a file in /etc/init.d, "service" complains there is no systemd service file:
firstname.lastname@example.com:/etc/init.d# ls -l /etc/init.d/my-test-app
lrwxrwxrwx 1 root root 32 Mar 16 10:58 /etc/init.d/my-test-app -> /var/services/my-test.jar
email@example.com:/etc/init.d#
firstname.lastname@example.com:/etc/init.d#
email@example.com:/etc/init.d# service my-test-app status
Unit my-test-app.service could not be found.
firstname.lastname@example.com:/etc/init.d#
firstname.lastname@example.com:/etc/init.d#
firstname.lastname@example.com:/etc/init.d# /etc/init.d/my-test-app status
Running [9519]
email@example.com:/etc/init.d#

Is it because I am using a symlink? Something else?
Comment: AFAIK the backward compatibility between systemd and SysV relies on `systemd-sysv-generator`, which might not get invoked outside of a full restart (although you could see if `systemctl daemon-reload` is sufficient) - see for example [How does systemd use /etc/init.d scripts?](https://unix.stackexchange.com/a/233581/65304)
Comment: @steeldriver: thanks, yes, running `systemctl daemon reload` sort of resolved the issue. But it things it is Inactive while the initscript reports it is running - but I get this with packaged sysV inits too. I'm really learning to hate systemd. If you repost as an answer, I'll accept it.
Answer: Backward compatibility between systemd and the SysV init system relies on hooks provided by systemd-sysv-generator, as descibed here:

How does systemd use /etc/init.d scripts?

Generators should be run automatically on boot, however if you want to avoid rebooting it appears to be possible to run them on demand by invoking
systemctl daemon-reload

From man systemctl:

   daemon-reload
       Reload the systemd manager configuration. This will rerun all
       generators (see systemd.generator(7)), reload all unit files, and
       recreate the entire dependency tree. While the daemon is being
       reloaded, all sockets systemd listens on behalf of user
       configuration will stay accessible.

service not as advertised


Using Ubuntu to save a dying HDD, disk completely unreadable, even though it works on other OS

Question: I have an old dying hard drive with loads of faulty sectors that I'm trying to save as much data from as I can (before ultimately throwing it out). Using ddrescue on my laptop on macOS did wonders, I was able to save about 95% of data from the drive, but scraping the last bits around the bad sectors is very slow since the -d option (direct disk access bypassing the kernel cache) of ddrescue is not available on macOS.
For this reason, I resorted to using my old RasperryPi 3b with Ubuntu 20.04 LTS and just let ddrescue run on there for a couple of days to scrape the last bits of data from the drive.
However, when I connect the drive to the RPi, I can't use it at all. It shows up in lsblk with the correct size, but any read operation on the drive just freezes. After connecting, the drive spins up, then, after a couple of seconds, there is a noticable click (which I assume is the head of the HDD snapping back). This sound repeats every 10-25 seconds and AFAIK is a typical sign of a dying drive. When I connect the drive to my mac however there are no clicks and the non-bad-areas are perfectly readable.
I checked the syslog and it shows some read errors on various sectors on the disk, which strikes me as odd, since I never mounted the disk in the first place (and don't plan to either, ddrescue recommends to not even mount the drive to cause as little potential damage as possible).
This is the syslog after I connected the drive, waited for exactly five clicks, and then disconnected the drive again:
Oct 23 17:46:34 qtpi kernel: [  681.381739] usb 1-1.2: new high-speed USB device number 4 using dwc_otg
Oct 23 17:46:35 qtpi kernel: [  681.524105] usb 1-1.2: New USB device found, idVendor=174c, idProduct=55aa, bcdDevice= 1.00
Oct 23 17:46:35 qtpi kernel: [  681.524123] usb 1-1.2: New USB device strings: Mfr=2, Product=3, SerialNumber=1
Oct 23 17:46:35 qtpi kernel: [  681.524138] usb 1-1.2: Product: ASMT1051
Oct 23 17:46:35 qtpi kernel: [  681.524152] usb 1-1.2: Manufacturer: asmedia
Oct 23 17:46:35 qtpi kernel: [  681.524166] usb 1-1.2: SerialNumber: 123456789012
Oct 23 17:46:35 qtpi kernel: [  681.592932] usb 1-1.2: UAS is blacklisted for this device, using usb-storage instead
Oct 23 17:46:35 qtpi kernel: [  681.592946] usb-storage 1-1.2:1.0: USB Mass Storage device detected
Oct 23 17:46:35 qtpi kernel: [  681.598080] usb-storage 1-1.2:1.0: Quirks match for vid 174c pid 55aa: 400000
Oct 23 17:46:35 qtpi kernel: [  681.598254] scsi host0: usb-storage 1-1.2:1.0
Oct 23 17:46:35 qtpi kernel: [  681.598774] usbcore: registered new interface driver usb-storage
Oct 23 17:46:35 qtpi kernel: [  681.613963] usbcore: registered new interface driver uas
Oct 23 17:46:36 qtpi kernel: [  682.630848] scsi 0:0:0:0: Direct-Access     ASMT     2105             0    PQ: 0 ANSI: 6
Oct 23 17:46:36 qtpi kernel: [  682.632467] sd 0:0:0:0: Attached scsi generic sg0 type 0
Oct 23 17:46:36 qtpi kernel: [  682.635097] sd 0:0:0:0: [sda] Spinning up disk...
Oct 23 17:46:51 qtpi kernel: [  683.653711] ...............ready
Oct 23 17:46:58 qtpi kernel: [  704.774566] sd 0:0:0:0: [sda] 586114704 512-byte logical blocks: (300 GB/279 GiB)
Oct 23 17:46:58 qtpi kernel: [  704.775233] sd 0:0:0:0: [sda] Write Protect is off
Oct 23 17:46:58 qtpi kernel: [  704.775252] sd 0:0:0:0: [sda] Mode Sense: 43 00 00 00
Oct 23 17:46:58 qtpi kernel: [  704.775891] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
Oct 23 17:46:58 qtpi kernel: [  704.822380]  sda: sda1
Oct 23 17:46:58 qtpi multipath: sda: can't store path info
Oct 23 17:47:12 qtpi kernel: [  718.781052] sd 0:0:0:0: [sda] Attached SCSI disk
Oct 23 17:47:44 qtpi kernel: [  750.657944] usb 1-1.2: reset high-speed USB device number 4 using dwc_otg
Oct 23 17:47:44 qtpi kernel: [  750.803479] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_TIME_OUT driverbyte=DRIVER_OK
Oct 23 17:47:44 qtpi kernel: [  750.803524] sd 0:0:0:0: [sda] tag#0 CDB: Read(10) 28 00 00 00 00 08 00 00 08 00
Oct 23 17:47:44 qtpi kernel: [  750.803547] blk_update_request: I/O error, dev sda, sector 8 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 0
Oct 23 17:47:58 qtpi systemd-udevd[900]: sda: Worker [1977] processing SEQNUM=5385 is taking a long time
Oct 23 17:48:05 qtpi kernel: [  771.966758] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
Oct 23 17:48:05 qtpi kernel: [  771.966784] sd 0:0:0:0: [sda] tag#0 CDB: Read(10) 28 00 22 ef 66 88 00 00 01 00
Oct 23 17:48:05 qtpi kernel: [  771.966808] blk_update_request: I/O error, dev sda, sector 586114696 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 0
Oct 23 17:48:19 qtpi kernel: [  785.798862] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
Oct 23 17:48:19 qtpi kernel: [  785.798888] sd 0:0:0:0: [sda] tag#0 CDB: Read(10) 28 00 00 00 00 40 00 00 08 00
Oct 23 17:48:19 qtpi kernel: [  785.798913] blk_update_request: I/O error, dev sda, sector 64 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 0
Oct 23 17:48:28 qtpi kernel: [  795.238641] sd 0:0:0:0: [sda] tag#0 FAILED Result: hostbyte=DID_ERROR driverbyte=DRIVER_OK
Oct 23 17:48:28 qtpi kernel: [  795.238667] sd 0:0:0:0: [sda] tag#0 CDB: Read(10) 28 00 00 00 00 80 00 00 08 00
Oct 23 17:48:28 qtpi kernel: [  795.238692] blk_update_request: I/O error, dev sda, sector 128 op 0x0:(READ) flags 0x80700 phys_seg 1 prio class 0
Oct 23 17:48:28 qtpi kernel: [  795.238864] usb 1-1.2: USB disconnect, device number 4
Oct 23 17:48:28 qtpi kernel: [  795.252762] sd 0:0:0:0: [sda] Synchronizing SCSI cache
Oct 23 17:48:28 qtpi kernel: [  795.258161] blk_update_request: I/O error, dev sda, sector 128 op 0x0:(READ) flags 0x0 phys_seg 1 prio class 0
Oct 23 17:48:28 qtpi kernel: [  795.268556] Buffer I/O error on dev sda, logical block 16, async page read
Oct 23 17:48:28 qtpi kernel: [  795.275921] sd 0:0:0:0: [sda] Synchronize Cache(10) failed: Result: hostbyte=DID_NO_CONNECT driverbyte=DRIVER_OK
Oct 23 17:48:28 qtpi multipathd[1497]: uevent trigger error
Oct 23 17:48:29 qtpi multipathd[1497]: sda: path already removed

According to the log, read operations are being done on multiple sectors (8, 64, 128 and 586114696), though I don't understand why these reads are being done in the first place. Sectors 8, 64 and 128 are definitely readable on my mac though, the first bad sector does not appear before around the 350MB mark. Each read error seems to correspond to one click. What could be the cause of this behaviour? How can I fix this?
Comment: How do you connect the drive to the raspberry pi? Is it powered externally? The raspberry pi 3b probably doesn't provide enough power on its USB ports to power an HDD. That periodic sound you hear is typical in cases where the HDD powers off due to voltage breakdown as a result of too much power draw.
Comment: @ExtraGoofy glad I could help!
Comment: @danzel The drive is a Maxtor Diamondmax 10, I'm connecting it using a ATA-to-USB adapter that is externally powered so I'd be surprised if it is a power issue. Also, if the HDD powers down, wouldn't I see disconnects and reconnects in the logs?
Comment: @danzel You had the right intuition. I just tried putting a powered USB hub in between and now it's working like a charm. Appearently, the power supply of the ATA-to-USB-adapter was not strong enough. Problem solved, thank you.
Answer: As it is so often with the RPi, it was a power consumption problem. After I put a powered USB hub in between the ATA-to-USB adapter of the drive (which already has its own power supply, which made me assume I would not need another power adapter) and the rpi, everything works fine.
Thanks to @danzel for having the right intuition.


How do I convert a repeating column into a row?

Question: I have a table that has rows with unique values in one column.  How can I place these in a row so that one entry has multiple entries?
For example here is a table...
create table visit_view
(
  last_name varchar(25),
  first_name varchar(25),
  middle_name varchar(25),
  dob datetime,
  di datetime,
  m varchar(20),
  d varchar(12),
  d_sequence_num smallint
)

insert into visit_view values ('LEE','BUDDY','','05/20/2010','10/01/2012','123456','786.2','2')
insert into visit_view values   ('LEE','BUDDY','','05/20/2010','10/01/2012','123456','784.99','3')
insert into visit_view values ('TU','BIBO','LU','09/29/2012','10/01/2012','321456','774.6','1')
insert into visit_view values ('SMITH','BOBBIE','JOE','09/29/2012','10/01/2012','321654','V50.2','1')
insert into visit_view values ('LEWIS','CAREY','','11/11/2011','10/01/2012','654123','057.9','2')
insert into visit_view values ('LEWIS','CAREY','','11/11/2011','10/01/2012','654123','074.3','3')
insert into visit_view values ('RAMIREZ','HECTOR','','04/21/2011','10/02/2012','654321','381.81','2')
insert into visit_view values ('RAMIREZ','HECTOR','','04/21/2011','10/02/2012','654321','786.09','3')
insert into visit_view values ('RAMIREZ','HECTOR','','04/21/2011','10/02/2012','654321','380.4','4')
insert into visit_view values ('RAMIREZ','HECTOR','','04/21/2011','10/02/2012','654321','478.19','5')

And my query looks like this...
SELECT
    first_name AS FirstName,
    ISNULL(middle_name, '') AS MI,
    last_name AS LastName,
    CONVERT(varchar,dob, 101) DOB,
    CONVERT(varchar,di,101) DCdate,
    CAST(m AS INT) AS MR,
    d AS Diag
FROM
    visit_view
WHERE
    d_sequence_num>1
    AND DATEDIFF(year,dob,GETDATE()) <= 3
ORDER BY di,d_sequence_num ASC

I my output is
FIRSTNAME MI LASTNAME DOB DCDATE MR DIAG
CAREY  LEWIS 11/11/2011 10/01/2012 654123 057.9
BUDDY  LEE 05/20/2010 10/01/2012 123456 786.2
BUDDY  LEE 05/20/2010 10/01/2012 123456 784.99
CAREY  LEWIS 11/11/2011 10/01/2012 654123 074.3
HECTOR  RAMIREZ 04/21/2011 10/02/2012 654321 381.81
HECTOR  RAMIREZ 04/21/2011 10/02/2012 654321 786.09
HECTOR  RAMIREZ 04/21/2011 10/02/2012 654321 380.4
HECTOR  RAMIREZ 04/21/2011 10/02/2012 654321 478.19

But I want it like this...
FIRSTNAME MI LASTNAME DOB DCDATE MR DIAG
CAREY  LEWIS 11/11/2011 10/01/2012 654123 057.9
BUDDY  LEE 05/20/2010 10/01/2012 123456 786.2 784.99
CAREY  LEWIS 11/11/2011 10/01/2012 654123 074.3
HECTOR  RAMIREZ 04/21/2011 10/02/2012 654321 381.81 786.09 380.4 478.19

Comment: try: http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-microsoft-sql-server-2005
Comment: And here for SQL Server solution: http://stackoverflow.com/questions/2046037/sql-server-can-i-comma-delimit-multiple-rows-into-one-column
Answer: I am not sure why you have CAREY LEWIS showing twice in your result and HECTOR RAMIREZ once, but you can consolidate the rows using something like this:
SELECT
    first_name AS FirstName,
    ISNULL(middle_name, '') AS MI,
    last_name AS LastName,
    CONVERT(varchar,dob, 101) DOB,
    CONVERT(varchar,di,101) DCdate,
    CAST(m AS INT) AS MR,
    stuff((select distinct ', '+ d
           from visit_view v1
           where v.first_name = v1.first_name
           FOR XML PATH('')),1,1,'') Diag
FROM visit_view v
WHERE d_sequence_num>1
    AND DATEDIFF(year,dob,GETDATE()) <= 3
GROUP BY first_name, middle_name, last_name, dob, di, m
ORDER BY di ASC

See SQL Fiddle with Demo
Gives the result:
| FIRSTNAME | MI | LASTNAME |        DOB |     DCDATE |     MR |                           DIAG |
-------------------------------------------------------------------------------------------------
|     BUDDY |    |      LEE | 05/20/2010 | 10/01/2012 | 123456 |                  784.99, 786.2 |
|     CAREY |    |    LEWIS | 11/11/2011 | 10/01/2012 | 654123 |                   057.9, 074.3 |
|    HECTOR |    |  RAMIREZ | 04/21/2011 | 10/02/2012 | 654321 |  380.4, 381.81, 478.19, 786.09 |

Comment: Putting Carey twice was my mistake, this was exactly what I was looking for!!
Comment: +1 for the SQL Fiddle - I didn't know that existed - it's been added to my bookmarks bar
Comment: @dwtorres happy to help, be sure to accept one of the answers to your questions if they are helpful. You can accept by clicking the checkmark to the left of the answer
Answer: I would suggest looking into CROSS APPLY and FOR XML:
SELECT  DISTINCT
    first_name AS FirstName,
    ISNULL(middle_name, '') AS MI,
    last_name AS LastName,
    CONVERT(varchar,dob, 101) DOB,
    CONVERT(varchar,di,101) DCdate,
    CAST(m AS INT) AS MR,
     STUFF(D2.d, 1, 1, '')  AS Diag
FROM
    visit_view v
CROSS APPLY ( SELECT ',' + d
              FROM visit_view v2
              WHERE v.last_name = v2.last_name
              ORDER BY d_sequence_num
                  FOR XML PATH('') )  D2 ( d )
WHERE
    d_sequence_num>1
    AND DATEDIFF(year,dob,GETDATE()) <= 3

Wasn't sure why you didn't have an ID in your visit_view table or would have used that in my cross apply where criteria, but this should get you going in the right direction.
Here is the SQL Fiddle.
Good luck.


Print specific line (Beautifulsoup)

Question: Currently, my code is parsing through the link and printing all of the information from the website. I only want to print a single specific line from the website. How can I go about doing that?
Here's my code:
from bs4 import BeautifulSoup
import urllib.request

r = urllib.request.urlopen("Link goes here").read()
soup = BeautifulSoup(r, "html.parser")

# This is what I want to change. I currently have it printing everything.
# I just want a specific line from the website

print (soup.prettify())

Comment: What line do you want? There are much better and accurate ways than using prettify, splitting the lines and indexing is going to break with the smallest change to the html
Comment: I want a line that says this each time:
E9-WAREHOUSE

the "E9-WAREHOUSE" may be different each time
Comment: What other tags are around it? can you share the link or the html?
Answer: li = soup.prettify().split('\n')
print str(li[line_number-1])

Comment: THANK YOU! Worked beautifully!
Answer: Don't use pretty print to try and parse tds, select the tag specifically, if the attribute is unique then use that, if the class name is unique then just use that:
td = soup.select_one("td.content")
td = soup.select_one("td[colspan=3]")

If it was the fourth td:
td = soup.select_one("td:nth-of-type(4)")

If it is in a specific table, then select the table and then find the td in the table, trying to split the html into lines and indexing is actually  worse than using a regex to parse html.
You can get the specific td using the text from the bold tag preceding the td i.e Department of Finance Building Classification::
In [19]: from bs4 import BeautifulSoup

In [20]: import urllib.request

In [21]: url = "http://a810-bisweb.nyc.gov/bisweb/PropertyProfileOverviewServlet?boro=1&houseno=1&street=park+ave&go2=+GO+&requestid=0"

In [22]: r = urllib.request.urlopen(url).read()

In [23]: soup = BeautifulSoup(r, "html.parser")

In [24]: print(soup.find("b",text="Department of Finance Building Classification:").find_next("td").text)
O6-OFFICE BUILDINGS

Pick the nth table and row:
In [25]: print(soup.select_one("table:nth-of-type(8) tr:nth-of-type(5) td[colspan=3]").text)
O6-OFFICE BUILDINGS

Comment: then would i use use print(td) after that? cause I called that and it's printing out "none". here's my current code: http://puu.sh/puY3G/bf07dffd63.png
Comment: Posted wrong snippet, can you add the actual link or html and it iwll be a lot easier show you how to parse html properly.
Comment: Here's the link: http://a810-bisweb.nyc.gov/bisweb/PropertyProfileOverviewServlet?boro=1&houseno=1&street=park+ave&go2=+GO+&requestid=0
Comment: In that case I would want to print "O6-OFFICE BUILDINGS"
Comment: I was messing around and put  td = soup.select_one("td:nth-of-type(135)"), then call print(td.get_text()), which works, but only like 40% of the time. I'm just baffled.
Comment: I will be back on my notebook soon and I will show you how to get it
Comment: Are you always looking for `Department of Finance Building Classification:`?
Comment: No, i'm just looking for the "06 - Office Buildings"

Print specific line (Beautifulsoup)


How do I change a bulb in this flush mounted light fixture?

Question: I need to replace the bulb in this flush mounted ceiling light with a glass dome but cannot open it. There are two handles (springs?) that I assume should be used to achieve that but I could not figure the system out. I tried pushing on them upwards or pulling to the side but no luck. I have tried rotating the glass dome but that does not loosen it.
Any ideas?
Comment: Hello, and welcome to Stack Exchange. Do those handles move at all? Have you tried just a moderate pull straight down on the glass?
Comment: Looking at the 2nd photo it looks like the handle may be able to be pushed in. That may just be paint that has scraped off but you have tried the normal things.
Comment: @EdBeal your idea with the handle did not work but was a very good hit in the right direction... Instead of pushing in, I pulled them out which released the glass dome.
Answer: The solution was inspired by Ed Beal's idea.
Pulling both handles out released the glass dome. Each handle can be pulled out separately to help keep the dome from falling.
Comment: I figured you had tried out glad you got it.


How to write and read to/from a QResource file in Qt 5?

Question: It's strange, I add desired file into the resources via Add Existing Files..., the file is there. I run qmake ("Build->Run qmake") to make the file available.
The first issue: I can't write anything into the file from output terminal! But when I manually write into the file, the output terminal shows the change every time I run it. Second issue: it still says QIODevice::read: device not open !
Here's my code:
<code>#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QString>
#include <QTextStream>
#include <iostream>

void wFile(QString Filename)
{
  QFile  nFile(Filename);
  QTextStream str(&nFile);
  qDebug() << "what do you want to write in the desired file: ";
  str.readLine();
  if (!nFile.open(QFile::WriteOnly  | QFile::Text))
  {
    qDebug() << "could not open the file";
    return;
  }
  nFile.flush();
  nFile.close();
 }

void read (QString Filename){
  QFile nFile(Filename);

  if(!nFile.open(QFile::ReadOnly | QFile::Text))
  {
    qDebug() << "could not open file for reading";
    return;
  }
  QTextStream in(&nFile);
  QString nText = in.readAll();

  qDebug() << nText;
  nFile.close();
 }

int main(int argc, char *argv[])
{
 QCoreApplication a(argc, argv);
 QString nFilename =":/MyFiles/DocumentArminV.txt";

 wFile(nFilename);
 read(nFilename);

 return a.exec();
}
</code>
And here's output terminal of the code:
Comment: the items saved in qresource are **read-only**.
Comment: @eyllanesc: Even if it is short, this comment should be an answer. Because, as you stated, ressource files cannot be written (as they are compiled into the executable).
Answer: The files saved in a qresource are read-only since they are part of the executable so you can not write or modify them.
docs:

Currently, Qt always stores the data directly in the executable, even on Windows, macOS, and iOS, where the operating system provides native support for resources. ...
Comment: Dear @eyllanesc Thanks a lot for your answer :) I mark the question as answered with your great answer. Though, I don't want to have two issues in one question, but if you would find out that the  answer this question is also just straight forward, just give me a hint please. Actually my main purpose is how to write a code to prompt user and write the desired text typed by that user into a specific file and then read it and show it in output terminal. I searched it but I haven't exactly found it yet. :(
Comment: @Armin change `":/MyFiles/DocumentArminV.txt"` to `"DocumentArminV.txt"`


Are Linq's Skip and Take optimized for arrays? [4.0 edition]

Question: It's a common situation to copy a range from an array. C# supports this operation in various ways, for instance using Array.Copy, but also by Linq's Skip and Take combination.
Starting at .NET 4.0, do the Skip and Take operations still add considerable overhead, or do they recognize (either at compile time or at run time) their target is an array?
To clarify: I am referring to a) the time taken to skip the initial bytes and b) to the combination of Skip-Take-ToArray, which does not suffer from side effects. For instance, new byte[10000].Skip(9999).Take(1).ToArray() could be optimized this way and would (for large n) be noticeably faster.
Comment: They can't work in O(1) for arrays. How do you expect a lazily evaluated sequence to ever be O(1)? Just imagine if I did a `.Skip(1)` on a 10,000,000 element array - are you expecting a 9,999,999 element memory copy? That would be very inefficient if I then immediately did a `.Take(1)`.
Comment: @Enigmativity: There's the size of the array... and then there's the argument passed to `Skip`.  Anyway, neither `Skip` nor `Take` copy the source collection.
Comment: I have reworded the question to remove the misleading statement of O(1).
Answer: Skip/Take still operate in O(n) due to how LINQ has to maintain knowledge of how elements even in arrays can be changed and how the objects have to stay aware of the changes.Therefore, while the optimizations to O(1) seems trivial, it is not currently realized.
See: https://edulinq.googlecode.com/hg/posts/40-Optimization.html
Jon Skeet had an excellent blog a few years back discussing these and more in "reimplementing LINQ" (http://codeblog.jonskeet.uk/2011/01/02/reimplementing-linq-to-objects-part-23-take-skip-takewhile-skipwhile/). It's a great read.
Answer: Since they are not optimized in 4.5 I can confidently say that they are not optimized in 4.0 either
http://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs#83ec6a20321060a1#references
BTW there is no way Take is O(1) even on arrays since it has an output of N (assuming it is iterated of course)
Answer: The optimisation that would be nice is if on Skip(k) the first .MoveNext just sets the internal index to k, and I thought the JITter could do this, but it seems not to, for the versions I've tried.
The code to be optimised is:
while (count > 0 && e.MoveNext()) count--;

from SkipIterator and:
      public bool MoveNext() {
            if (_index < _endIndex) {
                _index++;
                return (_index < _endIndex);
            }
            return false;
        }

from SZGenericArrayEnumerator.
(The reference source is 4.5.1, but reflector shows very similar code in 4.0.)
Comment: Just an update: A number of answers to similar questions eventually link to the same Jon Skeet blog post as Jason W. or [this one](http://stackoverflow.com/a/7288572/256431), but more directly suggest loops cannot (or will not) be removed by optimisation; and, since .NET 4.5, `ArraySegment` becomes an option when you know you're dealing with an array.
Comment: That's the question! *Does* the JITter do it? ;)
Comment: @mafu Short answer, no: [My LinqPad Test](http://share.linqpad.net/fhb96l.linq). It is possible that some JIT optimisations are still off but this is with the LinqPad /o+ option on. (You'll need my [`.Time` My Extension](http://share.linqpad.net/jkuqrc.linq) to replicate the test.)


Number of moves required to empty all the boxes as per the given rules

Question: I have the following question with me:
"There are 1990 boxes containing 1,2,3,....,1990 chips respectively, on a table. You may choose any subset of boxes and subtract the same number of chips from each box. What is the minimum number of moves you need to empty all boxes?"
How do I proceed with the question?
Comment: I have a question on the rules.  Suppose I pick $4$ as the first number.  What action do I take on the first $3$ boxes?
Comment: Interesting question. Let's generalize this to $n$ boxes. Do I understand correctly that we can do $n=3$ in $2$ moves? $[1,2,3];[0,2,2];[0,0,0]$
Comment: I believe you can do $n=1990$ in $11$ moves. Hint: look at the binary representations of the numbers. I am not sure whether this is optimal though.
Comment: Ok I am sure that this is optimal. If you want me to explain, just ask and I'll write a complete answer.
Comment: @saulspatz it is not possible to take 4 chips from a box with fewer than 4 chips.
Comment: @MJD I understand that; that's why I'm asking.
Answer: Since 1990 is a rather arbitrary number, let's generalize the problem for a little bit.

"There are $m$ boxes containing 1, 2, 3, ...., $m$ chips respectively, on a table. You may choose any subset of boxes and subtract the same number of chips from each box. What is the minimum number of moves you need to empty all boxes?"

A quick observation yields that:
(1) If $p<q$, and the problem of $q$ boxes can be cleared within $n$ moves, then the problem of $p$ box can also be cleared within $n$ moves.
(2) If $p<q$, and the problem of $p$ boxes cannot be cleared within $n$ moves, then the problem of $q$ box cannot be cleared within $n$ moves.
(3) The number of boxes that contains the same amount of chips do not affect the result.
Justification of (1): We can deal with the $p$ boxes exactly the same way as we deal with the $q$ boxes, except for the moves that is intended for the boxes including more than $p$ chips are ignored. (3) follows from that whatever moves we made for the scenario without the copies, we can extend the original subsets so as to treat the duplicates as well.
Justification of (2): Proof by contradiction. If $q$ boxes problem can be cleared in $n$ moves, then from (1) we know that there is also a solution for $p$ boxes, since $p<q$, which is not possible.
First let's prove that if $m=2^n-1$, then $n$ moves is sufficient. Firstly, subtract $2^{n-1}$ chips from the boxes that has at least $2^{n-1}$ chips, then from (3) we learn that this is equal to a $2^{n-1} - 1$ boxes problem, because the boxes now contain 1, 2, ..., $2^{n-1}-1$, 0, 1, 2, $2^{n-1}-1$ chips. Besides, $2^1-1=1$ box problem can be solved with $1$ move. By induction we completed the proof.
Then we will show that if $m=2^n$, then $n$ moves is not enough.    I would prefer to use sets to interpret this problem, since (3) tells us that duplicates have no effect on the result. Rephrase the problem in this way:
$\def\card{\mathrm{card}}$

$S_0\subset\mathbb N$ is a set of positive integers from 0 to $m$. You may choose any partition $S_0=P_1\cup Q_1$, and a non-negative number $t_1\leq\min P_1$. Define $S_1=\{x-t_1| x\in P_1\}\cup Q_1$. $S_2, S_3, \ldots$ are also defined in this way. Find $\{P_i\}$ and $\{t_i\}$ to minimize $n$, where $S_n= \{0\}$.

We want to prove that if $\card S_k=s$, then $\card S_{k+1}\geq s/2$. Actually, if $\card S_{k+1}<s/2$, then $\card P_{k+1}\leq \card S_{k+1}<s/2$ and $\card Q_{k+1}\leq \card S_{k+1}<s/2$. But $P_{k+1}$ and $Q_{k+1}$ are actually partition of $S_k$, the sum of cardinals should be $s$. This leads to a contradiction.
When $m=2^n$, $\card S_0 = 2^n+1$. After one move, we have $\card S_1 \leq 2^{n-1} + 1/2$. But $\card S_1$ is an integer, so $\card S_1 \leq 2^{n-1} +1$. Using induction, we know that $\card S_n \geq 2 >1$, so it cannot be $\{0\}$.
In this case, $1024\leq1990\leq2047$. From (1) and (2) we know that 11 is the minimal amount of moves required.
Comment: Are your observations 1 and 2 correct? I feel you interchanged p and q there.....
Comment: @saisanjeev I rearranged the answer for a little bit, hopefully this is helpful for understanding.
Comment: Can you please elaborate the part after you have rephrased the required problem into that of a set theory problem. I have some trouble with the subscripts 'k+1' and 'k' coz I am unable to relate them directly as you have
Comment: @saisanjeev Ok. $\{S_k\}$ is a sequence of sets of non-negative integers. I added zero in them just for convenience. $S_0$ is what you have originally got, i.e. boxes 1, ..., m chips, and an additional empty one. After each move, we generate another set from $\{S_k\}$. So after move 1 we got $S_1$, and after move 2 we got $S_2$, etc. The numbers in $a_1, \ldots, a_u$ in $S_k$ indicates that after $k$ moves, you have some boxes with $a_1$ chips, some boxes with $a_2$ chips, ..., ... with $a_p$ chips. You choose some boxes to subtract t chips, whose amount of chips is $P$. Is this clear?
Comment: $P_k$ and $Q_k$ may not be disjoint, but this does not influence the result.
Comment: "If $q<p$, and the problem of $q$ boxes *can* be cleared within $n$ moves, then the problem of $p$ box *can* also be cleared within $n$ moves." Let $n=q=1,$ $p=2,$ then $q<p$ and the problem of $q$ boxes can be cleared within $n$ moves, and your statement says $p=2$ boxes also can be cleared in $n=1$ move. I think you have the right idea in mind but you mixed up your $p$s and $q$s in the statement.
Answer: As SmileyCraft said in the comments, it can be done in $11$ moves.
The procedure is, at every step, to remove half the current chip maximum from all boxes containing more than this maximum. I.e. if the current chip maximum is $n_i$, the number of chips to remove is $n_{i+1} = \lceil \frac{n_{i}}{2} \rceil$.
With $n_0=1990$, the number of chips to remove in step $i=1$ is $n_1 = \lceil \frac{n_0}{2} \rceil = 995$. This leaves $2$ sets of boxes with $1$ to $995$ chips. With $n_1=995$, the number of chips to remove in step $i=2$ is $n_2 = \lceil \frac{n_1}{2} \rceil = 498$. This leaves $4$ sets of boxes with $1$ to $497$ chips. With $n_2=497$, the number of chips to remove in step $i=3$ is $n_3 = \lceil \frac{n_2}{2} \rceil = 249$. This leaves $8$ sets of boxes with $1$ to $248$ chips. And so on.
Comment: Can you prove that it cannot be done with less than 11 moves?
Comment: See if this may work out: To clear 1...$2^n$, we know that it requires n moves. However, if there is 1...$2^n+1$ instead, whatever first move are made, there are at least $2^{n-1}+1$ boxes that contains different amount of chips (plus, they are not empty). Use induction and we may conclude that after n moves, at least 1 box is not empty. For $m>2^{n}+1$, we know that the first $2^n+1$ boxes that cannot be dealt with n moves. This completes the proof.
Comment: No, I cannot. Can you?
Comment: I am thinking of it, but I don't have any idea by now.
Comment: @fantasie Hmmm. Not sure. If you can do the proof in detail, you should add it as an answer.
Comment: Actually there is a tricky little issue in the numbers, but I corrected it in my answer, as you suggested.
Answer: A simpler strategy is to remove the largest power of $2$ that is in any box from all the boxes you can.  Now there is an easy inductive proof that you can handle boxes up to $2^n-1$ in $n$ moves because each move clears the high order bit.
To prove this is a minimal number of moves, show that the set up to $2^n-1$ must require $n$ moves because any smaller set of removals cannot clear it.  Then any first move that gets all the boxes below $2^n-1$ is acceptable.
Comment: Not exactly, even if we know 2047 boxes can be dealt with 11 moves and 1023 boxes requires at least 10 moves, there is no information about numbers in the middle.
Answer: The answers so far don't address your question, which is to show the minimum number of moves required to empty the boxes.  I will give you a hint:

Suppose the chips are arranged in the boxes in such a way that all the boxes can be emptied in one move.  What can you say about the numbers of chips in the boxes?
Now suppose the chips in the boxes are such that the boxes can be emptied in two moves.  What must be true about the distribution of the chips?


OpenSSL - Failed to create p12 from private key on bad decrypt

Question: I installed OpenSSL 1.1.1 on windows https://kb.firedaemon.com/support/solutions/articles/4000121705#Download-OpenSSL
I got crt file and I have PrivKey.pem created and I try to generate p12
openssl pkcs12 -export -in Cert.crt -inkey PrivKey.pem -out KeyStore.p12

Output:
unable to load private key
18328:error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt:..\crypto\evp\evp_enc.c:615:
18328:error:0906A065:PEM routines:PEM_do_header:bad decrypt:..\crypto\pem\pem_lib.c:461:

I notice that when I create private key I don't get password prompt
openssl genrsa -aes256 -out PrivKey.pem 2048

Output:
Generating RSA private key, 2048 bit long modulus (2 primes)

Most related answers I found related to wrong configuration/file, but it seems as a different case
Should I reset my settings and renew process?
Answer: I download and install OpenSSL 1.1.1 for Linux and it works without any issue