gradle-android-scala-plugin gives "Could not find matching constructor" error

Question: Importing this example code into Android Studio gives this error:

Error:(17, 0) Could not find matching constructor for:
  org.gradle.api.internal.tasks.DefaultScalaSourceSet(java.lang.String,
  org.gradle.api.internal.file.BaseDirFileResolver)

build.gradle:
buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "com.android.tools.build:gradle:2.0.0"
        classpath "jp.leafytree.gradle:gradle-android-scala-plugin:1.4"
    }
}

repositories {
    jcenter()
}
apply plugin: "com.android.application"
android{
    compileSdkVersion "android-23"
    buildToolsVersion "23.0.1"
}

apply plugin: "jp.leafytree.android-scala"

android {

    defaultConfig {
        targetSdkVersion 23
        testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
    }

    productFlavors {
        dev {
            minSdkVersion 21 // To reduce compilation time
        }

        prod {
            minSdkVersion 8
        }
    }

    dexOptions {
        preDexLibraries false
        javaMaxHeapSize "2g"
    }

    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
    }
}

dependencies {
    compile "org.scala-lang:scala-library:2.11.7"
    compile "com.android.support:multidex:1.0.1"
    androidTestCompile "com.android.support:multidex-instrumentation:1.0.1", { exclude module: "multidex" }

    // to break 64k limit
    compile "org.scalaz:scalaz-core_2.11:7.1.0"
    compile "com.google.guava:guava-jdk5:17.0"
    compile "org.apache.commons:commons-math3:3.3"
}

Details:
bash-3.2$ ./gradlew --info
Starting Build
Evaluating root project 'buildSrc' using build file '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/build.gradle'.
Selected primary task 'build' from project :
:compileJava (Thread[main,5,main]) started.
:buildSrc:compileJava
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/src/main/java', not found
Skipping task ':compileJava' as it has no source files.
:buildSrc:compileJava UP-TO-DATE
:compileJava (Thread[main,5,main]) completed. Took 0.022 secs.
:compileGroovy (Thread[main,5,main]) started.
:buildSrc:compileGroovy
Executing task ':compileGroovy' (up-to-date check took 0.09 secs) due to:
  Input file /Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/plugins/maven-model-3.0.4.jar has been added.
  Input file /Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/plugins/servlet-api-2.5-20081211.jar has been added.
  Input file /Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/plugins/jsp-2.1-6.1.14.jar has been added.
Starting process 'Gradle Compiler Daemon 1'. Working directory: /Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc Command: /Library/Java/JavaVirtualMachines/jdk1.8.0_91.jdk/Contents/Home/bin/java -Djava.security.manager=jarjar.org.gradle.process.internal.child.BootstrapSecurityManager -Dfile.encoding=UTF-8 -Duser.country=US -Duser.language=en -Duser.variant -cp /Users/joco/.gradle/caches/2.12/workerMain/gradle-worker.jar jarjar.org.gradle.process.internal.launcher.GradleWorkerMain 'Gradle Compiler Daemon 1'
Successfully started process 'Gradle Compiler Daemon 1'
Started Gradle compiler daemon (0.516 secs) with fork options DaemonForkOptions{minHeapSize=null, maxHeapSize=null, jvmArgs=[], classpath=[/Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/groovy-all-2.4.4.jar, /Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/ant-1.9.3.jar, /Users/joco/.gradle/wrapper/dists/gradle-2.12-all/4ng70i0k4ou37vg5et2lk2qc7s/gradle-2.12/lib/ant-launcher-1.9.3.jar]}.
Executing org.gradle.api.internal.tasks.compile.ApiGroovyCompiler@58db718 in compiler daemon.
Successfully executed org.gradle.api.internal.tasks.compile.ApiGroovyCompiler@58db718 in compiler daemon.
:compileGroovy (Thread[main,5,main]) completed. Took 1.666 secs.
:processResources (Thread[main,5,main]) started.
:buildSrc:processResources
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/src/main/resources', not found
Skipping task ':processResources' as it has no source files.
:buildSrc:processResources UP-TO-DATE
:processResources (Thread[main,5,main]) completed. Took 0.002 secs.
:classes (Thread[main,5,main]) started.
:buildSrc:classes
Skipping task ':classes' as it has no actions.
:classes (Thread[main,5,main]) completed. Took 0.001 secs.
:jar (Thread[main,5,main]) started.
:buildSrc:jar
Skipping task ':jar' as it is up-to-date (took 0.021 secs).
:buildSrc:jar UP-TO-DATE
:jar (Thread[main,5,main]) completed. Took 0.035 secs.
:assemble (Thread[main,5,main]) started.
:buildSrc:assemble
Skipping task ':assemble' as it has no actions.
:buildSrc:assemble UP-TO-DATE
:assemble (Thread[main,5,main]) completed. Took 0.002 secs.
:compileTestJava (Thread[main,5,main]) started.
:buildSrc:compileTestJava
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/src/test/java', not found
Skipping task ':compileTestJava' as it has no source files.
:buildSrc:compileTestJava UP-TO-DATE
:compileTestJava (Thread[main,5,main]) completed. Took 0.002 secs.
:compileTestGroovy (Thread[main,5,main]) started.
:buildSrc:compileTestGroovy
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/src/test/groovy', not found
Skipping task ':compileTestGroovy' as it has no source files.
:buildSrc:compileTestGroovy UP-TO-DATE
:compileTestGroovy (Thread[main,5,main]) completed. Took 0.002 secs.
:processTestResources (Thread[main,5,main]) started.
:buildSrc:processTestResources
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/src/test/resources', not found
Skipping task ':processTestResources' as it has no source files.
:buildSrc:processTestResources UP-TO-DATE
:processTestResources (Thread[main,5,main]) completed. Took 0.002 secs.
:testClasses (Thread[main,5,main]) started.
:buildSrc:testClasses
Skipping task ':testClasses' as it has no actions.
:buildSrc:testClasses UP-TO-DATE
:testClasses (Thread[main,5,main]) completed. Took 0.001 secs.
:test (Thread[main,5,main]) started.
:buildSrc:test
file or directory '/Users/joco/dev/android/scala/gradle-android-scala-plugin/buildSrc/build/classes/test', not found
Skipping task ':test' as it has no source files.
:buildSrc:test UP-TO-DATE
:test (Thread[main,5,main]) completed. Took 0.001 secs.
:check (Thread[main,5,main]) started.
:buildSrc:check
Skipping task ':check' as it has no actions.
:buildSrc:check UP-TO-DATE
:check (Thread[main,5,main]) completed. Took 0.001 secs.
:build (Thread[main,5,main]) started.
:buildSrc:build
Skipping task ':build' as it has no actions.
:buildSrc:build UP-TO-DATE
:build (Thread[main,5,main]) completed. Took 0.001 secs.
Stopped 1 compiler daemon(s).
Settings evaluated using empty settings script.
Projects loaded. Root project using build file '/Users/joco/dev/android/scala/gradle-android-scala-plugin/sample/hello/build.gradle'.
Included projects: [root project 'hello']
Evaluating root project 'hello' using build file '/Users/joco/dev/android/scala/gradle-android-scala-plugin/sample/hello/build.gradle'.
Creating configuration compile
Creating configuration apk
Creating configuration provided
Creating configuration wearApp
Creating configuration androidTestCompile
Creating configuration androidTestApk
Creating configuration androidTestProvided
Creating configuration androidTestWearApp
Creating configuration testCompile
Creating configuration testApk
Creating configuration testProvided
Creating configuration testWearApp
Creating configuration debugCompile
Creating configuration debugApk
Creating configuration debugProvided
Creating configuration debugWearApp
Creating configuration testDebugCompile
Creating configuration testDebugApk
Creating configuration testDebugProvided
Creating configuration testDebugWearApp
Creating configuration releaseCompile
Creating configuration releaseApk
Creating configuration releaseProvided
Creating configuration releaseWearApp
Creating configuration testReleaseCompile
Creating configuration testReleaseApk
Creating configuration testReleaseProvided
Creating configuration testReleaseWearApp
Parsing the SDK, no caching allowed
Parsing /Users/joco/Library/Android/sdk/build-tools/20.0.0/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/21.0.0/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/21.1.2/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/23.0.1/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/23.0.3/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/24.0.0/package.xml
Parsing /Users/joco/Library/Android/sdk/build-tools/24.0.1/package.xml
Parsing /Users/joco/Library/Android/sdk/extras/android/m2repository/package.xml
Parsing /Users/joco/Library/Android/sdk/extras/google/m2repository/package.xml
Parsing /Users/joco/Library/Android/sdk/platform-tools/package.xml
Parsing /Users/joco/Library/Android/sdk/platforms/android-20/package.xml
Parsing /Users/joco/Library/Android/sdk/platforms/android-21/package.xml
Parsing /Users/joco/Library/Android/sdk/platforms/android-23/package.xml
Parsing /Users/joco/Library/Android/sdk/platforms/android-24/package.xml
Parsing /Users/joco/Library/Android/sdk/sources/android-21/package.xml
Parsing /Users/joco/Library/Android/sdk/system-images/android-21/google_apis/x86_64/package.xml
Parsing /Users/joco/Library/Android/sdk/system-images/android-23/google_apis/x86_64/package.xml
Parsing /Users/joco/Library/Android/sdk/system-images/android-24/default/x86_64/package.xml
Parsing /Users/joco/Library/Android/sdk/tools/package.xml

FAILURE: Build failed with an exception.

* Where:
Build file '/Users/joco/dev/android/scala/gradle-android-scala-plugin/sample/hello/build.gradle' line: 21

* What went wrong:
A problem occurred evaluating root project 'hello'.
> Failed to apply plugin [id 'jp.leafytree.android-scala']
   > Could not find matching constructor for: org.gradle.api.internal.tasks.DefaultScalaSourceSet(java.lang.String, org.gradle.api.internal.file.BaseDirFileResolver)

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 6.334 secs
Stopped 0 compiler daemon(s).

Any idea how to fix this ?
Comment: You cannot use newest android studio with the scala gradle plugin
Comment: did you change the virsion of scala-library lib to 2.12.0-M5????
Comment: not that I know of , should I ?
Comment: use update lib and try again...
Comment: thanks, I just checked, I have 2.11.7 scala
Comment: you mean this ? http://lpaste.net/174608 @ExceptionLover
Comment: I get same error: http://lpaste.net/174610
Answer: I just uploaded a new version to JitPack.
It supports Android Gradle Plugin 2.3.0 and Gradle 3.3.
In your project build.gradle:
buildscript {
    repositories {
        jcenter()
        maven { url 'https://jitpack.io' }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        classpath 'com.github.xingda920813:gradle-android-scala-plugin:android-gradle-2.3.0'
    }
}


Python ModuleNotFoundError: No module named 'google.analytics'

Question: I'm trying to use the new Google Data Analytics (https://developers.google.com/analytics/devguides/reporting/data/v1). On my local machine I've got this up and running. However on our Python machine I keep getting the folling error.

In  from google.analytics.data import AlphaAnalyticsDataClient
ModuleNotFoundError: No module named 'google.analytics'

Based on the documentation I had to install google-analytics-data package by using pip. However the problem has nog been solved after installing this package.
Does anyone experience this aswell?
Answer: I've found out why this error occurs. I've installed the correct package, but is has been installed into the wrong directory.
Use the following command to install it on the correct directory:
<code>pip install google-analytics-data -t "C:\<python path>\Lib\site-packages"
</code>
Read more on this on the following page:
windows pip installing libraries in wrong directory
Comment: @DaImTo Yes I followed the instructions. However I didn't want to setup a virtual environment. So I've installed the google-analytics-data package on the regular Python installation. But somehow the installation of the package ended up on a total different location then expected.

On a other sidenote I've missed the documentation of authentication by using the service account json file. By just trying out the following solved my problem
AlphaAnalyticsDataClient.from_service_account_json(credientials.json'). The documentation was not really sufficiënt.
Comment: at the top of the page in the blue there is a link to a form "To report an issue with the API, use the "  submit your comments when you have a minute, im sure the team would appreciate it.
Comment: Did you follow [this](https://developers.google.com/analytics/devguides/reporting/data/v1#python)? If so and there is an issue with that please submit feedback on the page. The team is in the process of flushing out these documentations they could use some tips where information is lacking.


Prove that there exists irrational numbers $x$ and $y$ such that $x + y$ is rational, without using subtraction

Question: My homework has this problem:

Prove that there exist irrational numbers $x$ and $y$ such that $x +
 y$ is rational.

There is an easy solution that I found on mathbitsnotebook.com:

\begin{align} \left(2+6\sqrt{7}\right) + \left(-6\sqrt{7}\right) = 2.\end{align}

Can we prove the same without using subtraction?
Answer: To give one answer, let $\varphi=\frac{\sqrt{5}+1}2$. Notice that both $\frac{1}{\varphi^2}$ and $\frac{1}{\varphi}$ are irrational, but their sum is $1$. That is
$$\frac{1}{\varphi^2}+\frac{1}{\varphi}=1.$$
This stems immediately from the fact that $\varphi$ satisfies (and very often stems from) the equation:
$$1+\varphi=\varphi^2$$
and if we divide through by $\varphi^2$, we get the first equation.
Strictly speaking, however, for any irrational $x$ and $y$ such that $x+y$ is rational, there exists a rational $a_1,a_2$ and irrational $b$ such that $x=a_1+b$ and $y=a_2-b$ meaning that we could write, for rational $p$:
$$x+y=p$$
$$(a_1+b)+(a_2-b)=p$$
where the irrational terms obviously cancel. So, in some sense, we can't avoid subtraction here - no matter what example we choose, we can always express it in a way that makes the cancellation obvious.
(Though this is probably not helpful to the original poster, for others, it's worth noting that the last paragraph in a sense expresses that $\mathbb R$ is a vector space over $\mathbb Q$ - we can consider any irrational $x$ as being on a plane, including sums of the form $px+q$ for rational $p,q$. If we take the quotient space $\mathbb R/\mathbb Q$, we are left with a notion of the "irrational" component of $x$ - and we must undo it to get back to the rationals)
Comment: Thanks for your fast answer. I will study it.
Comment: Great solution! Quick and simple. +1
Comment: But $\dfrac1\phi=\phi^{\color{red}-1}~$ ;-$)$
Comment: @Lucian Don't worry, we can write it as $\varphi^{i\cdot i}$ to avoid that issue! :)
Comment: @Lucian What would be the problem with ϕ^(−1)? Thanks!


how to detect message that has my bot username discord.js

Question: I'm trying to make my bot react on the message which has its username
If I enter my bot username like this, it works:
if(message.content.includes('bot123')) console.log('TRUE') //TRUE

But this one doesn't:
if(message.content.includes(client.user.username)) console.log('TRUE') //doesn't work

I wonder why and if there is a way to make client.user.username works
Comment: Please add some more information, for example: how does your message looks (its content)?
Comment: Can you log `client.user.username` ? Like `console.log(client.user.username)`
Comment: @itzJOH_ I want my bot react on messages which have the bot username or mention it, like "baka bot123", "@bot123" or "bot12345".....
Comment: @Akio I can, it still prints "bot123" on the console but return nothing on message has the bot username
Answer: In the messageCreate event the only parameter is message, thus if you are using a lets say command handler it would be
if(message.content.includes(message.client.user.username)) // ...


Focused window is not in front

Question: Since I upgraded1 from Ubuntu 15.04 to 15.10, I stumbled upon a really frustrating bug of gnome: if I click on a window, it correctly gets the focus but stays in the background (see screenshot below).
Please note that this issue is not related to any particular window or application. It's the whole window manager that screws up!

Here, I clicked on the firefox' window, it get the focus --- I can enter keyboard shortcuts for instance --- but the gnome-terminal window sits there ...
If I Alt-Tab, the newly focused window is correctly put in the front.

1) I've got the exact same issue with a newly installed Ubuntu 15.10 from scratch. Maybe it is related to my configuration (I kept my $HOME folder).

Envirnment

Linux 4.2 on x86_64
Ubuntu 15.10
gnome-session 3.16.0-1ubuntu2
(ask for more)

What can I do to fix it?
Comment: Check this thread: http://askubuntu.com/q/80969/
Comment: @whtyger Unfortunately, this is not the same issue, though it is related to focus. I tried the suggested solutions anyway (who knows?) but it didn't help.
Comment: Gnome-terminal does have a function "always on top". Normally you can check and un-check it with a right mouse click in the upper part of the terminal. (right from the minimize, maximize, close box). Did you check that already?
Comment: I did. This is not related to the "always on top" feature I think. Question updated.
Answer: Have you checked this out?
It's for an older version of Ubuntu (10.04), but the problem seems similar to yours, so it might be worth checking out.

August 19th, 2012 by A Traveller

Re: Windows staying on top Thanks Frogs Hair. Your suggestion has
  fixed the problem! Here is what I did:-
Press 'Alt + F2'     Typed 'gconf-editor' and clicked 'Run'
  Expanded 'Apps', then 'Metacity' and the clicked on 'General'
  Double-clicked 'raise_on_click' and changed the 'Value' to 'True' by
  clicking on the button which said 'False'       Clicked 'OK' and then
  closed the Gconf Editor window     Voila!
I have read warnings advising against changing the Value to False, but
  can't remember ever changing it to False. I have played with the
  location of the maximize, minimize and close buttons but I don't know
  how the raise-on-click got changed. I did install Ubuntu Tweak
  recently but don't know if anything I may have changed in that caused
  the problem.
Comment: It did not solve my problem, but it lead me to the solution. So thank you.
Answer: Thanks to the suggestion of Phrostatus, I ended up opening gconf-editor and something bizarre happened when I played with its keys. When I opened gnome-tweak-tool, it did not display the same configuration as gconf-editor would. It smelled fishy.
The solution, quite radical, was to reset my entire gnome-session configuration.

Back it up!
mkdir ./.gnome-config.bak/ && mv ./.gnome* ./.gnome-config.bak/ && mv .gconf* ./.gnome-config.bak/ && mv ./.metacity ./.gnome-config.bak/ && mv ./.cache ./.gnome-config.bak/ && mv ./.dbus ./.gnome-config.bak/ && mv ./.dmrc ./.gnome-config.bak/ && mv ./.mission-control ./.gnome-config.bak/ && mv ./.thumbnails ./.gnome-config.bak/   && mv ~/.config/dconf/* ./.gnome-config.bak/

Kill it with fire!
rm -rf .gnome .gnome2 .gconf .gconfd .metacity .cache .dbus .dmrc .mission-control .thumbnails ~/.config/dconf/user ~.compiz*

Close and reopen you session...
Enjoy!

Focused window is not in front


What happens to class members when malloc is used instead of new?

Question: I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this:

Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why.

The program:
#include<iostream.h>
class cls
{     int x;
      public: cls() { x=23; }
      int get_x(){ return x; } };
int main()
{     cls *p1, *p2;
      p1=new cls;
      p2=(cls*)malloc(sizeof(cls));
      int x=p1->get_x()+p2->get_x();
      cout<<x;
      return 0;
}

My first instinct was to answer with "the program is not correct, as new should be used instead of malloc". However, after compiling the program and seeing it output 23 I realize that that answer might not be correct.
The problem is that I was expecting p2->get_x() to return some arbitrary number (whatever happened to be in that spot of the memory when malloc was called). However, it returned 0. I'm not sure whether this is a coincidence or if class members are initialized with 0 when it is malloc-ed.

Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this?
What would your answer to my teacher's question be? (besides forgetting to #include <stdlib.h> for malloc :P)
Comment: Why can't 0 be an arbitrary number too?
Comment: Apart from anything else `` should simply be ``.
Comment: You could also fix your teacher's memory leaks.
Comment: THE STRUGGLES OF FMI UNIBUC
Answer:
Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this?

No, p2->x can be anything after the call to malloc. It just happens to be 0 in your test environment.

What would your answer to my teacher's question be? (besides forgetting to #include  for malloc :P)

What everyone has told you, new combines the call to get memory from the freestore with a call to the object's constructor. Malloc only does half of that.
Fixing it: While the sample program is wrong. It isn't always wrong to use "malloc" with classes. It is perfectly valid in a shared memory situation you just have to add an in-place call to new:
p2=(cls*)malloc(sizeof(cls));
new(p2) cls;

Comment: If you are using placement new you must also explicitly call the destructor (you can not use delete as you did not use new). Also you should enphasis that this is not common (mainley used when building your own container obejcts when you pre-allocate storage for multiple items (not just one))
Comment: I would argue for using `reinterpret_cast`. It emphasizes that you're doing something very dangerous.
Comment: In response to Matthieu M., I don't like to edit 5 year old questions but IMrecentE, I would rewrite my final example above as void* p2Buffer=malloc(sizeof(cls)); cls* p2 = new(p2Buffer) cls;. That way you can later call p2->~cls and free(p2Buffer); and it is obvious that p2 is the "class object" and p2Buffer is the allocated memory pointer.
Answer: new calls the constructor, malloc will not.  So your object will be in an unknown state.
Comment: @Felix: If the constructor isn't called, the value of member data is undefined behavior.
Comment: @Felix Initializing x happens in the constructor, so it's undefined. Even using `new` wouldn't zero out x unless x was actually set to 0 in the constructor; member fields don't get default initializations like in Java
Comment: I know `malloc` doesn't call the constructor. My question was about the class member `x` -- does it get initialized with 0 or does it get some random value that was in memory at that spot?
Comment: If you're building in debug mode I believe the memory will probably be 0'd.  If you're in release mode you will probably see some random number in that space.
Comment: @tloach - that depends on the compiler. Microsoft C++ will fill uninitialized memory with 0xcdcdcdcd (or something like that. Freed memory also gets filled with some similar number) in debug mode. In release mode it doesn't modify the memory at all during malloc/new.
Comment: @tloach, in fact, some operating systems will zero out all the memory allocated for a process (in release). That will only obscure the error more since a simple test program (where malloc always provides new memory) can seem to initialize the memory, while in a more complex environment the values would seem random.
Comment: As tloach mentioned, in order to more easily spot issues in debug mode, some compilers will 0-out the memory that is malloc so that if you stumble on a 0 you know your forgot to allocate it. Unfortunately using 0 might be just what you intended in which case.. you'll just assume it works :/
Comment: @tloach: Like jmucchiello said, the point here is... undefined behavior is undefined.
Answer: The actual behaviour is unknown, because new acts pretty the same like malloc + constructor call.
In your code, the second part is missing, hence, it could work in one case, it could not, but you can't say exactly.
Answer: Why can't 0 be an arbitrary number too? Are you running in Debug mode? What compiler?
VC++ pre-fills newly allocated memory with a string of 0xCC byte values (in debug mode of-course) so you would not have obtained a zero for an answer if you were using it.
Answer: Malloc makes no guarantuee to zero out the memory it allocated and the result of the programm is undefined.
Otherwise there are many other things that keep this program from being correct C++. cout is in namespace std, malloc needs to included through#include <cstdlib> and iostream.h isn't standard compliant either.


Can I use 0000 steel wool to remove streaks in my polyurethane finish?

Question: Can I use 0000 steel wool to make a better uniform finish?
Comment: Don't use _steel_ wool when working with water-borne "polyurethane" finishes.  You're talking about "sanding" a dried finish to make it more even?
Answer: I would use a dual action orbital sander and wet/dry paper @1200 grit a very wet sponge to dampen the area dont press down let the sander float and as the streaks are cut out the residue will turn milky, keep wiping and moving this high grit with water will leave a mirror finish, I have used 800 & 1000 to remove larger imperfections but the 1200 works best in my opinion. (agree with JPHIL dont use steel wool)
Answer: Once the urethane has dried, sanding will only fog up the surface. You could sand it to remove any large imperfections and then put on another coat. If you were getting streaks you may want to work in a slightly cooler area so it takes longer to dry and you have more time to work with it.


Hybrid iso - can it be created by isohybrid?

Question: I trying to understand it right. isohybrid is a tool to make Ubuntu iso bootable - see mkusb.

Cloning an iso file to a mass storage device makes a boot drive,
  provided it is a hybrid iso file, post-processed with isohybrid. See
  this link to the isohybrid sub-page.

Also on same link:

mkusb will 'use the whole device', actually only the head end (size of
  the iso file), but the rest of the device is not available. mkusb
  simply clones the ISO 9660 file system with its content from the iso
  file. This ISO 9660 file system works from CD/DVD disks, and also from
  USB drives. After using a USB pendrive like this, you make a new
  partition table and file system, if you want to use it for another
  purpose.

But in wikipedia Hybrid_disc:

A hybrid disc is an optical disc that has multiple file systems
  installed on it, typically ISO 9660 and HFS+ (or HFS on older discs).
  One reason for the hybrid format is the restrictions of ISO 9660
  (filenames of only eight characters, and a maximum depths of eight
  directories, similar to the Microsoft FAT file system).

So do I understand it correctly that isohybrid tool makes ordinary ISO 9660 images, not hybrid ones? What is the meaning of hybrid apex in isohybrid, why is it not called something like isoboot? I could not find that "historic" info via web search.
Comment: Sounds like a question for Sudodus. you can PM him @ https://ubuntuforums.org/private.php?do=newpm&u=1499021
Comment: @DK Bose: Thanks, I just gave the route we usually use. Seems to have worked.
Answer: Hybrid iso file and program isohybrid
The program isohybrid from the package syslinux-utils converts

an iso file that can be burned to a bootable CD/DVD

to

a hybrid iso file, that can be

burned to a bootable CD/DVD and
cloned to a bootable mass storage device: USB pendrive, USB SSD, memory card, internal HDD, internal SSD ...

It is possible to use the robust cloning method to create a boot drive from a mass storage device (most often a USB pendrive).
isohybrid adds some code near the head end of the iso image in order to make this possible.

Please notice that isohybrid should be used only once. Do not you use it on an iso file, that has already this hybrid feature. Most (but not all) linux distros are distributed as hybrid iso files.

I don't know the history of the word isohybrid, but I have used this tool myself, when I made bootable iso files 'from scratch', and I have used it to convert CD/DVD-only iso files for years. Nowadays I seldom use it, because most iso files that I download are already 'isohybrid' iso files, that boot also when cloned into a USB pendrive.
Links
wiki.syslinux.org/wiki/index.php?title=Isohybrid
wiki.osdev.org/El-Torito
A hybrid disc is something else
The link in your question about 'hybrid disc' is describing something else, not a hybrid iso file. The similar names can cause confusion.
Comment: @Martian2020, It is often best to create an own question, where you can describe what you have, what you have done, what you want and what went wrong. Please put a link to the new question here.
Comment: Thanks, have not tried this myself.
Comment: @C.S.Cameron, You are welcome :-)
Comment: Hi! `isohybrid: image.iso: could not find boot record` after `mkisofs -lJR -o image.iso directory_name` directory_name is loopmounted hybrid iso that resulted in properly booting USB. What is wrong? If too complex for comment, than I see a new question is needed.
Comment: https://askubuntu.com/questions/1378005/isohybrid-image-iso-could-not-find-boot-record


How to get the type of a variable

Question: I'm pretty new to Java so please forgive my noob question.
How can I make the error checking logic syntactically correct and what built in methods might I use?
public static void initialize(HighScores[] scores) {
    Scanner input = new Scanner(System.in);

    // capture input
    for (int i = 0; i < 5; i++) {
        System.out.println("Enter the name for score #" + i + ": ");
        String name = input.next(); // Alex
        System.out.println();
        System.out.println("Enter the score for score #" + i + ": ");
        int score = input.nextInt();
        // Error checking
        // if the 'input' is NOT of type 'int'
        if (score.getClass().getSimpleName() != int) {
            // Ask to input a numeric value
            System.out.println("Please enter a numeric value! :)");
            score = input.nextInt(); // inputting a value in again
        }
        System.out.println();

        HighScores object = new HighScores(name, score);

        scores[i] = object;
    }
}

What it would look like if correct:
Enter the name for score #0:
Alex
Enter the score for score #0:
s
Please enter a numeric value! :)
5
Enter the name for score #0:
John
Enter the score for score #0:
3
.... etc...
Comment: If you don't enter an `int`, you will get an error here : `int score = input.nextInt();`
Comment: I'd guess you're from a dynamically-typed background based on this question... Keep in mind that **Java is statically typed**. You don't need to get the type of the variable, because *it's already there when you declared it*. You wrote `int score`, so you know `score` *has* to be an `int`.
Comment: @Anoop That won't work because you can't call methods on a primitive type variable.
Comment: @Anoop - Reflection is not necessary. What would be the purpose of `Scanner# nextInt()` if he had to use reflection to check for the type?
Comment: Your question is very deeply misguided.
Comment: `score.getClass().getSimpleName() != "Integer"`. I am not sure if getClass() will return primitives
Answer: You seem to be confused,
try {
  int score = input.nextInt();
} catch (InputMismatchException ime) {
  ime.printStackTrace();
}

Will always be of type int (or you'll get an Exception), per the Scanner#nextInt()

Scans the next token of the input as an int.

and note that the throws says

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

It is also possible to call Scanner#hasNextInt() first,
if (input.hasNextInt()) {
  int score = input.nextInt();
} else {
  System.out.println(input.next() + " isn't an int");
}

Answer: First, as guys already mentioned in their comments you do not need this. If your variable is defined as int it is int and you do not have to check this.
Second, int is a primitive, so you cannot say score.getClass().
However in some cases (if you write some generic code that must care about several, yet certain types) you probably want to fix your if statement as following:
Integer score = .....
.........
if (Integer.class.equals(score.getClass())) {
   // your code here
}

How to get the type of a variable


Second [[GIDSignIn sharedInstance] signIn] isn't prompting the user

Question: Many people have more than one Google account.  I'd like to support multiple Google accounts in my app.  I'm having trouble getting a prompt for the user to sign in with a second account.
The user can sign in to one account just fine.  Calling sign in the first time results in a call to the delegate with all of the expected values.
When I call signIn again, my app doesn't switch to the Google sign in UI but instead the delegate is called immediately. The values returned to the delegate are for the first account.  In that sense, it's working like signInSilently.
I'm using the iOS Google Sign In SDK version 2.1.0.  I'm using the iOS simulator.
Does the sign in sdk support more than one account?  And if so, how?
My preferred behavior would be for signIn to always prompt the user to sign in.
Answer: Calling signOut before calling signIn will bring up the prompt window again.  The token (or at least the refresh token) seems to still be active after signing out so access to all accounts is still possible.
Comment: Now you're signin to second out as per your answer. Now you want first user access token. ie After signout for first account, then how will you get access token for first account?
Comment: We persisted the access token and refresh token from the first login.  Calling sign out on the first account did not prevent us from using the saved tokens to access the first account.However, in the end, we abandoned the Google SDK in favor of Xamarin Auth, which is open source so we could fix a few issues that prevented it from working well with Google OAUTH2 implementation.
Comment: I know that. But one thing, you may know, anyway I just remember that google access token will expire in 1hour. So First account signout will not work after 1 hour. right? There's many source avail for Google OAuth2. But I want to use GIDSignIn. If there's no way with GIDSignIn, I'll back with any of open source. Thank you rascal2210..


JOptionPane behaving weird with KeyListener

Question: I am currently working on a Sudoku solver with a GUI. Neither is finished, but the GUI is partly operational.
However I have encountered something weird. The code follows below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class SudokuWindow extends JFrame {
    public SudokuWindow() {
        SwingUtilities.invokeLater(()->createSudokoWindow());
    }

    private void createSudokoWindow() {
        JFrame frame = new JFrame("Sudoku!");
        int height = 600;
        int width = 1000;
        frame.setPreferredSize(new Dimension(width,height));
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new FlowLayout());
        SudokuBoard sB= new SudokuBoard(width/2,width/2,9,9);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JButton button1 = new JButton("Import solvabel setup");
        JButton button2 = new JButton("Find solution");
        JTextField t1=new JTextField("0");
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
        panel.add(button1);
        panel.add(button2);
        panel.add(t1);
        mainPanel.add(sB,BorderLayout.WEST);
        mainPanel.add(panel, BorderLayout.EAST);
        frame.add(mainPanel);
        frame.pack();
        frame.setVisible(true);
    }

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

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class SudokuBoard extends JPanel {
      int width, height, rows, cols;
      JFormattedTextField[][] txtM = new JFormattedTextField[9][9];

      SudokuBoard(int w, int h, int r, int c) {
            setSize(width = w, height = h);
            this.setPreferredSize(new Dimension(w,h));
            for(int i = 0; i < r; i++) {
                for(int j = 0; j < c; j++) {
                    txtM[i][j] = new JFormattedTextField();
                }
            }
            rows = r;
            cols = c;
      }

      public void paint(Graphics g) {
            width = getSize().width;
            height = getSize().height;

            int rowHt = height / rows;
            int colWt = width / cols;
            JFormattedTextField t;

            for (int i = 0; i < rows; i++) {
                for(int j = 0; j < cols; j++) {
                    t = txtM[i][j];
                    t.setText("0");
                    t.setSize(rowHt,colWt);
                    t.setMargin(new Insets(0,18,0,0));
                    t.setFont(new Font("TimesRoman",Font.PLAIN,26));
                    t.setLocation(i*colWt, j*rowHt);
                    t.addKeyListener(keyListener);
                    if((((j+1) % 9 == 1 || (j+1) % 9 == 2 || (j+1) % 9 == 3) && ((i+1) % 9 == 1 || (i+1) % 9 == 2 || (i+1) % 9 == 3))){
                        t.setBackground(Color.MAGENTA);
                    } else if(((j+1) % 9 == 7 || (j+1) % 9 == 8 || (j+1) % 9 == 0) && ((i+1) % 9 == 1 || (i+1) % 9 == 2 || (i+1) % 9 == 3)){
                        t.setBackground(Color.MAGENTA);
                    } else if(((j+1) % 9 == 7 || (j+1) % 9 == 8 || (j+1) % 9 == 0) && ((i+1) % 9 == 7 || (i+1) % 9 == 8 || (i+1) % 9 == 0)){
                        t.setBackground(Color.MAGENTA);
                    } else if(((j+1) % 9 == 1 || (j+1) % 9 == 2 || (j+1) % 9 == 3) && ((i+1) % 9 == 7 || (i+1) % 9 == 8 || (i+1) % 9 == 0)){
                        t.setBackground(Color.MAGENTA);
                    } else if(((j+1) % 9 == 4 || (j+1) % 9 == 5 || (j+1) % 9 == 6) && ((i+1) % 9 == 4 || (i+1) % 9 == 5 || (i+1) % 9 == 6)){
                        t.setBackground(Color.MAGENTA);
                    }
                    add(t);
                }
            }
        }

        KeyListener keyListener = new KeyListener() {
            @Override
            public void keyPressed(KeyEvent e) {}

            @Override
            public void keyTyped(KeyEvent e) {
                if(Character.isLetter(e.getKeyChar()) || ((Character) e.getKeyChar()).equals('0')){
                    JOptionPane.showMessageDialog(null, "Invalid input!");
                }

            }

            @Override
            public void keyReleased(KeyEvent e) {}
        };
}

The code works as intended so far except for one thing. When the KeyListener finds a Letter or a 0, the JOptionPane pops up three times. This is kind of annoying, and I don't understand why it does that.
Also I am trying to reach the JFormattedTextFields so I can reset them after a Invalid input but can't reach them through the KeyListener. Is there some nice way to do this?
If anyone could help me figure this out I would greatly appreciate it!
Thank you!
Comment: **Don't override paint().**. Painting methods are for custom painting only. You are NOT doing custom painting. This can cause multiple components to be created and added to the panel every time Swing decides the components needs to be repainted. Your components should be created and added to the panel in the constructor of your class and a `GridLayout` should be used to position the components in a grid
Comment: There is no need for a KeyListener. You can configure the `JFormattedTextField` to use a `MaskFormatter` to only accept numeric digits and you can then use the `setValidCharacters(...)` method to limit the digits from 1-0.
Answer: TL;DR
Your problem is that you are adding another KeyListener to each JFormattedTextField every time method paint is called and each listener is executed. So if...

the JOptionPane pops up three times

then it means that method paint was called three times which caused three listeners to be added to each JFormattedTextField.

Other general notes regarding your code:
Class SudokuWindow:

Swing application classes, such as your SudokuWindow, don't need to extend JFrame. In any case you create a new JFrame in method createSudokoWindow() (of class SudokuWindow) so really no need for class SudokuWindow to extend JFrame.
mainPanel.add(sB,BorderLayout.WEST); Because you explicitly set the layout of mainPanel to FlowLayout, the BorderLayout constraints are ignored. If you want to use BorderLayout constraints then you need to set the layout manager for mainPanel to BorderLayout.
frame.setPreferredSize( Better you should not use mainPanel at all and instead use the content pane of the JFrame – whose default layout manager is BorderLayout – and set the preferred size of the SudokuBoard and add it to BorderLayout.CENTER.

Class SudokuBoard:

Set its layout manager to GridLayout and set its preferred size. Then you don't have to worry about explicitly setting sizes for each JFormattedTextField.
If you are going to override a painting method, then it almost always should be paintComponent and not paint. However you don't need to override any painting method since you should create the JFormattedTextFields in the constructor and set the background colors also in the constructor rather than in method paint.
As mentioned by @camickr in his comment, you don't need a KeyListener if you are using JFormattedTextField.

Consider the following (which is my alternative solution):
(Notes and explanations after the code.)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.text.ParseException;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LookAndFeel;
import javax.swing.UIDefaults;
import javax.swing.UIManager;
import javax.swing.text.MaskFormatter;

public class SudokuPuzzle {
    private static final int  COLS = 9;
    private static final int  ROWS = 9;
    private static final Color[][]  BACKGROUNDS;

    static {
        LookAndFeel laf = UIManager.getLookAndFeel();
        UIDefaults dflts = laf.getDefaults();
        Color dflt = (Color) dflts.get("TextField.background");
        Color mgnt = Color.magenta;
        BACKGROUNDS = new Color[][] {{mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt},
                                     {mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt},
                                     {mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt},
                                     {dflt, dflt, dflt, mgnt, mgnt, mgnt, dflt, dflt, dflt},
                                     {dflt, dflt, dflt, mgnt, mgnt, mgnt, dflt, dflt, dflt},
                                     {dflt, dflt, dflt, mgnt, mgnt, mgnt, dflt, dflt, dflt},
                                     {mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt},
                                     {mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt},
                                     {mgnt, mgnt, mgnt, dflt, dflt, dflt, mgnt, mgnt, mgnt}};
    }

    private void buildAndDisplayGui() throws ParseException {
        JFrame frame = new JFrame("Sudoku!");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createBoard(), BorderLayout.CENTER);
        frame.add(createButtonsPanel(), BorderLayout.LINE_END);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createBoard() throws ParseException {
        JPanel board = new JPanel(new GridLayout(0, 9));
        board.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        for (int row = 0; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                board.add(createSquare(row, col));
            }
        }
        return board;
    }

    private JPanel createButtonsPanel() {
        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));
        BoxLayout layout = new BoxLayout(buttonsPanel, BoxLayout.PAGE_AXIS);
        buttonsPanel.setLayout(layout);
        buttonsPanel.add(Box.createVerticalGlue());
        JButton button1 = new JButton("Import solvable setup");
        buttonsPanel.add(button1);
        buttonsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
        JButton button2 = new JButton("Find solution");
        button2.setMaximumSize(button1.getMaximumSize());
        buttonsPanel.add(button2);
        buttonsPanel.add(Box.createRigidArea(new Dimension(0, 5)));
        JTextField t1 = new JTextField("0");
        t1.setMaximumSize(button1.getMaximumSize());
        buttonsPanel.add(t1);
        buttonsPanel.add(Box.createVerticalGlue());
        return buttonsPanel;
    }

    private JFormattedTextField createSquare(int row, int col) throws ParseException {
        MaskFormatter formatter = new MaskFormatter("#");
        formatter.setValidCharacters("123456789");
        JFormattedTextField ftf = new JFormattedTextField(formatter);
        ftf.setColumns(2);
        ftf.setHorizontalAlignment(JTextField.CENTER);
        ftf.setFont(new Font("TimesRoman",Font.PLAIN,26));
        ftf.setBackground(BACKGROUNDS[row][col]);
        return ftf;
    }

    public static void main(String[] args) {
        SudokuPuzzle puzzle = new SudokuPuzzle();
        EventQueue.invokeLater(() -> {
            try {
                puzzle.buildAndDisplayGui();
            }
            catch (ParseException xParse) {
                xParse.printStackTrace();
            }
        });
    }
}

I don't see a need for a SudokuBoard class that extends JPanel since there is no need to override any of JPanel class methods.
Since the valid characters are 1 - 9, I can't set the text of each JFormattedTextField to 0 (zero), hence the JFormattedTextFields are initially all empty.
Default behavior of JFormatedTextField, when entering an invalid value, is to beep. If you want to display a JOptionPane instead then I think you will need to write your own formatter and use that instead of MaskFormatter. I felt it was too much work for me so I just left the default behavior.

Here is how it looks:
Comment: Thank you very much! I did not expect such a comprehensive answer. You rewrote the code and everything! Solved my issues completely! Again thanks a bunch!


Error while accessing contents from other website using php and curl

Question: error setting certificate verify locations: CAfile: /var/local/etc/ca-bundle.crt CApath: none
I am getting the above error while accessing the content of a website using php with curl. I am very new to using both php and curl so not able to find the solution. Can someone please help?
Answer: running these commands should fix the problem:
<code>sudo rm -rfv /var/local/etc/ca-bundle.crt
sudo curl -o /var/local/etc/ca-bundle.crt https://curl.haxx.se/ca/cacert.pem
sudo chmod 0444 /var/local/etc/ca-bundle.crt
</code>
some pages you can check for details: https://curl.haxx.se/docs/sslcerts.html / https://en.wikipedia.org/wiki/Certificate_authority
Comment: I can see this in terminalPoojas-MacBook-Pro:~ poojadeole$ sudo curl -o /var/local/etc/ca-bundle.crt https://curl.haxx.se/ca/cacert.pem
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0Warning: Failed to create the file /var/local/etc/ca-bundle.crt: No such file
Warning: or directory
  0  230k    0  2068    0     0  10578      0  0:00:22 --:--:--  0:00:22 10605
curl: (23) Failed writing body (0 != 2068)
Comment: Sorry...but I can't exactly understand where is /var/local/etc/ca-bundle.crt
Comment: huh. add --create-dirs  to the curl command then. `sudo curl -o /var/local/etc/ca-bundle.crt --create-dirs https://curl.haxx.se/ca/cacert.pem`


Excel TEXT formula doesn't convert 'yyyy' to a year

Question: I want to combine some text with a date in Excel 2013.
Let's say I have a cell A2 with a date like 30-10-2014. I tried to append the date after the text with this formula:
="Some text and a date: "&A2
But the output shows the date as a number: Some text and a date: 41942
So I tried it with the TEXT formula:
="Some text and a date: "&TEXT(A2;"dd-mm-yyyy")
But this shows Some text and a date: 30-10-yyyy and not Some text and a date: 30-10-2014
So or I do not understand how the TEXT formula works or is there some bug / issue here?
UPDATE: It looks like it's important that I have a Dutch version of Windows (7) but an English version of Excel (2013) which causes this issue!
Answer: All kudos go to @AxelRichter, thanks Axel!
It looks like that if you have a Dutch Windows but an English version of Excel (2013) the formulas get mixed up. For example, I still have the English formula names like TEXT (which would be TEKST in Dutch) but still have to use a colon instead of a comma in the formula. The format_text value of TEXT still expects the Dutch format which is different for the year (jjjj instead of yyyy).
So if you have a Dutch Windows and an English Excel version the correct formula for some text followed by a formatted date would be:
="Some text and a date: "&TEXT(A2;"dd-mm-jjjj")
I hope Microsoft will fix this, this is very annoying!
Comment: The format pattern for dates comes from the Windows locale settings and have to be "dd-mm-jjjj"; [d]ag [m]aand [j]aar if it is a Netherlands Windows. Also the formula delimiter (list delimiter) is ";" per default in Netherlands Windows. Only the function name TEXT comes from the English Excel. So there is nothing to fix for Microsoft ;-).

And, no, the string within the TEXT function =TEXT(A1;"dd-mm-jjjj") will not change automatically if someone uses other locale settings. This is one of the disadvantages of the TEXT function.
Comment: @AlexRichter, you wrote "there's nothing to fix for Microsoft" - well, there's definitely something they could improve. Even if they insist on localizing the format specification (y vs j), then they should provide a way to suppress that - e.g. allow an argument specifying the locale. Or simply providing a function which always takes the same format (the English one). Otherwise you end up with a nightmare of the same file looking differently on different computers.
Comment: @AxelRichter, This is definitely an issue with the TEXT() function if you are sending the same Excel document to various people with different locales (which you cannot control). There should be locale-independent formatting strings.
Comment: For PT-BR: AAAA
Comment: I don't believe that it is possible to change the date/time pattern without changing the whole locale to another language. The list delimiter is changeable http://www.solveyourtech.com/change-the-windows-7-list-separator/ But this not really makes sense in my opinion. It only increases the confusion because it often comes in conflict with the decimal separator which can not be the same as the list separator.
Comment: @AxelRichter Thanks again for your detailed explanation, do you also know how to change the locale settings for this in Windows?
Comment: OK, in that case I'll keep in mind not to mix the OS language with the Excel language next time ;-)
Comment: This almost drove me nuts. C'mon MS, fix this damn thing !!! up-voted <3
Comment: I have tried RRRR but never guessed jjjj
thank you very much :)
Comment: what if its a shared document and people are using it in different countries. is there any generalized formula so that id doesn't feel invalid for other countries.
Answer: You can now use 'e' instead of 'yyyy'. The e is the universal version of yyyy a
Comment: Do you have a link to the source?
Comment: Are there similar variants for `mm` and `dd`?
Answer: we have the same issue at our work and I found that if I cannot influence the localization of the windows then I use a formula which in your case looks like:
="Some text and a date: "&TEXT(A2;"dd-mm-")&YEAR(A2)

It is funny that "dd" and "mm" is the same.
Comment: It's not "funny", it's what Dutch words are: day = dag, month = maand. Try a German local and "dd" will stop working (day = Tag).
Comment: This worked for me on US-EN on Spain-Spanish PC. What a mess this was.
Answer: Excel here obviously fails. TEXT should be language agnostic.
The workaround I found, especially if you have multiple cells to format:

Calculate the desired date format in a hidden cell or white colored:

=IF(TYPE(VALUE(TEXT(DATE_CELL;"YY")))=1;"DD.MM.YYYY";"ДД.ММ.ГГГГ")
If you need, it can be extended to support multiple regions like:
=IF(TYPE(VALUE(TEXT(DATE_CELL;"YY")))=1;"DD.MM.YYYY";IF(TYPE(VALUE(TEXT(DATE_CELL;"ГГ")))=1;"ДД.ММ.ГГГГ";"DD.MM.JJJJ"))

On cells where you need dates, use previous cell as second parameter:

="Date: " & TEXT(DATE_CELL; FORMAT_CELL)
Answer: This should work regardless of your system language or regional settings:
="Some text and a date: "&TEXT(DAY(A2);"00")&"-"&TEXT(MONTH(A2);"00")&"-"&TEXT(YEAR(A2);"0000")

Click here to see it working
[Edit] I just tested the solution with German (TT.MM.JJJJ) and English settings (DD.MM.YYYY) and it works fine!
You may need to use , instead of ; in the MS EXCEL formula (depending on your actual list separator symbol --> check your OS settings!).
Comment: It looks a bit ugly, but your solution is the only one that works on a wide range of Excel versions and Windows locales without resorting to macros (often limited for security reasons) or named functions (a less "in the face" redirect, tougher to spot cell dependencies with in Trace Dependents and therefore harder to set-up).
Answer: For same problem when your system or keyboard is Danish then use åååå in place of jjjj. I also struggled a lot to find this key.
However if anyone facing same problem apart from Dutch or Danish then you can check which key is correct.  To find it right click on any cell and goto 'Format Cell' then select 'Custom' and find date related formats in your local language. There you can find which is the right key to be used for DATE format in your local language.
Answer: This issue is still there on Excel 2016 (or Office 365, if you may). It is caused by different language settings in Windows. This happens for languages that have different year symbols (dutch is 'jjjj', portuguese is 'aaaa'). If you're experiencing this problem, try using your local Windows language's year format.
Answer: My computer is set to English (German). I had to use tt/MM/jjjj. Carefully note its MM not mm.
Comment: 'German' English? What is German English?
Comment: It's one of the language options in windows. Possibly English with German number and date formats, etc.
Comment: I'm asking because I speak American English, but I've also heard of UK English, Australian English, Canadian English IRCC, but I have not heard of German English.
Comment: "English (Germany)" is a language configuration that one can install on Windows, see [this screenshot](https://web.archive.org/web/20240116122527/https://files.mastodon.social/media_attachments/files/111/765/611/329/959/603/original/955dbd1ff7607a5c.png). It likely works similar to my "English (Netherlands)" setting, Excel uses `j` for year instead of `y`.
Answer: Solution: To check if "jjjj" format is working:
The date you want to display in a certain format is in A1
In cell A2 link a cel to the cel with the date you want displayed in a certain format with the following formula:
=TEXT(A1;"dd/mm/jjjj")

In a 3rd cel you then place the following formula:
=IF(RIGHT(A2;4)="jjjj";TEXT(A1;"yyyy");TEXT(A1;"jjjj"))

If the 4 digits from the right are "jjjj" this formula will display the date formatted as "yyyy" else the formatting "jjjj" will be used.
Comment: What if your companion uses the Bengali locale or the Russian one? (And you don't know in advance or ever.)
Answer: The easy fix, whether directly custom formatting a cell or using TEXT(), is to use a country code for a language you know the proper formatting codes for.
For instance, I am in the US, have a US version of Excel, and am familiar with its date code formats. So I'd want to use them and to ensure they "come out" regardless of anyone's Windows or Excel version, or the country they are in, I'd do it like the following (for TEXT(), let's say, but it'd be the same idea in custom formatting):
=TEXT(A1,[$-en-US]"dd-mm-yyyy")

The function would collect the value in A1, ask Excel to treat it as a date, Excel would and would say fine, it's cool (i.e.:  the value is, say, 43857 and not "horse") because it is a positive number which is a requirement for anything to be treated as a date, and let the function move on to rendering it as a date in the manner prescribed. Rather than  giving an #ERROR! as it would for "horse" or -6.
The function would then read the formatting string and see the language code. It would then drop the usual set of formatting codes it loaded upon starting up and load in the formatting codes for English ("en") and in particular, US English ("US"). The rest of the string uses codes from that set so it would interpret them properly and send an appropriate string back to TEXT() for it to display in the cell (and pass on to other formulas if such exist).
I have no way to test the following, but I assume that if one were to use a format that displayed day of the week names or month names, they would be from the same language set. In other words, Excel would not think that even though you specified a country and language that you still wanted, say, Dutch or Congolese month names. So that kind of thing would still need addressed, but would be an easy fix too just involving, say, a simple lookup one could add though it'd be "fun" setting up the lookup table for each language one wanted to accomodate...
However, the basic issue that arises here, and with this problem in general, is very, very easily solved with the country codes. They aren't even hard or arcane anymore now that the [$-409] syntax has been replaced with things like [$-en-us] and [$-he-IL] and so on.
Comment: English Excel, German OS `=TEXT(DATE(2021;11;25);"[$-en-us]ddd")`  returns `ddd`; `=TEXT(DATE(2021;11;25);"[$-en-us]ttt")` returns `Thu` and `=TEXT(DATE(2021;11;25);"ttt")` returns `Do`. The [$-en-us] part only controls the output, not the recognition of a format specifier.
Answer: If VBA is an option... works for any locale/language
Public Function dateYYYYMMDD(dt As Date) As String
    dateYYYYMMDD = Format(dt, "yyyyMMDD")
End Function


The switch statent and return values - How to use a switch to determin JPanel drawn

Question: I have a program which has different JPanels written in different classes. I would like to print a particular JPanel depending on the button clicked by a user.
When the program is launched, it only has three buttons: "Animals JButton", "Plants JButton" and a "Refresh JButton" in a JFrame "frame"; no JPanel.
If, for example, a user clicks on the "Animals JButton", the JPanel with Animals gets printed on the JFrame.
The "AnimalsJPanel" and "PlantsJPanel" are written in different classes. Another class, "PageReturner", has a method that determines what gets printed via a switch.
public class Redirect {

    String pageAnimals = "pageAnimals";
    String pagePlants = "pagePlants";

    String value;

    public String pageRedirect (String pageID) {
        switch (pageID) {
            case pageAnimals:
                value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel());
            break;
            case pagePlants:
                value = (PlantsJPanel plantsJPanel = new PlantsJPanel());
                break;
            case 2:
                value = null;
                break;
        }
        return null;

    }

}

I get "constant string expression required" and "incopatible types" errors in netbeans. What might be the problem with my switch statement, and is there a better way to go about this, i.e, determining a page to print.
I'd like to code this and not use cardlayout. I'm new to JAVA and trying to learn how to get objects from classes.
Is my switch statement even well done. I'm teaching myself programming, and have no one to consult. Much appreaciation in advance for any advice
Answer: Declare variable as final those are used in switch case.
   final String pageAnimals = "pageAnimals";
   final String pagePlants = "pagePlants";

Since all case labels should be compile time constants in Switch.
Comment: Thanks for the fast reply. It solved the "constant string expression required". How do I handle the "incompatible types - required: string - found AnimalsJPanel" and required: string - found PlantsJPanel
Comment: how are you calling `pageRedirect()` method.?edit your question with that code
Answer: Declare pageAnimals and pagePlants as static final (note the variable name change to match java conventions for constants):
static final String PAGE_ANIMALS = "pageAnimals";
static final String PAGE_PANTS = "pagePlants";

Also, you have to explicitly case the panels to String:
case PAGE_ANIMALS :
     value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel()).toString();
     break;
case PAGE_PANTS :
     value = (PlantsJPanel plantsJPanel = new PlantsJPanel()).toString();
     break;

Answer: You are assign a JPanel object to a String and you can't do that!
Define value as JPanel value; or do write value = (AnimalsJPanel animalsJPanel = new AnimalsJPanel()).toString();


How to use __func = None in Python decorators

Question: I have the following decorator(as per https://realpython.com/primer-on-python-decorators/#decorators-with-arguments):
def slow_down(_func=None, rate = 1):

    def decorator(func):

        print(_func) # Added for understanding?

        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            time.sleep(rate)
            return func(*args, **kwargs)
        return wrapper

    if _func==None:
        return decorator

    else: return decorator(_func)

My question is, shouldn't a this slow_down function initialize with _func = None ? However, when I create a function with the decorator, I get an initialized _func value:
@slow_down
def countdown(time = 5):
    print(time)
    if time == 0: pass
    else: countdown(time-1)
<function countdown at 0x7f1aa0a8da60>

But when I initialize the value of the function, I get None:
@slow_down(rate=2)
def countdown(time = 5):
    print(time)
    if time == 0: pass
    else: countdown(time-1)

None

Shouldn't it be the other way around?
Comment: When you use a bare name for a decorator (as in `@slow_down`), it is called with the function being decorated as a parameter.  When parentheses are involved (as in the second case), the decorator is called as written, and is expected to return another function which gets called with the function being decorated as a parameter.  The `if` in your particular decorator allows it to work either way.
Answer: When you use a bare name for a decorator (as in @slow_down), it is called with the function being decorated as a parameter. When parentheses are involved (as in the second case), the decorator is called as written, and is expected to return another function which gets called with the function being decorated as a parameter. The if in your particular decorator allows it to work either way. – jasonharper


How to pause stream consumption in caolan/async queue v3

Question: I have a working stream consumer in caolan v2.6.3 which basically pauses the stream consumption as soon as the queue is saturated and resumes after it's drained:
let q = async.queue(function(tasks, callback) {
  // ...
  callback()
}, 4);

q.drain = function() {
  some_readable_stream.resume()
}

q.saturated = function() {
  some_readable_stream.pause();
}

some_readable_stream.on("data", function(data) {
  q.push(data);
});

It seems there's breaking change in v3 After updating, above logic fails with error
Cannot assign to read only property 'saturated' of object '#<Object>'

But I am uncertain what would be the correct replacement for this in v3.
Anyone any hints?
Answer: properties from v2 q.saturated, q.unsaturated and q.drain are methods in v3, so it can be solved like this:
// ...

q.drain(function() {
  some_readable_stream.resume()
})

q.saturated(function() {
  some_readable_stream.pause();
})

//...


I want a list of all the William Hill betting shops in the UK

Question: I am trying to obtain a list of all the William Hill Betting shops in the UK using the google places api. However, using the google places api will only let me return up to 60 results. Does anyone know of a way around this or an alternative approach to the problem I am having?
Answer: The places API has a pagetoken optional parameter that is used to return the next set of results.
https://developers.google.com/places/web-service/search#find-place-responses
Edit: I didn't realize the you could only get a maximum number of 60 results. To get around this you can search a smaller area that won't have more than 60 results.
You can use a combination of location (latitude and longitude) and radius. You can create a box and iteratively shift the coordinates left to right and up and down until your entire area is covered. You can use something like geopy to help you calculate the coordinates and then send the request to the google places API
Comment: Each page gives you 20 results. Using the pagetoken parameter you can get up to 60 results but I don't think beyond this.
Comment: Looking into it further, you're correct 60 is the max number of with the same query. I think the way around this would be go break your search into grid sections where there wont be more than 60 results in a given area


Azure DevOps - how to know a Resolved work item is actively being tested (vs. in the queue)

Question: TLDR;
Does Azure DevOps have a recommended built in way of marking Resolved Work Items as being actively tested as opposed of being in the queue for testing?
Details
My team is using Azure DevOps with Agile workflow.
This means that out-of-the box a user story goes through the following states

New -> Implementation started ->
Active -> Code complete ->
Resolved -> Acceptance tests passed ->
Closed

This is nicely shown at learn.microsoft.com:

Testing happens in when the story (or bug) is in the Resolved state.
The out of the box board has 4 lanes.

When looking at the board (or even in queries) I'm having trouble seeing what is being actively tested.
For example, if there are 2 resolved items it is not clear which one is being actively worked on and which one is waiting to be picked up.
Showing what is being tested seems like a common desire and my intuition is that the solution for my problem is built in. I want to avoid customising the workflow (and adding a new state called Testing).
Cross-post from pm.stackexchange.com
Answer: I would suggest using the Kanban board and adding a column named Testing. This won't require adding a custom state to your workflow but does give you more visibility into the state of a work item.
You can also split columns into Doing and Done so you know where an item is stuck in the flow of your work.
Answer: In my company we have been in the same situation.
I like @Wouter's answer and I think it deserves upvotes, but I just want to expose it in another way (it depends on your needs, maybe they are similar to mine).
In my company we have a board with a column called "Testing" (divided into "Doing" and "Done") but this board is only for developers, for their tests. But in our development lifecycle there is another step called "UAT" where the software is deployed in a test environment called "uat" ... and is tested by business users who run their own acceptance tests.
Now, we developers don't want these business users to use Azure DevOps Boards or, worse, change work item states (we tried, it can be a mess).
We want to isolate their actions on a Test Plan.
Therefore, when the release pipeline deploys in the "uat" stage N work items, it also creates a Test Plan with N test cases (manual, not automated) that our business users must validate with Pass / No pass.
When all test cases have been validated, we can deploy the build to Production.
Maybe this suites you.
Comment: "we tried, it can be a mess" :)


Ruby on Rails 4.2.0: How to find the directories set for loading libraries etc

Question: Is there a environment variable and some command-line options to check my rails application's directories that are set automatically or configured somewhere so that rails know where to load libraries etc.?
As a compare, ruby has a command line option (-I):

ruby -I path:another/path:/usr/lib rubyfile.rb arg1 arg2

such that users can set the directories where libs can be looked up by Ruby.
Similarly, here I am asking if for rails there is a similar way to check the loading paths for Rails applications? Or if there is certain variable set somewhere?
Highlight: I am using Rails version 4.2.0. The config/application.rb sample code doesn't appear to contain config.autoload_paths, not even in comments, which used to be the one for Rails 3 and Rails 4.1.x.
And, how would the Rails application know where to look up for Gems, etc.?
Thanks!
Answer: See this file:
config/application.rb

Specifically, you add this setting:
config.autoload_paths

You can add to the autoload paths like this:
config.autoload_paths << Rails.root.join('mydir')

The config.autoload_paths accepts an array of paths from which Rails will autoload constants.
The default is all directories under ./app, such as controllers, models, etc.
The default does not autoload from the typical top-level ./lib directory. If you want to autoload from lib:
config.autoload_paths << Rails.root.join('lib')

See the Rails Guides for Configuring
Rails knows where to look for gems a variety of ways: typically your environment GEM_PATH or the bundler gem bundle exec command. For example, I personally bundle my Rails gems into ./vendor/bundle/.
Comment: Oh, thanks! That makes sense. Just a quick follow-up: the Guide said the default is all dirs under app/, then the lib/ dir is NOT by default included? I am also confused and surprised that the default is just all dirs under app/ - then how would the Rails applications load those Gems without knowing where they are?
Comment: Thanks for sharing your answer! However, this does not seem to be the one for Rails version 4.2.0. The application.rb does not contain config.autoload_paths variable. Actually, I didn't find it throughout the whole Rails application generated under version 4.2.0. I know it was there for Rails 3.x.x, though. I will update my question to highlight my Rails version.
Comment: Rails 4.2 uses the same setting -- it's just that the default new app doesn't put it in, so you need to add it yourself.


Centre of symmetry of a triangle

Question: Suppose we have a $\triangle ABC$ wherein points $D,E,F$ are confined to move along the edges of $BC, AC, AB$ respectively such that $\triangle DEF \sim \triangle CAB$. What would be the centre of symmetry for the $\triangle FED$ ?
If instead $\triangle DEF \sim \triangle ABC$, then what would the centre of symmetry of$\triangle FED$ ?
By centre of symmetry, I mean the fixed point about which $\triangle ABC$ can be scaled and rotated to get the required $\triangle DEF$.
Answer: Such a point is the orthocenter of $DEF$.

It is easier to build $ABC$ given $DEF$: since $\widehat{FAE}=\widehat{FDE}$ and so on, the circumcircles of $FAE,ECD,DBF$ meet on the orthocenter $H$ of $DEF$. Given that $D',E',F'$ are the mirror images of $D,E,F$ with respect to the midpoints of $EF,DF,DE$, we have:
$$\widehat{AFD'}=\widehat{AHD'}=\widehat{AED'}=\widehat{F'EC}=\widehat{F'HC}=\widehat{F'DC}=\widehat{BDE'}=\widehat{BHE'}=\widehat{BFE'},$$
so $H$ is the wanted symmetry point.
Comment: So what would be H in terms of $\triangle ABC$?
Comment: And what about the first case where $\triangle DEF \sim \triangle BAC$ ?
Comment: @user117913: if $DEF$ is not similar to $ABC$ as expected, but to $BCA,CAB,ACB$ or $CBA$, the the symmetry point is the mirror image of the orthocenter of $DEF$ with respect to an angle bisector of $DEF$. With respect to $ABC$ we have not a fixed point, but a point travelling on a curve (it should be an hyperbola).

Centre of symmetry of a triangle


"Accept-language" not set in the request header while using URLConnection in android?

Question: I am using URLConnection to download the html file from an android app. But I want the HTML content based on the device-locale.
Suppose user send the request from German locale then response should be in german language. I am expecting that URLConnection should send accept-language according to device-locale, similar to ajax calls. But accept-language header is not present in the request made by URLConnection.
Do I need to set request header explicitly or are there any alternative?
Thanks in advance.
Comment: Possible duplicate of [Android HTTP calls not setting Accept-Language headers?](https://stackoverflow.com/questions/21345363/android-http-calls-not-setting-accept-language-headers)
Answer: You can use any of following to get the device locale language in your format -
Locale.getDefault().getLanguage()       ---> en
Locale.getDefault().getISO3Language()   ---> eng
Locale.getDefault().getCountry()        ---> US
Locale.getDefault().getISO3Country()    ---> USA
Locale.getDefault().getDisplayCountry() ---> United States
Locale.getDefault().getDisplayName()    ---> English (United States)
Locale.getDefault().toString()          ---> en_US
Locale.getDefault().getDisplayLanguage()---> English

Source - Refer here
You can give Accept-Language header in your request like -
URL url = new URL("website url");
URLConnection urlconnection = url.openConnection();
urlconnection.setRequestProperty("Accept-Language", "en-GB");


changed /etc permission in oneiric (ubuntu11.10) by using "sudo chmod 665 /etc" cant use sudo now

Question: I screwed up big time. I changed the permission of /etc in ubuntu 11.10 by using following command
sudo chmod 665 /etc

now when ever i try to use sudo it gives the following error:
sudo: can't open /etc/sudoers: Permission denied
sudo: no valid sudoers sources found, quitting

Any help will be greatly appreciated because i am new to Ubuntu. I have already tried using su but it doesnt even login as root and even i give it the right password it always say Authentication Failure. I don't want to login as root coz its risky and even a newbie in Linux like me is not stupid enough to have such control. I just want to use my sudo again. I have tried to go into recovery mode as well but I can't get in to recovery mode.
Answer: Boot the recovery console option.
Select remount read-write
Select root shell
cd /
chmod 755 etc <--to get it back to default
sync
init 6

Comment: You got the arguments the wrong way around there. `chmod 755 /etc`
Comment: @Tim Changed directory to / first.  Don't like absolute urls.
Comment: i dont know how to boot the recovery console option....i am really sorry but could you give me some hints on how to do it...i.e. boot the recovery console option?
Comment: thanx for the help......my problem is fixed.....happy coding
Comment: I think that should be `/etc`?
Comment: sorry, didn't notice. Any reason why?
Comment: [Habit](http://askubuntu.com/questions/502254/is-the-command-sudo-rm-desktop-filename-safe/502260#502260)
Comment: LIFE SAVER. ty :D
Answer: You can generally fix this sort of problem without booting into recovery mode, without using a live CD, and without rebooting at all. An Ubuntu system with a GUI (as opposed to an Ubuntu Server system with no GUI installed) has two mechanisms for running commands as root. One is sudo. The other is PolicyKit. You can use pkexec, the command-line frontend to PolicyKit, to fix the permissions:
pkexec chmod 755 /etc

If all you did to create the problem was to run sudo chmod 665 /etc, then that completely fixes the problem and you don't need to try to repair any permissions inside /etc. (Nothing inside /etc is changed with a chmod command on /etc that doesn't use the -R flag.)
Comment: +1 for pkexec: surely the most easy and quick way to solve the problem.
Answer: Try inserting the the ubuntu live cd, open up the terminal and enter

sudo su -
mount /dev/sda5 (or whichever is the root partition of your Ubuntu installation) /mnt
chroot /mnt
chmod 755 /etc
exit

This should make things as they were.
Answer: You need to chmod 440 /etc/sudoers. Try to do this in rescue mode or pass init=/bin/bash to boot command line. Ask if you need more info.
Comment: well to be honest i dont know how to go in rescue mode.....i know this is a stupid question but please tell me how to go in rescue mode.....boot menu shows 2 options only
Windows7
ubuntu
Comment: Try liveCD. Anyway, to run sudo you need to `chmod 440 /etc/sudoers`.
Answer: your boot-manager-OS-List looks like the windows-bootmanager, not the ubuntu-grub-bootmanager, which would give you the option to get into recovery mode.
i don't actually know if the system installs grub anywhere anyway, but when you select ubuntu try holding shift to get into the grub-menu (if existent).
Another way would be to edit the boot.ini-file on your windows-partition. There should be an entry for ubuntu. Try appending an 1 to this line and boot into ubuntu. The 1 ends you up in single-user-mode - a command line with root-access to your system.
But the easiest way is a life-CD for sure!!!


Find the adjoint operator of an operator on $C \left [ 0,1 \right ]$

Question: Let $\varphi : \left [ 0, 1 \right ] \to \left [ 0,1 \right ]$ be the continuous function. Let $A : C \left [ 0,1 \right ] \to C \left [ 0,1 \right ]$ be an operator defined by $$\left ( Af\right ) \left ( t \right ) = f \left ( \varphi \left ( t \right ) \right ) $$ for $f \in C \left [ 0,1 \right ]$. Prove that $A$ is a continuous linear operator. Determine norm of $A$ and find the adjoint operator $A^*$.

I proved that $A$ is continuous linear and $\left \| A \right \|=1$. I don't know  how to find the adjoint operator $A^*$ of $A$. Denote $X = C \left [ 0,1 \right ]$, we define $A^*$ by for $y^* \in X^*$ we have $A^*y^* = y^* \circ A$. Hence, for $f^* \in X^*$ we get $$\left ( A^*f^*\right ) \left ( f \right ) = \left ( f^* \circ A\right ) \left ( f \right ) = f^* \left ( Af\right ) = f^* \left ( f \circ \varphi\right ).$$ How can I keep on?
Answer: Recall that $C([0,1])^*$ is the space $M([0,1])$ of Radon measures on $[0,1]$ with the total variation norm. For $\mu \in M([0,1])$ and $f \in C([0,1])$, we have
\begin{align*}
  A^*\mu(f) &= \mu(Af)\\
            &= \int_{[0,1]} f \circ \phi\, d\mu\\
            &= \int_{[0,1]} f \,d(\phi_*\mu)\\
            &= (\phi_*\mu)(f)
\end{align*}
where $\phi_*\mu \in M([0,1])$ denotes the pushforward measure $(\phi_*\mu)(B) = \mu\bigl(\phi^{-1}[B]\bigr)$ for Borel sets $B \subseteq [0,1]$.


Captcha not showing odd characters like �

Question: Using magento I installed Magestore's Product Questions on my localhost and all working great. I uploaded it to live website and now doesnt work. The captcha doesnt show (http://camerakings.co.uk/lanparte-professional-kit-v2-with-7-hdmi-monitor-save-800#product-tabs-container), and when you click the link that shows the captcha (http://camerakings.co.uk/productcontact/index/imagecaptcha/) it just shows loads of these symbols � and numbers.
I spoke with magestore and they said they didnt know (where not actually very helpful at all even though provided ftp and have a lot of their plugins). I appreciate this is a plugin and I would have to paste in all the code for people to check this properly, but just wondered if people had ever experienced it with Captcha before? Or if they know why these � appear so I could investigate further.
I have tried reinstalling the plugin but no success.
Answer: The correct Content-Type header is not being sent with the response.
It is coming back as text/html which causes the browser not to render it as an image.
You may need to edit the plugin or Magento routes to add:
header('Content-type: image/png');

to that response.  Unfortunately I'm not sure how to guide you in doing that since it is a captcha plugin which should do that for you and I'm not too familiar with Magento's internals.
Comment: Thanks! I have tried this in what I think generates the captcha but it doesnt seem to work, but I will put this within some of the other files and update
Comment: I have checked and the file that generates the captcha outputs at jpeg. You can see the full text here -> https://jsfiddle.net/4ewcqcxp/ -> it says header("Content-Type: image/jpeg"); -> any idea?
Comment: Perhaps it does, but based on the response I'm getting from the actual page, it is not returning the right content type.  See screnshot in updated answer.  Also, the image is a png according to the output.


htaccess rule to protect some files independent from from protocoll and host

Question: I have an htaccess to limit the access to files to a direct click in the website. Copy the link send to another one and open it should be forbid.
My htaccess works well
RewriteCond %{HTTP_REFERER} !^http://localhost.*$ [NC]

RewriteRule ^.*$ - [NC,R=403,L]

Now I tried to make it more variable to protocol and host, but now nobody can access the files. The code should do the same as above only with variable http(s) and localhost part ...
RewriteCond %{HTTPS} =on
RewriteRule ^ - [env=proto:https]
RewriteCond %{HTTPS} !=on
RewriteRule ^ - [env=proto:http]

RewriteCond %{HTTP_REFERER} !^%{ENV:proto}://%{HTTP_HOST}.*$ [NC]
RewriteRule ^.*$ - [NC,R=403,L]

I don't see the error. Can someone help to solve this?
Answer: If you change variables to manual entries, will it work?
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^(http://|https://)(www.)?(example.com).*$ [NC]
RewriteRule ^.*$ - [NC,R=403,L]

Comment: I added a variable instead of the fixed url, but I think this could work ```RewriteEngine On

RewriteCond %{HTTP_REFERER} !^(http://|https://)(www.)?(%{HTTP_HOST}).*$ [NC]

RewriteRule ^.*$ - [NC,R=403,L]```
Comment: hmm the htaccess works only if I insert the host by hand. %{HTTP_HOST} does not work ...


How to show $(1-x)^2+(y+1)^2+(1-xy)^2\geq 2$?

Question:
How to show $(1-x)^2+(y+1)^2+(1-xy)^2\geq 2$?

I want to show that $h(x,y)=(1-x)^2+(y+1)^2+(1-xy)^2$ has a global minimum in $(1,0)$ and $(0,-1)$ where $h(1,0)=h(0,-1)=2$. How can I go about this?
Answer: Indeed we have $$h(x,y)-2=x^2 y^2 + x^2 - 2 x y - 2 x + y^2 + 2 y + 1=(y-x+1)^2+x^2y^2\geq0$$ See this interesting script for the theory behind decompositions like this.
Comment: Danke, das ist sehr gewitzt! :) Translation: Thank you, that's really slyish!
Comment: @ParabolicAlcoholic Yes, but if a point is a global minimum then the gradient at that point will be $0$. So if you check all extremal points you only need to check what happens "at the boundary" i.e. what happens when $|(x,y)|\to\infty$, as said above
Comment: But is there an alternative? I feel like this wouldn't be the way to go in a test situation
Comment: @ParabolicAlcoholic In a test you can always look for all points such that $\nabla h(x,y)=0$ and check that $h$ is positive at these points. You will also need to study what happens as $|(x,y)|\to\infty$ but this is easy here because the fourth order term will dominate
Comment: Could you elaborate please?
Comment: @ParabolicAlcoholic Please see here for the alternative method I described: https://math.stackexchange.com/questions/2058469/how-can-we-minimize-a-function-of-two-variables
Comment: Well, the second derivative test is enough to show a local maximum/minimum, not a global though


Steam no longer recognizing games in drive F

Question: I installed games onto another internal drive, and since yesterday steam seems to have forgotten that games are installed on that drive, I don't want to download all the games again, help?
Answer: I went to settings, downloads, steam library folders, and then "add library" and re-selected my old folder. All the games are back now.


creating a simple document management system

Question: I have been asked to create a simple portfolio system for architects
the architect can create a document set of popular drawings, called a portfolio.
he can select individual documents (called folios) from their hard drive and they can set meta data for these folios.
they have given me a mockup which is a wire that forces the user to select the folios from the hard drive then set meta data for the individual folios and the portfolio in another step and then manage the folios in another step (1)
This to my mind fragments the process and I want it all done in one place (2)

the client is essentially advocating a facilitated walkthrough where the folios and portfolio are created in a number of steps.
My question:
what are the advantages of the clients solution? wouldnt it be better to have one standard interface where everyting is handled in the same place without these extra creation steps?
***you should consider folios as exactly the same as a file, its just that the client uses the term folio lots and is familiar with it.
Comment: Have you put this question to the client at all? Have they provided any rationale for the way they have suggested doing it? I wonder if they are suggesting that solution because that's how it's been done in the past and not necessarily because it's really the most efficient.
Comment: dont know yet. I have deadlines so I'm pressing ahead
Answer: This looks like SharePoint where you first need to define the Document Set and its properties of metadata before you can upload or create folios. This is standard behavior, but I have trouble with the fact that they add metadata before they upload folios. It may very well be general built in document metadata such as creation date and author. However, more specific metadata, such as location and organization, may be difficult to attach to the document before it's inside the DMS. Maybe I've misinterpreted their image.
However, even if you plan to move everything to a single step, these things need to be performed. Therefore, I see no real reason putting it all in a single-step-do-it-all. I guess they repeat step 1:3 a lot where they don't have to build structure and set metadata. I think you're better off keeping their way of structuring to minimize confusion.


accdb vs mdb access database file

Question: what is the difference between these two extensions?
i need to write to an access database from a WORD file using an ADODB connection
when i create a new access database it gives me the option to make only an ACCDB file and for some reason i cannot make an MDB file
can someone please help me create an MDB file so that i am able to make an ADODB connection to it in order to write to the database/?
Answer: Look at this explanation.
Also, in Access, 'save as' will give you older versions to save as (including .mdb).
(from above link)
by using the ACCDB format, you will be able to:

Include attachments in your database. (supports BLOBs)
Use multivalued fields. (store "check all that apply" in one field)
Safe integration with SharePoint and Outlook (you can e-mail accdb and Outlook won't block them)
Encryption improvements

ACCDB databases do not support user level security or replication.

accdb vs mdb access database file


Boot custom precise live cd via ipxe

Question: I configured isc-dhcp, ipxe and tftpboot so I can boot over network via PXE. It works the ubuntu netinstall image is booting nice with pxelinux.0.
I created a custom live cd with this tutorial https://help.ubuntu.com/community/LiveCDCustomizationFromScratch. It boots nicely in an VM.
Now I wan't to connect this image to my pxe environment. The best would be to boot and append the disk via http.
There are plenty of tutorials. But I can't get the squashfs mounted. What is the best way to do this. Do I need pxelinux, do I need NFS? I'm confused about all the different bootloaders.
Help is highly appreciated. Thank you.
part of dhcpd.conf
<code>next-server 10.1.1.1;
if exists user-class and option user-class = "iPXE" {
   filename "menu.ipxe";
} else {
   filename "undionly.kpxe";
}
</code>
and menu.ipxe
<code>#!ipxe

set smartos-build 20121004T212912Z

######## MAIN MENU ###################
:start
menu Welcome
item
item --gap -- ------------------------- Operating systems ------------------------------
item cellos-storage     Boot CellOS
item smartos    Boot SmartOS (${smartos-build})
item ubuntu     Boot Ubuntu Precise 12.04 netinstall
item --gap -- ------------------------------ Utilities ---------------------------------
item shell      Enter iPXE shell
item reboot     Reboot
item
item exit       Exit (boot local disk)
choose --default cellos-storage --timeout 5000 target && goto ${target}

########## UTILITY ITEMS ####################
:shell
echo Type exit to get the back to the menu
shell
set menu-timeout 0
goto start

:reboot
reboot

:exit
exit

########## MENU ITEMS #######################

:cellos-storage
kernel /cellos/storage/cellos-latest/casper/vmlinuz
initrd /cellos/storage/cellos-latest/casper/initrd.lz
#chain http://10.1.1.1/boot/cellos/storage/cellos-latest.iso
boot

# SmartOS Root shadow is "root"
:smartos
kernel /smartos/${smartos-build}/platform/i86pc/kernel/amd64/unix -B root_shadow='$5$2HOHRnK3$NvLlm.1KQBbB0WjoP7xcIwGnllhzp2HnT.mDO7DpxYA'
initrd /smartos/${smartos-build}/platform/i86pc/amd64/boot_archive
boot
:ubuntu
kernel /ubuntu/precise/netinstall/ubuntu-installer/amd64/linux
initrd /ubuntu/precise/netinstall/ubuntu-installer/amd64/initrd.gz
boot
goto start
</code>
Answer: Did this with Linux Mint 13, but should be the same with Ubuntu 12.04.  I used mintconstructor to customize my live-dvd but should work LiveCDCustomizationFromScratch.
I was able to configure net booting from a live-dvd using only iPXE (no pxelinux).
To do so, I configured a http server (with apache) to publish content in /var/www.  It's necessary because the initrd and vmlinuz need to be accessible through http.
I took the initrd.lz and vmlinuz from the live-dvd and put it into /var/www
Took all the files in /casper (from live-dvd) and put it in /var/www/casper.
On your web server, publish also an NFS share of /var/www so the files are also accessible through NFS.  That is necessary for accessing the squashfs (casper folder) through the network (doesn't seem to work through http).
Here's my /etc/exports (NFS)
<code>/var/www *(ro,async)
</code>
Your iPXE script should look like this (replace the IP accordingly) :
<code>#!ipxe
initrd http://10.54.9.43/initrd.lz
chain http://10.54.9.43/vmlinuz boot=casper netboot=nfs nfsroot=10.54.9.43:/var/www/ initrd=initrd.lz
</code>
That will load the kernel and initrd through http, and the squashfs through NFS...
About the DHCP part, I'm using a Windows Server DHCP ... so I could not help you. Follow the documentation of iPXE.  For others, here's what I did : I configured a TFTP server on the same server (linux).  I configured option 66 to the IP of that server (on the DHCP server).  I put undionly.kpxe (iPXE) in the TFTP folder of my server to chainload iPXE (check iPXE doc). I configured option 67 as specified in the iPXE doc to prevent an infinite loop (because of the chainload).
All this was a bit diffult for me to find out because there's not much documentation about this on the web.

Boot custom precise live cd via ipxe


When can an arbitrary function be put into this form?

Question: A problem I've been trying to address but not been able to get very far with is to devise a method to check whether or not some function $q(x)$ can be written like
$$
q(x) = \varphi^{-1}[1+\varphi(x)].
$$
Or, put another way, "given a function $q(x)$, how do we decide whether or not there exists a solution $\varphi(x)$ to $\varphi\circ q - \varphi = 1$?".
Yet another way to recast the problem is, "for a given $q(x)$, how do we know whether or not one can find a function $f$ so that $e^{f(x)\frac{d}{dx}}x = q(x)$?".
At the very least, $q$ must be invertible, which is apparent from it's definition ($q^{-1}(x) = \varphi^{-1}[\varphi(x) - 1]$). As a matter of practicality, one can make definitions for $\varphi$ without any loss of generality to arrive at other equivalent forms for $q$, for example $\varphi\rightarrow\ln\sigma\Rightarrow q(x)\rightarrow\sigma^{-1}[e\sigma(x)]$.
Actually finding $\varphi$ for a given $q$ is something I've been able to do a few times via infinite matrices (with much sweat and tears), and any information on that process would be fun for me to hear about too. I'm sure there are already far more general existence and uniqueness theorems that answer my question...I can recall coming across some that consider similar things, at the very least, but I still have trouble absorbing most mathematical literature at this point in my education. Any pointers in the right direction, i.e. things I could be considering, any meaningful discussion is greatly appreciated.
Answer: Actually, I had a thought. While this is definitely not the whole story, it certainly seems true that if
$$
q: I \longrightarrow\, I
$$
for some $I\in\mathbb{R}$, and we specify some point $\phi(x_0) = \phi_0,\,x_0\in I$, then we have some type of solution on $I$. This was easy to see after I tried a super brute-force method of a table of values. If by dotting the $x$-axis with each pair of points $(x,q(x))$ on a plot of $\phi(x)$, one fills up the entire interval $I$:
$$\forall x'\in I,\,\,q(x')\in I$$
Then we have a corresponding value for $\phi$ at each point $x'$ in $I$. There is lots of room for trouble, though, i.e. if $q$ has a fixed point. If, though for each $x'\in I$ there is a unique $q(x')$, so that $q$ is one-to-one on $I$, then it is possible to construct $\phi$ by starting with $\phi(q(x_0)) = 1 + \phi(x_0) \equiv 1 + \phi_0$, and then plugging in $\phi(q(q(x_0)))$, etc. for each pair to get a resulting pair $(\phi(q(x_i)),\phi(x_i) + 1)$ to plot on the $\phi$-axis. That is,
$$
(q)^n(x_0) = \phi^{-1}(n+\phi_0)
$$
Where $(q)^n$ is $n$-fold composition of $q$, i.e. $(q)^3(y) = q(q(q(y)))$.
We can sort of say, then
$$
\phi^{-1}(x) \sim (q)^{x-\phi_0}(x_0)
$$
This actually holds for a few $q$, and gives correct answers when verifying with $q(x) = \phi^{-1}(1+\phi(x))$ or equivalently $e^{\partial_\phi}x = q(x)$. There is the issue of the set $\{(q)^n(x_0), \forall n \in \mathbb{Z}\}$ covering the interval $I$ in an optimal, 'disjoint' fashion, which worries me when it comes to proofs, but as far as actually doing what I want to do, the formula $(q)^n(x_0) = \phi^{-1}(n+\phi_0)$ works just fine when one can analytically expand $n$ to real values, i.e. $(q)^n(x_0) \equiv f(x_0,n)$.
So, then, I humbly submit a (certainly incomplete, if not incorrect altogether) first guess of some conditions on $q$:
The equation
$$
(\phi\circ q)(x) - \phi(x) = 1
$$
Has a solution, $\phi(x)$, for all $x \in I$, if $q$ is one-to-one on $I$, and has no fixed points on $I$ (perhaps no attractive fixed points near $I$?).


Using Python to translate Excel --> Dictionary --> Excel

Question: I would like to create a dictionary from an excel file, which I can use to write to a new excel file.
For example, if data is organized as follows:
Subject Date     Measurement
134     1/20/09  22
134     2/21/10  25
134     2/22/13  34
134     1/5/15   33
211     2/23/00  34
211     3/5/09   33

I would like to create a dictionary which outputs:
{134: {1/20/09: 22, 2/21/10: 25, etc}, 211: {2/23/00:34, 3/05/09:33}}

From this dictionary, I would like to write a new cvs or excel which organizes data as follows:
subject average measurement
134     28.5
211     33.5

Answer: It's a bit old now but it may interest someone. This code works:
# you need pandas library in my code but it's not the only possibility
import pandas as pd
from dateutil.parser import parse # for the date format

# your path
path_file_xl = "your\path\to\your\file.xlsx"
# Create a DataFrame (DF)
df = pd.read_excel(path_file_xl)

# Create the dictionnay
dict_data = {} # create an empty dictionary
for index, row in df.iterrows():
    # If the subject not already in dict_data
    if int(row[0]) not in dict_data.keys():
        dict_data[int(row[0])] = {} # create the key
    # Add the new entry in the the dictionary linked to the subject
    dict_data[int(row[0])].update({ parse(row[1]): float(row[2]) })

# Create the table with average
table = [] #empty list to append data
for subject in dict_data.keys(): # for each subject in your dict_data
    # Calculate the average sum divided by length
    average_subject = sum(dict_data[subject].values())/len(dict_data[subject])
    table.append([subject, average_subject]) #append in the table

# create a DF with average data
df_out = pd.DataFrame(table)
# Rename and sort values
df_out = df_out.rename(columns={0: 'Subject', 1: 'average measurement'}).sort_values(['Subject'])
# write into a csv without the index of the DF
path_file_csv = "your\path\to\your\file.csv"
df_out.to_csv(path_file_csv, index = False)

There is probably another way without table feeding directly a pandas DF.