Task Scheduler only killing cmd.exe but not its child processes

Question: Our customer has some Windows 2003 servers running batch jobs activated by Task Scheduler. The actual programs performing the work are custom .exe processes, and they are aggregated into .cmd scripts so that they get launched together by Task Scheduler when the scheduled interval comes by. The lines within the cmd scripts may or may not use the Call command to launch the separate .exe programs.
In this setup, Task Scheduler is effectively monitoring cmd.exe, and when using Process Explorer, one can observe that the child .exe processes are parked under the cmd.exe process tree. However, when Task Scheduler kills cmd.exe due to exceeding the permissible time limit, the child .exe processes may not be killed along with their parent and become orphaned. Those processes remain stalled indefinitely. Due to the state of the process threads shown in Process Explorer, i suspect those processes end up in error and popped up a .NET debugger dialog box (these are .NET applications) which cannot be seen since the batch job user is a separate user account.
Initially when i was investigating this behaviour on my Windows XP workstation, I observed that child .exe processes launch from my test .cmd script do get killed together with the cmd.exe when Task Scheduler decides time is up. There was no way I could orphan the child processes.
Based on a hunch, i eventually moved over to a Windows 2003 machine to test this. Similarly, the child processes to get terminated like those in my workstation. My second step was then to use another user account to run the scheduled task. This time round, cmd.exe gets killed after the time limit is exceeded, but the child processes remain standing, just like what my customer observed in their production servers.
If i preemptively logon that batch user account (which just so happened to be another admin account) to claim a desktop session, any error or info pop-ups from my test .exe programs would be routed and rendered on that desktop, allowing me to see the actual user output. If i only logon after the scheduled task had been invoked, the desktop session will not "reclaim" the existing processes' windows; they stay hidden forever.
My question is, what condition(s) am I missing here that can cause Task Scheduler not to wipe out the child processes under a cmd.exe? What is special about using another account that would induce this behaviour, but not when using my current administrator account to run the schedued task?
Comment: We have the same problem. Did you ever get this solved?
Comment: Nope ..... T__T
Answer: Try using "Taskkill /T" on the command line. (/T = "…Terminates the specified process and any child processes which were started by it…")
If you have multiple processes running (we often have 5 or more "powershell.exe" running) then add the "Command Line" column to the "Details" tab in Task Manager. That should make it clear which Process ID is the one you want to kill off
Answer: Processes are independant in Windows - Killing a parent process will not automatically terminate a child process.
Comment: If that is the case, why would Task scheduler ending cmd.exe also end the other .exe processes in my test cases?
Comment: Why not and how does one end a task such that the child processes are also killed?
Comment: See @Warren-Stevens answer
Answer: If you think it is due to a debugger message popping up, have you tried wrapping the code in a try{}catch{} block and logging the error?
Otherwise, maybe what you could do is have the processes write the output of WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent())
I suspect that the children are somehow escalating their priveledge level to Administrator and then can't be killed with the parent.
To test this without modifying code, you could write another scheduled task that tries to kill the other processes using taskkill. This scheduled task should be run as the Administrator. If that works, then it looks like it is a security issue.
Comment: those programs were not written by us and we are not allowed to modify them unless there are serious problems that call for fixing them.

my question here is not about .NET application development. It is about the Task Scheduler and process tree control.
Comment: If I run the scheduled task as my own user account, which is administrator, they can be killed.
Comment: Right, because your application then starts in the right security context. But I suspect the other apps escalate their security context, making it impossible for non-administrator accounts to then kill them.
Comment: I updated my answer with an alternate approach.
Comment: But when i tested this using another administrator account, the behaviour surfaces.
Comment: Hm...then I'm out of ideas.
Answer: How about using the pskill utility, which is part of the SysInternals suite. This program can kill processes by name. I would add a scheduled task, which will run a few minutes after you expect the processes to be finished, that will run pskill to terminate them.
PSKill can also run under user credentials you supply on the command line.
Comment: I am not asking about killing processes. I am asking about what causes a child process to get orphaned or not after the parent cmd.exe is terminated.
Answer: I don't know that it will solve your problem, but if it is related to the popup boxes (and it might be - the app is in a faulted state, and suspended while the non-existent user decides what to do about it).
Take a look at http://blogs.msdn.com/shawnfa/archive/2004/07/15/184490.aspx, and see if you can't get rid of those boxes...
Comment: While that is interesting note, I am asking about what causes a child process to get orphaned or not after the parent cmd.exe is terminated.


How can reordering the linked libraries fix multiple definitions error?

Question: I faced a situation where different order of linking librdkafka and the Pulsar C++ client does matter, because both of them include their version of LZ4 compression. The linking fails because of multiple definitions of LZ4 functions (both librdkafka and Pulsar have the same names for those functions). I checked the static libraries, but I couldn't find anything suspicious, why it works in one order and doesn't in the another. Because it is hard to provide a minimal working example with those big libraries, I tried to reproduce the same situation, and I was able to do so. I created a small project where the linking order matters.
libA.hpp:
#pragma once

void NotClashingFunctionA();
void ClashingFunction();

libA.cpp:
#include "libB.hpp"

#include <iostream>

void NotClashingFunctionA() {
    std::cout << "Not clashing function A\n";
}

void ClashingFunction() {
    std::cout << "Clashing function A\n";
}

libB.hpp:
#pragma once

void NotClashingFunctionB();

libB.cpp:
#include "libB.hpp"

#include <iostream>

void NotClashingFunctionB() {
    std::cout << "Not clashing function B\n";
}

libBSub.hpp:
#pragma once

void ClashingFunction();

libBSub.cpp:
#include "libBSub.hpp"

#include <iostream>

void ClashingFunction() {
    std::cout << "Clashing function B\n";
}

main.cpp:
#include "libA.hpp"
#include "libB.hpp"
#include "libBSub.hpp"

int main() {
    NotClashingFunctionA();
    NotClashingFunctionB();
    ClashingFunction();
    return 0;
}

CMakeLists.txt:
project(clashing)

add_library(A STATIC libA.cpp)

add_library(B STATIC libB.cpp libBSub.cpp)

add_executable(working main.cpp)
target_link_libraries(working A B)

add_executable(failing main.cpp)
target_link_libraries(failing B A)

From the logs I can clearly see that working just links fine:
clang++ -g -rdynamic CMakeFiles/working.dir/main.cpp.o -o working  libA.a libB.a
make[3]: Leaving directory 'build'
[100%] Built target working

But failing fails to link:
clang++ -g -rdynamic CMakeFiles/failing.dir/main.cpp.o -o failing  libB.a libA.a
ld: libA.a(libA.cpp.o): in function `ClashingFunction()':
libA.cpp:9: multiple definition of `ClashingFunction()'; libB.a(libBSub.cpp.o):libBSub.cpp:5: first defined here
clang-12: error: linker command failed with exit code 1 (use -v to see invocation)

I removed the common prefixes to make the logs more readable.
As you can see the only difference between the two is the linking order A and B. I don't know why it works in A B order, and not B A order.
If you cannot explain it in details, helping keywords are also very appreciated, because I have absolutely no idea why it is happening.
Comment: The code breaks the One-Definition-Rule (ODR) - no diagnostic required - and is an example of Undefined Behaviour - see https://en.cppreference.com/w/cpp/language/definition  specifically _"One and only one definition of every non-inline function or variable that is odr-used is required to appear in the entire program ...The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined...."_
Comment: Thanks! To be honest I haven't faced a situation where the violation of ODR doesn't ended up in a linker error, therefore I was thinking that it might be actually valid because of some edge cases. Now I checked, and GCC behaves in the same way as Clang, and this makes me curious. I know it is still UB, but it seems both Clang and GCC implemented this in the same way. But thats a different topic!
Comment: since you static library is copied into you program it will clash in linking so I rppose you add some namespace to your libraries .
Comment: Yes, it was clear. The question was about why it is working in one order.
Answer: To understand why, read this (earlier) post or this (nicer) one.
To make a concrete example:

suppose main.o defines main(), fn(), and references a() and b().
libA.a contains a.o which defines a()
libB.a contains b.o which defines b(), and also a1.o which defines a() and fn().

Now, if you link with gcc main.o -lA -lB, the link will succeed (a.o from libA.a and b.o from libB.a will be selected into the link, and no symbol conflicts will arise. Notably, a1.o from libB.a will not be selected into the link).
But if you link with gcc main.o -lB -lA, then fn() will be multiply defined (because both a1.o and b.o from libB.a will be selected into the link, but the definition of fn() in a1.o will be in conflict with the definition of fn() in main.o).
Comment: Thanks for the nice explanation and links, I really think I understood the whole situation based on your answer!


R 'effects' plot - dichotomizing variable with 'xlevels' with cut-off-values

Question: lets say I want to dichotomize a previously continuous variable (e.g. Age) of a mixed-effect model (lme4) into two levels directly in the effects function in R (Age 8-12 and Age 13-16).
I know with xlevels=list(Age=2) I could get my 2 levels right away, but I do not find any information on which rule this classification is based.
Here there is my command:
effect("Age",model,xlevels=list(Age=c(12))

Let's say I set 12 to a cutoff (12 still belonging to the lower level), this doesn't work, because two input values are needed.
Answer: I think you can't dichotomoize directly in the effects function, because the xlevels-argument considers input of length one as amount of equally spaced levels, see ?effect:

If xlevels=n is an integer, then each numeric predictor is represented by n equally spaced levels

Thus, xlevels=list(Age=2) will simply try to find two values of your Age-variable that are "equally spaced" (which most likely will be the minimum and maximum value of Age).
If you specify more than one value, e.g. xlevels=list(Age=c(2, 4, 6, 8), then the effect-function will return the predicted values for Age = 2, Age = 4, Age = 6 and Age = 8.
Maybe you could get the mean from your two ranges, 8-12 = 10 and 13-16 = 14.5, and use these values for the xlevels-argument (xlevels=list(Age=c(10, 14.5)). I don't know if this comes close to dichotomizing...


How do a change a dynamic localhost port?

Question: Mismatch
I am currently testing my website on a local webserver.
The localhost port localhost:[port] keeps changing everytime I run the python3 manage.py unittest.
As a result of the localhost:port changing on every test, it cannot match the url [localhost:'port'] with the redirect url that I have entered in the Oauth credentials.
How am I able to run my unittests and have the browser use a certain port every time?
I'm currently following the taskbuster django tutorial
http://www.marinamele.com/user-authentication-with-google-using-django-allauth taskbuster
If you scroll down on that page to the following section
"indicating that the redirect URI at http://localhost:8081 is not valid. This is because we registered a different url, http://127.0.0.1:8000, and not the one that is used by tests."
Then my problem will become apparent.
To summarise
1.I've registed the callback url to be http:127.0.0.1:8081

Everytime I run the unit test, the web server runs on the follwoing 'http:127.0.0.1:53000' or a variant of that number.

How do I get the test to run on a designated port.
Comment: Using a LiveServerTestCase might help https://stackoverflow.com/questions/47887156/setting-liveserver-port-when-running-tests-in-django
Answer: SOLUTION:
After some research and asking some Django Users -
The solution was to add below the test class, port = 8010.
<code>class TestGoogleLogin(StaticLiveServerTestCase):

    fixtures = ['allauth_fixture']
    port = 8010

    def setUp(self):
        "CODE"
</code>


Tokenizing a expression string in C#

Question: I have a calculation formula string of the form
 string formula = w_tb + Min(d_3,a_x) * Pow(x,2)

In the above example w_tb, d_3, a_x, x are variables. I am able to find the list of variables in the formula by splitting the strings using the operands as the delimiter.
But in order to assign the values to the variables (value from the database), my first approach was to replace the variable name with the value of the variable from the database. But that would result in replacing even a substring of the expression string with the value. Eg : If the variable x is replaced with the value 1,2 in the expression string a_x will be replaced to a_1,2 which is not the required result.
I have the list of variables and and the complete list of delimiters(operators).
What I am trying to achieve?
I am trying to get the following list from the expression string
List<string>() {"w_tb","+","Min","(","d_3",",","a_x",")","*","Pow","(","x",",","2",")"}

Is there a way I could achieve the task.
I have already tried the solution mentioned in this answer. But the tokenizer I am having is a string.
Answer: What you are trying to do is called Parsing, frequently used by compilers.
You can define a simple grammar for your expression and let a parser-generator generate the parser code for you. It allows you to define syntax errors and gives the full token list like the one you want. A very good example in Antlr. Have a look http://www.antlr.org/
Comment: @Rob: I will try writing a grammar; but probably that is going to result in another question as I am not familiar writing grammars, but first i will have to search how to write a simple grammar. Thanks :)
Comment: I am unable to think of a grammar that would suffice my need. :(. But in no way i am looking fro someone to write a grammar for me. but an approach to do so.
Comment: The answer you linked in your question looks simple and good. You can use it.
Comment: yes. But it applies only if the delimiter is a char array. In that case i loop through all the characters in the string and achieve my intended result. in my case the delimiter is a string array. I could do this again by looping through all characters , appending it as a string and searching for delimiter substring in it and adding it to string after some string manipulations. but it isnt as convenient as it should be. and the chances of failure are really high.
Comment: @Vini You would simply need a tokenizer. It would break up the expression into singular tokens, which you can then properly replace and re-combine. For example, your expression might have the tokens `w_tb, Min, d_3, a_x, Pow, x, 2` (of course, `Min` and `Pow` might be classified as 'function-tokens' which can be excluded from the replace process)
Comment: Note that Antlr (as Kilanny recommended) will provide this functionality for you. The grammar file I would imagine would be extremely simple (almost to the point of `token: [a-z]+(0-9)*` with a few edge cases for method calls, etc.
Comment: @Vini If you need a hand getting started, I've setup a chat with a simple grammar that get's you most of the way: http://chat.stackoverflow.com/rooms/info/101258/room-for-rob-and-vini
Comment: @rob : thanks a lot for your help :) i will look into it.
Comment: @Vini If you've got a moment, jump into the chat room so I can run you through what's needed, the simple grammar I've written there at least will parse your current input :)
Answer: So i could find an approach to achieve my task. I have a list of all available operators and a list of all available operands. The list of operands can be obtained by splitting the formula string based on the operator string.
var Operatorlist = new string[] { "Min", "Max", "Abs", "Pow", "+", "-", "*", "/", "(", ")", "²", "³", "Length", " ", "\r", "\n", ",", "[", "]", "Sqrt", "Cubrt", "^" };
string[] formulaSplit = formula.Split(Operatorlist,StringSplitOption.None);

Now to parse the formula to get a list of operands and operators
string sb="";
var formlist = new list<string>();
foreach(var c in calc.CalculationFormula)
{
    sb = sb + c;
    if(delimstringlist.Contains(sb))
    {
        formlist.Add(sb);
        sb = "";
    }
    else if(formulaSplit.Contains(sb))
    {
        formlist.Add(sb);
        sb = "";
    }

}

May not be so efficient, but will surely do the task.

Tokenizing a expression string in C#


Should you include time as a continuous predictor when estimating incidence or prevalence?

Question: Suppose one has a time series of disease counts and populations (at risk, total etc.) or, equivalently, binary events of disease status.
Then suppose one wanted to present estimates of incidence or prevalence over the time series.
One could calculate separate estimates for each year. I believe this would be the same as a regression model with dummy variables for each year. Or is it better to fit time (e.g. year) as a continuous explanatory variable (linear, polynomial, spline etc.)? In the former case, the estimate at each year is not influenced by estimates at other time points. In the latter, I think the estimate at each year would be "adjusted" by the trend. Im thinking that this would provide a better estimate at a given time point, since it's taking other time points into account (more so the closer in time).
I'm not sure if I'm missing something obvious, but would appreciate some guidance on whether my thoughts make any sense and which approach might be better.
Answer: Your intuition is correct.  Time is continuous and needs to be analyzed as such.  But also think about decomposing time into long-term smooth nonlinear trends and seasonal variation.  An example is here.  A spline is used for the long-term trend and a harmonic series for seasonal effects.
Comment: If the time period defined for calculating incidence or prevalence itself is one (WHOLE) year, would modelling time as a continuous term be contradictory since this would in theory allow model predictions at e.g. 2.5, 3.7 years etc. Prevalence and incidence are only defined here for whole year periods and not decimals / periods between years.
Comment: You can add long-term trends to short-term trends, so getting a prediction for a specific day of a specific year should not be a a problem if the model fits OK.
Comment: If one does not have day or month information they must specify a time within the year to regress on e.g. year mid point, end of year. I think this would be problematic. Also, would this not change the time unit for prevalence or incidence to per day? This is not what is required...rather we need "per year".


How to disable ETag headers in Tomcat

Question: Tomcat seems to send an ETag header with each response by default. I'd like to disable these for reasons outlined here. I know I can strip them out in my Apache configuration, but is there any way to disable them on the Tomcat side?
Answer: No way disable out of the box. But ETags are set by the DefaultServlet via request.setHeader(). So an easy workaround to disable them is to create a filter for DefaultServlet which swallows the tag. For example:

void doFilter(ServletRequest request, ServletRequest reponse) {
  chain.doFilter(request, new HttpServletResponseWrapper(response) {
      public void setHeader(String name, String value) {
          if (!"etag".equalsIgnoreCase(name)) {
              super.setHeader(name, value);
          }
      }
  });
}

And in web.xml:

  <filter>
    <filter-name>noetag</filter-name>
    <filter-class>foo.NoEtagFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>noetag</filter-name>
    <servlet-name>default</servlet-name>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
  </filter-mapping>

How to disable ETag headers in Tomcat


Google Mock: Return() a list of values

Question: Via Google Mock's Return() you can return what value will be returned once a mocked function is called. However, if a certain function is expected to be called many times, and each time you would like it to return a different predefined value.
For example:
EXPECT_CALL(mocked_object, aCertainFunction (_,_))
    .Times(200);

How do you make aCertainFunction each time return an incrementing integer?
Answer: Use sequences:
using ::testing::Sequence;

Sequence s1;
for (int i=1; i<=20; i++) {
    EXPECT_CALL(mocked_object, aCertainFunction (_,_))
        .InSequence(s1)
        .WillOnce(Return(i));
}

Answer: Use functors, as explained here.

Something like this :
int aCertainFunction( float, int );

struct Funct
{
  Funct() : i(0){}

  int mockFunc( float, int )
  {
    return i++;
  }
  int i;
};

// in the test
Funct functor;
EXPECT_CALL(mocked_object, aCertainFunction (_,_))
    .WillRepeatedly( Invoke( &functor, &Funct::mockFunc ) )
    .Times( 200 );

Answer: You might like this solution, which hides implementation details in the mock class.
In the mock class, add:
using testing::_;
using testing::Return;

ACTION_P(IncrementAndReturnPointee, p) { return (*p)++; }

class MockObject: public Object {
public:
    MOCK_METHOD(...)
    ...

    void useAutoIncrement(int initial_ret_value) {
        ret_value = initial_ret_value - 1;

        ON_CALL(*this, aCertainFunction (_,_))
             .WillByDefault(IncrementAndReturnPointee(&ret_value));
    }

private:
    ret_value;
}

In the test, call:
TEST_F(TestSuite, TestScenario) {
    MockObject mocked_object;
    mocked_object.useAutoIncrement(0);

    // the rest of the test scenario
    ...
}

Google Mock: Return() a list of values


Can we define the cartesian product by a universal property without involving (not yet defined) functions

Question: I know that set theory provides a definition of ordered tuples:
\begin{equation}
(x,y):=\big\{\{x\},\{x,y\}\big\}
\end{equation}
However, I think that this is just one of many possible definitions - for example, my guess would be that
\begin{equation}
(x,y):=\big\{\{x,y\},\{y\}\big\}
\end{equation}
is a "good" alternative definition.
This suggests that it should be possible to define the cartesian product by a universal property. This has already been done (e.g. here), but it involves functions, which we can only introduce after defining the cartesian product.
Comment: The (categorial) product involves an object and some morphisms, yes. Depending on what object you choose as a representative of this product (it is unique only up to isomorphism -if I remembeer correctly the isomorphism is also unique) you will get some family of maps. These maps are abstractions of the projections from the cartesian product, so this maps just tell you how to project the product onto each of its factors. Usually, given a construction of the product object, the projections are clear, but if they're not, they should be specified.
Answer: A universal property characterizes an object up to a unique isomorphism, but it does not say that such an object exists. You still have to make some kind of construction to show that it does. What the universal property ensures is that all the different constructions will get you the same object (up to a unique isomorphism) so that, usually, you do not worry about the construction once you have done it once. But you still need to do it, one way or another ! Except of course if your category is defined by a set of axioms saying that such an object has to exist. But the usual axioms of set theory do not say that products need to exist, so you need to choose a way to construct them.
Comment: I understand, but can't we formulate a universal property and prove that the usual definition of the cartesian product has that property?
Comment: For example, my guess would be that if we are able to formulate such a universal property, the definition $(x,y):=\big\{\{x,y\},\{y\}\big\}$ would be a valid alternative definition.
Comment: There is such a universal property (that is, the set of such couples is a product in the category of sets) which does exactly that. I'm not entirely sure of what you are looking for there.
Comment: If I understand properly, you would like to state the universal property before doing the construction ? The problem is that from the ZF axioms, you don't get a category automatically, and I can't see how you could define functions from these axioms without having already constructed cartesian products. Again, there may be axioms better suited to get a category before constructing products, or even axioms assuming the existence of products, but the ZF axioms are not meant to do this.
Comment: You understand properly, that's exactly what I would like to do! I am an undergraduate student (currently writing my bachelor thesis) and unfortunately, we have never talked about categories and I'm not satisfied with the information I found online...
Comment: Anyways, as far as I understand, you think that we need another system of axioms - possibly with sets $\textbf{and}$ functions as [primitive notions](https://en.wikipedia.org/wiki/Primitive_notion#:~:text=In%20mathematics%2C%20logic%2C%20philosophy%2C%20and%20formal%20systems%2C%20a,relations%20between%20primitive%20notions%20are%20restricted%20by%20axioms.) - as our foundation, right?
Comment: I do not think we need another system of axioms (ZFC is fine), but I think you would need another system of axioms if you want to do what you suggest. Maybe something like the way topos theory is looking at the category of sets. But I am not convinced this is really worth the effort (at least if your question is your only motivation).
Comment: However, if you want to read about category theory (which is totally worth the investment), Simmons' Introduction to Category Theory is really nice, starting from scratch. McLane's book is a bit more tough, but a good reference also.
Comment: Thank you very much for the references!
Comment: Here's what I currently consider the solution to my "problem": The cartesian product $X\times Y$ can be regarded as a tool to define functions from $X$ to $Y$ and after having introduced functions, we can define a product of $X$ and $Y$ by the universal property I mentioned in my question. It then turns out that the the cartesian products $X\times Y$ and $Y\times X$ - together with the usual projections - are both products of $X$ and $Y$ (according to the universal property, a product of $X$ and $Y$ is also a product of $Y$ and $X$).
Comment: Ok, and this is the usual way of doing things. Namely, you construct your object first, then you show that it satisfies a universal property, and then any other object satisfying this universal property is isomorphic to it (and there is a unique isomorphism commuting with the universal maps - here, the projections). For instance, indeed, $X \times Y \cong Y \times X$ (which is true in any category with products,  then).
Comment: What I'm about to say is probably obvious, but I want to be sure there hasn't been a misunderstanding: What bothered me we was the impression that we define the cartesian product and afterwards **re-define**  it by a universal property, which implicitly involves the priorly made definition via the use of functions. However, I don't think this is correct: The cartesian product is always the set of ordered pairs defined in my question, while a product (notice the omission of "cartesian") is only defined up to an isomorphism.
Comment: When a proof involves a product, it should suffice to invoke its universal property. I guess it's easier to work with ordered pairs (tuples), but especially in physics, I think it's conceptually important to keep this distinction in mind.
Comment: As I said, a universal property is not a definition. But it is a characterization, up to a unique isomorphism. And usually, if you have a canonical isomorphism (in the category of sets, a canonical bijection) between two objects, you can consider that they are the same (in our particular situation, all of these objects are "the" (cartesian) product). So making this distinction does not really matter, in fact. Well, you can keep it in mind if you prefer, but you will see that it is not that useful.
Comment: So in fact you can use the universal property and use ordered pairs, both are equally good. At least if you take products of sets ;  products exist in many categories where ordered pairs don't make sense.


Send pre-fx signal of a track to the return track in Ableton

Question: Is there a way in Ableton to send the unaltered signal of a particular track to a return track? By unaltered I mean the signal before the insert effects kick in. I have a vocal which I would like to filter in and out, but would still like to hear the unfiltered delay on my return track, even when the vocal is completely inaudible due to the low pass filter insert.
I tried fiddling around with "pre" and "post" in my Master channel for the return track of interest, but this still kicks in post-effect and only works when my volume fader is all the way down.
Answer: Create an extra helper audio track, and configure it like this:

Set the Audio From i.e. input to be your original track that has the effects.
Set the Audio From as Pre FX.
Set Audio To to Sends Only, so that it doesn't contribute to the main mix.
In Sends, dial in the amount of effect send you want.
Switch Monitor to In so that it constantly just channels audio from its input to its output.

Like so:


What counts as a foot fault when serving and when attacking from the back court?

Question: In volleyball, what exactly is considered a foot fault when
a) serving?
b) attacking from the back court part (i.e. by a player from the back row)?
Three possible options come to mind:
* players are not allowed to even touch the line.
* players are allowed to touch the line but cannot cross it.
* players can cross the line, but only partially (i.e. with just a part of their
feet) - just as the case is at the central line with regular attacks.
Answer: Your first option is correct. FIVB Official Volleyball Rules 2013–2016, article 12.4.3:

At the moment of the service hit or take-off for a jump service, the server must not touch the court (the end line included) or the floor outside the service zone.
  After the hit, he/she may step or land outside the service zone, or inside the court.

Note that in beach volleyball, there is an additional statement that the server's foot may not even go under the end line.
Comment: Is this true not only for serving but also for attacking by players from the back row?
Comment: Indeed. "188.8.131.52 at his/her take-off, the player's foot (feet) must neither have touched nor crossed over the attack line" (and "after his/her hit, the player may land within the front zone").


Reconnect Windows Network Drive after network connection has been established

Question: User uses a piece of software (simple database and front end app) that connects to a database stored on another workstation, by way of mapped drive. This mode of access is supported by the software vendor and is not a hack in any way.
The problem comes because the 'client' the user uses is a laptop, hence connects to the network via wireless. When the user logs in, the laptop connects to wireless, but the mapped drive hasn't been 'reconnected', so to speak. I don't know the official terminology for this, but suffice it to say that it looks like this:

With the big red X over the drive. Just like the drive in the photo, I can 'double click' the drive in My Computer, and connect to the drive. However, I'd like to avoid submitting that as a 'fix' to the user, as it really isn't a fix. The drive must be 'connected to' before opening the program, or the program won't run.
I thought about using the 'Always Wait for Network at Logon' Group Policy, but I don't know if that applies to wireless (especially since network profiles are user based unless they're added to the group policy), and also since it could cause problems if the laptop isn't in range of a known wireless network.
I tried going into Powershell just now and navigating to the K: drive (see screenshot above) in hopes that it would be smart enough to reconnect the drive, but it didn't work.
Looking for suggestions and/or discrete workarounds, preferably powershell based, a one time configuration change, or something similar. If all else fails I might have to use net use and replace the current mapping, but that involves saving the credentials for the network drive in a script :-(
Comment: Check here mate: http://support.microsoft.com/kb/297684
Comment: I solved this in the past by using a startup script that cd'ed to the directory after the network connected but before the user had gotten the program loaded up. I'm hoping someone else has a far more elegant solution...
Comment: Can this application use a UNC path instead?
Comment: I assume the user is on a domain because you're using GPO - that said, if you use a logon script you don't need to store credentials within the script
Comment: @DKNUCKLES this isn't a domain, I was going to use local gpo. I'll need to store creds since 1) it isn't a domain and 2) the login account is different on the machine storing the database.
Comment: @MarkPorter I was thinking about that, but that information has to be supplied @ installation, so if I can avoid a reinstall.....
Comment: @MDMoore313 - did the KB article help?
Comment: @TheCleaner Not quite, I will be posting my answer soon however.
Answer: I used a powershell script that uses a timed while loop to check if the user has connected to the wireless SSID where the database lives, and if so then either delete and recreate the mapped network drive or cd into it, I cannot remember, but it's been stable all this time and it is the main business application so it's used everyday.
Comment: Apparently _soon_ in my book means 2 3/4 years later, but I was waiting until I saw the client again to actually post the script I used to solve the problem, in my haste I didn't make a backup so hopefully she doesn't lose her laptop before I can make a copy.


Acumatica using images in replace of CheckBox

Question: I want to be able to click on the rendered button and have the new value save.
In customization Project there are values for images for when the checkbox is pushed.

Currently, the Checkbox rendered as a button correctly displays the correct image for the value in the project but when the button is clicked and the user saves the project the value and button reverts to its original state.
GIF: http://g.recordit.co/vbe99tL7Q7.gif
If I remove the Render Style, the checkbox works normally in the project without displaying any images.
Is there something im missing in Customization?
Answer: Seems to be working with AutoCallBack defined for checkBox. AutoCallBack is calling an action from BLC every time a user clicks on the button representing checkbox.
Checkbox definition in Aspx:
<px:PXCheckBox runat="server" ID="chkUsrBoolField" CallbackUpdatable="True" DataField="UsrBoolField" RenderStyle="Button" AlignLeft="True" >
    <AutoCallBack Command="CheckFlag" Target="ds" />
    <UncheckImages Normal="main@Fail" />
    <CheckImages Normal="main@Success" />
</px:PXCheckBox>

PMProject DAC and ProjectEntryExt BLC extensions:
public class PMProjectExt : PXCacheExtension<PMProject>
{
    public abstract class usrBoolField : IBqlField { }

    [PXDBBool]
    public bool? UsrBoolField { get; set; }
}

public class ProjectEntryExt : PXGraphExtension<ProjectEntry>
{
    public PXAction<PMProject> CheckFlag;
    [PXButton]
    [PXUIField(Visible = false)]
    protected void checkFlag()
    {
        var proj = Base.Project.Current;
        proj.GetExtension<PMProjectExt>().UsrBoolField =
            !proj.GetExtension<PMProjectExt>().UsrBoolField.GetValueOrDefault();
        Base.Project.Update(proj);
    }
}


Clustering similar words in different sets

Question: Suppose I have $N$ sets as follow:
$$S_1 = \{a_1,a_2,\cdots,a_n\}$$
$$S_2 = \{b_1,b_2,\cdots,b_n\}$$
$$S_3 = \{c_1,c_2,\cdots,c_n\}$$
$$\vdots$$
elements of each set (i.e., $a_n$, $b_n$, $c_n$ and etc) are words. I want to go through all the sets and cluster similar words. So we may have $M$ number of clusters ($C$) with different lengths, for example:
$$C_1 = \{a_1,b_5,c_2,\cdots\}$$
$$C_2 = \{c_1,a_2\}$$
My idea was to take cosine similarity between all words on all sets, but if you have too many words and many sets this will not be a good idea. I wonder if there is a clustering method for such scenario?
One other idea might be just to flatten the sets and using standard clustering techniques, but then question is how do we keep track of the sets? namely it is vital for me to know which words came from which set.
Comment: If you have too many words how do you think track all of them?
Comment: @Allan yes indeed that's part of the problem
Comment: Try using hierarchical clustering with all datasets flatanned, I think it could work.
Comment: What is flattening a set? Please add a short explanation to the Q.
Comment: How do you estimate the amount of similarity between each two words?
Answer: Your question is not entirely clear to me. Keeping track of sets and words is independent of whether you flatten or not, you just need a mapping from words to sets (and presumably vice versa) in some data structure, then given a clustering of the words you can use that data structure to find the associations in the form you need them. The second issue is what is your essential problem: is it that you want to avoid doing an all vs all comparison on all the words? A simple approach would be to do all vs all comparison on the words, use some similarity for each comparison, use a cut-off, represent this as a network, and apply graph clustering (aka community detection). Protein sequence clustering is an example of a  similar problem.


jsonArray = (JSONArray)objIn.readObject(); raise java.lang.NoClassDefFoundError: java.beans.PropertyDescriptor

Question: I get an error while receiving a JSONArray from an ObjectOutputStream
ObjectInputStream objIn = new ObjectInputStream(con.getInputStream());

I'm trying to retrieve my Stream like this:
jsonArray = (JSONArray)objIn.readObject();

and it raise the following Exception:
java.lang.NoClassDefFoundError: java.beans.PropertyDescriptor
at libcore.reflect.InternalNames.getClass(InternalNames.java:55)
at java.lang.Class.getDexCacheType(Class.java:479)
at java.lang.reflect.ArtMethod.getDexCacheType(ArtMethod.java:198)
at java.lang.reflect.ArtMethod.getParameterTypes(ArtMethod.java:143)
at java.lang.reflect.Method.getParameterTypes(Method.java:174)
at java.lang.Class.getDeclaredMethods(Class.java:808)
at java.io.ObjectStreamClass.computeSerialVersionUID(ObjectStreamClass.java:566)
at java.io.ObjectStreamClass.createClassDesc(ObjectStreamClass.java:279)
at java.io.ObjectStreamClass.lookupStreamClass(ObjectStreamClass.java:1087)
at java.io.ObjectInputStream.verifyAndInit(ObjectInputStream.java:2337)
at java.io.ObjectInputStream.readNewClassDesc(ObjectInputStream.java:1643)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:657)
at java.io.ObjectInputStream.readNewObject(ObjectInputStream.java:1782)
at java.io.ObjectInputStream.readNonPrimitiveContent(ObjectInputStream.java:761)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1983)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:1940)

I tried to add the openbeans.jar in my Eclipse libs folder (even if I do not use it) but same error...
any idea ?
Thanks
Answer: Thats not, how you add jars as libaries to your project.
You can add a jar in Eclipse by right-clicking on the
Project → Build Path → Configure Build Path.
Under Libraries tab, click Add External JARs and give the Jar.
Comment: in latest Eclipse version by adding Jars in the Libs folder adds them automatically in Private libraries path
Comment: Is that so? Ok, didnt knew since I'm using IntelliJ for a long time now.
Comment: I tried to add it in the build path manually but I have the same error.
Answer: Finally I changed the server part and tried to send/read an other type of Object (String and JSonObject) and both are working....
So it seems that it comes from JSONByteArray but I would need to dig a bit more on it....


How to estimate and interpret an offset correctly in a Poisson regression?

Question: Assume the following easy example of a glm regression with an offset:
numberofdrugs <- rpois(84, 10)
healthvalue   <- rpois(84,75)
age           <- rnorm(84,50,5)
test          <- glm(healthvalue~age, family=poisson, offset=log(numberofdrugs))
summary(test)
fitted(test) # How to get one of these values manually?

How can I compute the fitted values manually?
Also, why is there no estimation of log(numberofdrugs)? (In the book Generalized Linear Models on page 205-207 there is an example where the offset is estimated. It was done to see if the coefficient is close to one. It's 0.903 (see page 207 if you've this classic book) and from this follows, that there is nearly a constant rate in the number of damage incident!)

Previous related questions asked:

When to use an offset?
Whether to use an offset when predicting hockey scores?
Comment: Please use code (four-spaces indent, `{}` button) instead of cite (`>` indent, `"` button).
Comment: Possible duplicate of [When to use an offset in a Poisson regression?](https://stats.stackexchange.com/questions/11182/when-to-use-an-offset-in-a-poisson-regression)
Comment: "How can I compute the fitted values manually?", eg, is sufficiently distinct that I think this can be left open as a separate question.
Answer: There should not be an estimate of the offset: this offset is (could be) different for every observation (the whole idea is that you monitor the number of events within a (linear) 'timemeasure' (here apparently numberofdrugs).
There is no one 'population' offset you could estimate: person 1 is going to have 5 drugs administered, person 2 maybe 10, and you assume that the number of events (healthvalue?) is linear with this person's numberofdrugs (as per the answer to your previous question).
I don't have the book at hand, and Amazon won't let me look at the pages you mention, but I suppose something else is happening there (maybe simply the average numberofdrugs in the population)?
Comment: Once you have the beta_0 and beta_1 from the model, then for any observation, given its `age` and `numberofdrugs`,  you calculate `beta_0+beta_1*age+log(numberofdrugs)`. You can see the offset as simply another variable for which you fix the coefficient (well, of its logtransform) to 1 in the Poisson regression.
Comment: Ok that makes sense to me, but how are the fitted values calculated?
Answer: (Much of this has already been addressed in the other answers and in other threads on the site, including your own previous question linked here.  I will just address the remaining parts.)

There is no estimate of log(numberofdrugs) because that coefficient is forced to be $1$.  That's what an offset is.  On the other hand, you can estimate a coefficient for log(numberofdrugs) instead of forcing it to be $1$.  (It may help to read my answer here: In a Poisson model, what is the difference between using time as a covariate or an offset?)
Moreover, you can test a fitted coefficient against any null value, not just $0$.  Thus, you could estimate a coefficient for log(numberofdrugs) and test it against $1$, if that were the hypothesis of interest for a study.  This should be fairly trivial with any statistical software.  The Wald test for a coefficient from a GLiM is:
$$
z = \frac{(\hat\beta - {\rm null})}{SE}
$$
The resulting $z$-statistic can be checked against a standard normal distribution.  Here is a simple example, coded in R using your data:
set.seed(3917)  # this makes the example exactly reproducible
numberofdrugs <- rpois(84, 10)
healthvalue   <- rpois(84,75)
age           <- rnorm(84,50,5)
test.coef     <- glm(healthvalue~age+log(numberofdrugs), family=poisson)
summary(test.coef)
# ...
# Coefficients:
#                      Estimate Std. Error z value Pr(>|z|)
# (Intercept)         4.2275043  0.1482237  28.521   <2e-16 ***
# ...
# log(numberofdrugs)  0.0346964  0.0403885   0.859    0.390
# ...
abs(0.0346964-1)/0.0403885
# [1] 23.90046       # <- the z-value
2*pnorm(23.90046, lower.tail=FALSE)
# [1] 3.029191e-126  # <- the p-value

This example shows that, on the one hand log(numberofdrugs) is not significantly related to healthvalue (which makes sense, given there is no relationship in how the data are generated).  On the other hand, the fitted coefficient does significantly differ from $1$.  That means that using log(numberofdrugs) as an offset is not sensible; there is not a consistent rate of healthvalue per unit of numberofdrugs.
Answer: About the practical part -- outputs of glm or summary are just lists which are pretty-printed for user convenience. You can see their full structure calling unclass on them and extract single values as usual, with a help of $, [[]] and [] operators.


How are you able to create partially initialised structs?

Question: When creating a struct in Rust it seems like it's difficult to create one without having all of the fields set. For example with the following code
struct Connection {
    url: String,
    stream: TcpStream
}

You aren't able to set url without giving stream as well.
// Compilation error asking for 'stream'
let m = Connection { url: "www.google.com".to_string() };

How are you able to create these references that might be Option<None> until a later time?
The best I have found is using the Default trait, but I'd rather not have to create the TcpStream until a later time than when the struct is initialised. Am I able to do this with something like a Box?
Comment: *it seems like it's difficult to create one without having all of the fields set* => Actually, it's impossible in safe Rust: the compiler keeps you honest.
Comment: And this is *a good thing*. No more accidentally using things that are NULL! Even better, no more accidentally using things that aren't NULL but also aren't initialized!
Answer: One thing you can do is to wrap the TcpStream in an Option, i.e. Option<TcpStream>. When you first construct the struct, it'll be None, and when you initialize it you make it self.stream = Some(<initialize tcp stream>). Wherever you use the TCPStream, you'll have to check if it's Some, i.e. if it has already been initialized. If you can guarantee your behavior then you can just unwrap(), but it's probably better to make a check anyways.
struct Connection {
    url: String,
    stream: Option<TcpStream>
}

impl Connection {
    pub fn new() -> Connection {
        Connection {
            url: "www.google.com".to_string(),
            stream: None,
        }
    }

    pub fn initialize_stream(&mut self) {
        self.stream = Some(TcpStream::connect("127.0.0.1:34254").unwrap());
    }

    pub fn method_that_uses_stream(&self) {
        if let Some(ref stream) = self.stream {
            // can use the stream here
        } else {
            println!("the stream hasn't been initialized yet");
        }
    }
}

This is similar to what is done in Swift, in case you're familiar with that language.
Comment: Sure. That should've just been `ref stream`, I've fixed it. It just means that a reference to the stream within the `Option` is obtained, rather than the moving the value entirely. For further information, check out [the Rust book](https://doc.rust-lang.org/book/second-edition/ch04-02-references-and-borrowing.html).
Comment: Can someone explain the syntax of `if let Some(ref mut stream) = self.stream {`?
Answer: As an extension to Jorge Israel Peña's answer, you can use a builder. The builder has all the optional fields and produces the final value without Options:
use std::net::TcpStream;

struct ConnectionBuilder {
    url: String,
    stream: Option<TcpStream>,
}

impl ConnectionBuilder {
    fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            stream: None,
        }
    }

    fn stream(mut self, stream: TcpStream) -> Self {
        self.stream = Some(stream);
        self
    }

    fn build(self) -> Connection {
        let url = self.url;
        let stream = self
            .stream
            .expect("Perform actual error handling or default value");
        Connection { url, stream }
    }
}

struct Connection {
    url: String,
    stream: TcpStream,
}

impl Connection {
    fn method_that_uses_stream(&self) {
        // can use self.stream here
    }
}

This means that you don't have to litter your code with checks to see if the stream has been set yet.
See also:

How to initialize a struct with a series of arguments
Do Rust builder patterns have to use redundant struct code?
Is it possible to create a macro to implement builder pattern methods?
How to write an idiomatic build pattern with chained method calls in Rust?
Answer: All fields indeed have to be initialized when creating the struct instance (there is no null in Rust) so all the memory is allocated.
There is often a dedicated method (like new) that sets default values for fields which are supposed to be modified at a later stage.
I'd use the Box when you don't know the size of the field (like Vec does).


$\sup_{x\in I}|f(x)|-\inf_{x\in I}|f(x)| \le \sup_{x\in I}f(x)-\inf_{x\in I}f(x)$ and $\left|\;\int_{0}^{1}f(x)\,dx\right| \le \int_0^1|f(x)|dx$

Question: $f(x)$ is a bounded real valued function on the closed interval $[0,1]$.
Show that for any closed interval $I \subseteq [0,1]$, $$\sup_{x\in I}|f(x)|-\inf_{x\in I}|f(x)| \le \sup_{x\in I}f(x)-\inf_{x\in I}f(x)$$
and show that $$\left|\;\int_{0}^{1}f(x)\,dx\right| \le \int_0^1|f(x)|dx$$ for all function $f$ which are Riemann integrable on $[0,1]$
Answer: Hints: (1) If $f \ge 0$, then $\def\abs#1{\left|#1\right|}\abs f = f$, so there is nothing to show, if $f \le 0$, we have $\abs f = -f$, hence $\sup \abs f = -\inf f$ and $\inf \abs f = -\sup f$, that is also equality. If $f$ changes sign, we have $\sup f \le \sup\abs f$ and $\inf f < \inf \abs f$.
(2)Approximate the integral by Riemann sums and use the triangle inequality for sums.
Comment: How does $\sup f \le \sup\abs f$ and $\inf f < \inf \abs f$ this imply the result?


How to convert dynamic html page to pdf in Django?

Question: I have a task to convert a dynamic html page into a pdf document.
What we have:

dogovor application.
Formadogovora.html page which contains a form with the required fields.
The page dogovortemplate.html which contains text into which the values from the form should be substituted on the page formadogovora.html and a pdf document should be immediately generated.
The dogovor/forms.py file contains:

from django import forms

     class DogovorUserForm(forms.Form):
         sellername = forms.CharField(label='Seller's name',
     widget=forms.TextInput(attrs={'class':'form-input'}))
         yachtclass = forms.CharField(label='Yacht Class',
     widget=forms.TextInput(attrs={'class':'form-input'}))

The dogovor/urls.py file contains:

from django.urls import path
     from . import views

     app_name = 'dogovor'

     urlpatterns = [
         path('formadogovora/', views.formadogovora_user,
     name='formadogovora'),

     ]

The file dogovor/views.py contains:

def formadogovora_user(request):
         form = DogovorUserForm() # Import the form class from forms.py
         return render(request, 'dogovor/formadogovora.html', {'form': form})

Contents of the formadogovora.html file:

{% extends 'base.html' %}
    {% load static %}

    {% block title %}Form of agreement{% endblock %}

    {% block content %}

Form of agreement

    <form method="post">
         {% csrf_token %}
         {{ form.as_p }}
         <button type="submit">Generate document</button>
    </form>
    {% endblock %}

Contents of the dogovortemplate.html file:

Agreement

This agreement is concluded between:

Seller: {{ dogovor.sellername }}

Yacht class: {{ dogovor.yachtclass }}

About the subject of the agreement:

The Contractor undertakes to perform work on the development and implementation of software for the Customer.

The customer undertakes to pay for the work performed in accordance with the terms of the contract.

Contract duration:

The Agreement comes into force from the moment of its signing and is valid for one year.

Signatures of the parties:

Customer: _____________________

Performer: _____________________

Captain: _____________________

The formadogovora.html page should open at the path mysite.com/dogovor/formadogovora.html. After filling out the fields and clicking on the "Generate document" button, a new tab should open with a pdf document based on the document template.html template.
How to implement this functionality?
Answer: Try using weasyprint library. It converts an html to a pdf and it has support for django applications.
For tutorial see this link:
https://micropyramid.com/blog/generate-pdf-files-from-html-in-django-using-weasyprint
Also here is official website:
https://weasyprint.org/


Is this chord progression possible?

Question: recently I've been thinking a chord progression that I'm not sure whether it's correct or uncommon. I'm just a music lover and never go into music theory deep. I just play by my ear and the chord sound a bit same to my expected progression. It just very easy chord...
F C C Em
The second C chord is inversion that is EGC. This chord progression I just simply hum it and put it together like this, any opinion? I'm not a professional music person...
Comment: After the C/E you change one note to form Em. All very close and tidy!
Answer: If you play the natural chords in the key of C, you get:
C / Dm / Em / F / G / Am / Bdim / C
If you sing the scale doh re mi ... (C D E ...) along with this sequence you will see that it fits.
Your sequence seems to be based on the key of C.
You use chord 4 (F), chord 1 (C), chord 1 (C 1st inversion), chord 3 (Em)
So yes, it is absolutely fine although a little unusual.  The main thing is that it sounds good to you!
Answer: In music, "is X possible?", where X is anything, the answer will always be YES. You can do anything in music. All rules are made to be broken.
Your example is simple, all chords belong to C major scale. Nothing's shocking.

Is this chord progression possible?


How do I set an image so I can save it in swift 2

Question: Hi I am writing a camera app where the picture will be saved to the cameraroll when you press the photobutton without displaying it. I am almost done, but I have a problem with a piece of code that should work with swift, but don't work with swift 2.
  func didTakePhoto() {
    if let videoConection = stillImageOutput2?.connectionWithMediaType(AVMediaTypeVideo){
        videoConection.videoOrientation = AVCaptureVideoOrientation.Portrait
        stillImageOutput2?.captureStillImageAsynchronouslyFromConnection(videoConection, completionHandler: { (sampleBuffer, ErrorType) -> Void in
            if sampleBuffer != nil {
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
                let dataProvider = CGDataProviderCreateWithCFData(imageData)
                let cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, .RenderingIntentDefault)

                var savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)

            }
        })
    }
}

@IBAction func takePhotoBtn(sender: UIButton) {
    didTakePhoto()
    UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}

When I try to use the image i just created in the function that saves it, it doesn't work. How can I fix this?
Comment: What does "wont be accepted by swift2" _mean_? Your question is meaningless. The line compiles, so what's the problem?
Comment: When I try to use the "imageToBeSaved" in the function that saves the photo, it don't work.
Comment: What does "use" mean? What does "it don't work" mean? What happens exactly? There is _no_ `imageToBeSaved` in your code. Explain! If the code above is not what fails, show the code that _does_ fail. How do you know there's a problem?
Comment: Sorry, the `var savedImage` that I created in  `func didTakePhoto()` gives an error when I try to call it in the `UIImageWriteToSavedPhotosAlbum()` function. How can I fix it?
Comment: Also, the error is "use of unresolved identifyer `savedImage`"
Comment: Your complaint makes no sense. The `var savedImage` that you created in  `didTakePhoto()` is a local variable. You cannot possibly access it in the `UIImageWriteToSavedPhotosAlbum()` function elsewhere. Do you understand what a local variable is, and how it differs from a property or a global? If not, read my book: http://www.apeth.com/swiftBook/ch03.html#_variable_scope_and_lifetime  To make these be the same variable, delete `var` and declare this variable at a higher level.
Comment: Oh, I see. It makes more sense now... Thank you realy much!
Answer: Your code is structured like this:
func didTakePhoto() {
     // ...
     var savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
}
@IBAction func takePhotoBtn(sender: UIButton) {
    didTakePhoto()
    UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}

So savedImage is declared locally in, and therefore is entirely confined to, the world of didTakePhoto(). In the world of takePhotoBtn, no savedImage exists — and thus you get a compiler error.
You have two choices. You can declare savedImage at a higher level that both methods can see:
var savedImage:UIImage!
func didTakePhoto() {
     // ...
     savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
}
@IBAction func takePhotoBtn(sender: UIButton) {
    didTakePhoto()
    UIImageWriteToSavedPhotosAlbum(savedImage, nil, nil, nil)
}

Or, you can have didTakePhoto return savedImage as its result:
func didTakePhoto() -> UIImage {
     // ...
     let savedImage = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right)
     return savedImage
}
@IBAction func takePhotoBtn(sender: UIButton) {
    UIImageWriteToSavedPhotosAlbum(didTakePhoto(), nil, nil, nil)
}

Comment: Thanks a lot for the help!
Answer: I'm using this snippet in my project:
func saveImage(image: UIImage)
   let destinationPath = documentsPath.stringByAppendingPathComponent("test.png")
   UIImagePNGRepresentation(rotateImage(image))!.writeToFile(destinationPath, atomically: true)

 }

func rotateImage(image: UIImage) -> UIImage {
    print(image.imageOrientation.hashValue )
    if (image.imageOrientation == UIImageOrientation.Up ) {

        return image //UIImage(CGImage: image, scale: 0.5, orientation: UIImageOrientation.Up)
    }

    UIGraphicsBeginImageContext(image.size)

    image.drawInRect(CGRect(origin: CGPoint.zero, size: image.size))
    let copy = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()
    return copy
}


Create ShortcutKey to call a method

Question: I wish I could define any sort of shortcut like Ctrl + F, Ctrl+P, Ctrl+Alt+Tab to call a method. I tried to use CommandBinding and KeyBinding without any success. If I ain't wrong, the only way would use the CanExecute or Executed of CommandBinding to do that, but I didn't know how to associate that with any custom shortcut that I wanted, and it's necessary to define the Command with, for example, ApplicationCommands.Open.
It would be perfect if I could simply define the shortcuts like Key="B" and Modifiers="Control" with the command Command="SomeEventHandlerHere", but it isn't going that simple, unfortunately.
EDIT
I've tried this so far (it looks so wrong even to me):
CommandBinding cb = new CommandBinding(ApplicationCommands.NotACommand, MyMethod);
KeyGesture kg = new KeyGesture(Key.B, ModifierKeys.Control);
KeyBinding kb = new KeyBinding(ApplicationCommands.NotACommand, kg);
this.InputBindings.Add(kb);

private void MyMethod(object sender, ExecutedRoutedEventArgs e)
{
    // Do something
}

Comment: Its almost that simple.  Why dont you post the code that you've created so far and we'll see how close you really are.
Comment: It looks like your question is very similar to this one: http://stackoverflow.com/questions/1361350/keyboard-shortcuts-in-wpf
Comment: It really seems to be the same question. But could you help me about this line?: `Command="{x:Static local:MyWindow.MyCommand}`.

I'm getting an error: `The namespace prefix "local" is not defined`.
Answer: I've just found what I was looking for.
In order to create my own command (instead of using pre-existing ones like "Open", "Help", "Save", etc), I need to create a new RoutedUICommand. Next, we create a CommandBinding to associating the Command with the methods.
<Window.Resources>
    <RoutedUICommand x:Key="MyCustomCommand"/>
</Window.Resources>

<Window.CommandBindings>
    <CommandBinding Command="{StaticResource MyCustomCommand}" Executed="CommandExecutedMethod" CanExecute="CommandCanExecuteMethod"/>
</Window.CommandBindings>

In the code behind we have:
private void CommandCanExecuteMethod(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = true;
    e.Handled = true;
}

private void CommandExecutedMethod(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Command executed");
    e.Handled = true;
}

Now I can do what I was looking for:
<Window.InputBindings>
    <KeyBinding Key="G" Modifiers="Control" Command="{StaticResource MyCustomCommand}"/>
</Window.InputBindings>

With the above, if the window is focused, when we press Ctrl + G, the method CommandExecutedMethod is called.
We also can use the command like this:
<Button Content="Click me" Command="{StaticResource MyCustomCommand}" />

Fonts:
Tech.Pro
StackOverflow

Create ShortcutKey to call a method


React Native - Too Many Re-Renders

Question: I am trying to create a state where it shows the visibility of some components depending on if the props are not empty. I have used an if statement as shown in the code however, it creates an error where there are too many re-renders happening. If i set a default let showComponents = false or true, everything works fine. Any idea on how to fix this issue as the visibility of the components is dependent on if the props are empty or not.
Code:
const [showcComponents, setView] = useState(false);
...
if (props.params == undefined) {
setVisibility(false);
} else {
setVisibility(true);
}

Comment: please provide the full code
Answer: For every update in sent to your component you are calling setVisibility(false/true). This is probably messing with the rendering method in react creating a rendering loop. You should try not to call a function outside a hook. Assuming you have a visibility variable you can try:
...
useEffect(()=>{
    if(props.params === undefined && visibility === true){
         setVisibility(false);
    }else if(props.params !== undefined && visibility === false){
         setVisibility(true);
    }
}, [props.params]
)
...

Answer: This code will result in infinite re-render cycles. Because each time the component will render it will call setVisibility which will re-render the component
const [showcComponents, setView] = useState(false);
useEffect(()=>{
  if (props.params == undefined) {
    setVisibility(false);
  } else {
    setVisibility(true);
  }
}, [props.params])

Also you can write is shorter like this:
useEffect(()=>{
    setVisibility(props.params !== undefined);
}, [props.params])

React Native - Too Many Re-Renders


Can we have many adapters for Alamofire session manager?

Question: I would like to have many adapters to the same SessionManager, is it possible?
My usecase is:
setup default header from an adapter
if basic_auth: add basic_auth_adapter
if token_auth: add token_auth_adapter
Thanks
Answer: Currently in Alamofire 4 you can only use 1 RequestAdapter with each SessionManager. We designed it this way because to help you simplify things and to avoid order issues if there are multiple adapters.
You could easily add all those functions to the same adapter. Our intention was that if an adapter became way too complicated, you could break out the logic into multiple smaller objects. One way you could possibly do this would be to create a smaller adapter for each type of URL request. Then the main adapter called by the SessionManager would inspect the URL request and call the appropriate smaller adapter.
Answer: I came up with this solution:
struct MasterAdapter: RequestAdapter {

    let adapters: [RequestAdapter]

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var request = urlRequest
        try adapters.forEach({ request = try $0.adapt(request) })
        return request
    }

}

Now set MasterAdapter with it's child adapters as your adapter on your default or custom SessionManager.
SessionManager.default.adapter = MasterAdapter(adapters: [MyAdapter1(), MyAdapter2()])

Comment: Thanks @diegotrevisan! But shouldn't `request` be returned at the end of the method, instead of `urlRequest`?
Comment: @ChristophP Ooops, you are right! I'm fixing it, thanks!


An inequality involving three consecutive primes

Question: Can you provide a proof or a counterexample to the following claim :

Let $p,q,r$ be three consecutive prime numbers such that $p\ge 11 $ and $p<q<r$ , then $\frac{1}{p^2}< \frac{1}{q^2} + \frac{1}{r^2}$ .

I have tested this claim up to $10^{10}$ .
For $p>5$ we get $\pi(2p)-\pi(p) \ge 2$  , a result by Ramanujan .
This means that $q<2p$ and $r<2p$ , so $\frac{1}{2p}<\frac{1}{q}$ and $\frac{1}{2p}<\frac{1}{r}$ which implies $\frac{1}{p} < \frac{1}{q} + \frac{1}{r}$ . If we square both sides of inequality we get $\frac{1}{p^2} < \frac{1}{q^2} + \frac{2}{qr} + \frac{1}{r^2}$ . Now , I don't know how to rule out term $\frac{2}{qr}$  .
Comment: @user477343 I made it  by myself...
Comment: @gnasher729 : The claim says three consecutive primes.
Comment: Wow... brilliant :)
Comment: Where did you find this claim? $(+1)$
Comment: @gnasher729 $$\frac{1}{101^2}<\frac{1}{103^2}+\frac{1}{107^2}$$ as $(101,103,107)$ is a triplet of three **consecutive** primes.
Comment: Let me tell you what I'm trying to explore this week, different versions/variations of the so-called Firoozbakht's conjecture. I try
rewrite the inequality showed in Firoozbakht's conjecture for different arithmetic functions. My problem is that I can not to find one (from my experiments and knowledges) with a good mathematical content. Maybe a variation using Ramanujan primes instead of prime numbers has mathematical meaning. I say it if you want to explore it. Isn't required a response and good week.
Comment: @user477343 To be honest relation $1/p < 1/q+1/r$ was already known...:-)
Comment: Your result by Ramanujan doesn't prove the claim, for example 1/101^2 < 1/197^2 + 1/199^2 is false. You need two primes between p and 1.4142p.
Answer: The inequality holds for all $p$ large enough. Let $a>1$ be such that $a^{-2}+a^{-4}=1$ and $p_n$ be the $n$-th prime. By the Prime Number Theorem there is an $N$ such that $p_{n+1}<a\,p_n$ for all $n\ge N$.If $p\ge p_N$, then $q<a\,p$ and $r<a\,q<a^2\,p$ and
$$
\frac{1}{q^2}+\frac{1}{r^2}>\frac{1}{a^2\,p^2}+\frac{1}{a^4\,p^2}=\frac{1}{p^2}.
$$
Comment: And since $$a = \sqrt{\frac{1 + \sqrt{5}}{2}} \approx 1.272 > \frac{6}{5}\,,$$ [we don't have to fear that $N$ must be large](https://math.stackexchange.com/questions/368798/understanding-a-famous-proof-by-jitsuro-nagura-need-help-understanding-one-step).
Answer: This is a comment as opposed to an answer

All primes $p_{n+1} < 2p_n$. Let $p'$ be the prime before $p$, $q'$ be the prime before $q$, and $r'$ be the prime before $r$. Then, $$p+q+r< 2(p' + q' + r')$$ So $$\frac{1}{p^2} < \frac{1}{\big(2(p' + q' + r') - q - r\big)^2}$$ Also, $$\frac{1}{p^2} < \frac{1}{q^2} + \frac{2}{qr} + \frac{1}{r^2} = \left(\frac{1}{q} + \frac{1}{r}\right)^2.$$ Consider $$\frac{1}{\big(2(p' + q' + r') - q - r\big)^2} < \left(\frac{1}{q} + \frac{1}{r}\right)^2$$ then multiplying both sides by the denominator, subtracting $1$ from both sides, and then factoring, we get $$0 < \left(\left(\frac{1}{q} + \frac{1}{r}\right)\left(2(p'+q'+r')-q-r\right) + 1\right)\left(\left(\frac{1}{q} + \frac{1}{r}\right)\left(2(p'+q'+r')-q-r\right) - 1\right)$$ Which is true since primes are always positive, the entire inequality is literally just a bunch of multiplication, and if $p' = 2$, $q' = 3$ and $r' = 5$ then this inequality holds.
Your conjecture would be thus true if $$\frac{1}{\big(2(p'+q'+r')-q-r\big)^2} < \frac{1}{q^2} + \frac{1}{r^2}.$$
Answer: Here is a stronger form of the above inequality. The prime number theorem implies that for every $\epsilon$, there exists a prime $p_{\epsilon}$ such that for all $p > p_{\epsilon}$, we have $1 - \epsilon < \frac{p}{q}, \frac{q}{r} < 1$. Hence for all positive real $a$ and all primes greater than some $p_{\epsilon_a}$
$$
\frac{2 - \epsilon_a}{p^a} < \frac{1}{q^a} + \frac{1}{r^a} < \frac{2}{p^a}
$$


fail to get procees name (vb.net)

Question: i wan to create a program that can get the application name
i can start the program but cant get the program name

a = Process.Start("calc").Handle

MsgBox(a)

MsgBox(Process.GetProcessById(a).ToSt
ring)

it show Process with an Id of 1796 is not running, but the program already opened
Answer: Handle!=Id, and ToString() won't give you the process name:
Dim a = Process.Start("calc").Id
MsgBox(a)
MsgBox(Process.GetProcessById(a).ProcessName)

Displays a process ID in one message box, then "calc" in the next.
If you had Option Strict On, you'd have received a warning already about your mixup between Handle and Id, since Handle returns an IntPtr, but GetProcessById expects an Integer.
Comment: oic..
ty for reply my post..
ty <3

fail to get procees name (vb.net)


How to write a sharp (#) or hash-tag in Lilypond markup

Question: I want to write a Cis (C-sharp) with markup{}.
I am aware that there is a difference between the usual hashtag sign # (used in commenting code or on twitter) and the muscial sharp sign ♯.
With the original sharp sign this code works well.
markup{C♯}

But I found out that it does not work with a hashtag even if it is escaped
markup{C#}
markup{C\#}

So why is that and how could this be solved without the original sharp sign?
Comment: Because # is LilyPond syntax to introduce Scheme code. Try \markup { "C#" }.
Comment: Terminology nitpick: `#` is more usually known as the 'hash' sign*;  hash_tag_ is the metadata tag _beginning_ with a hash symbol. (* It's also sometimes called the 'number' sign — and in the US 'pound' sign, referring to the weight unit, but that's confusing in e.g. the UK where the pound sign is `£` referring to the currency.)
Comment: Why don't you just set up a keyboard layout that can type a ♯ rather than all this messing around? macOS you could do it with Ukelele [or even just a text replacement as I used here]. I'm sure Windows must have some sort of equivalent, even if it's the lumpy alt/unicode thing.
Answer: Try:
\markup{C\sharp}
You might also like to make the symbol smaller and raise it up with \super, and and you'll probably want to concatenate the letter and symbol together with \concat; something like:
\markup{\concat{C\super\sharp}}
Answer: It is unclear to me what you want.  You write

I am aware that there is a difference between the usual hashtag sign # (used in commenting code or on twitter) and the muscial sharp sign ♯.

And you state

With the original sharp sign this code works well.
\markup{C♯}

Yet you appear to desire getting a hashtag sign instead of an accidental in a musical context.  That makes little enough sense.  Of course, LilyPond uses the hashtag sign for something different (introducing Scheme), and "it does not work with a hashtag even if it is escaped" is nonsensical in a language that does not use backslashes to escape special characters (other than in very specific in-string contexts).
It appears that you want \markup "C#" or in most contexts the simpler "C#" though it is unclear why.
Comment: What makes you say "you appear to desire getting a hashtag sign instead of an accidental"?


CPP WINDOWS : is there a sleep function in microseconds?

Question: I know there is for milliseconds (Sleep(milli))
but I couldn't find one for micro..
Comment: http://stackoverflow.com/questions/5801813/c-usleep-is-obsolete-workarounds-for-windows-mingw
Comment: http://stackoverflow.com/questions/85122/sleep-less-than-one-millisecond
Answer: The VS 11 dev preview includes the part of the standard library dealing with threads. So now you can say:
std::this_thread::sleep_for(std::chrono::microseconds(1));

Of course this doesn't mean the thread will wake up after exactly this amount of time, but it should be as close as the platform (and library implementation) allows for. As other comments have pointed out, Windows doesn't actually allow threads to sleep for durations this short.
Answer: You can use rdtsc instruction or QueryPerformanceCounter Windows API function to get high-resolution counters. You can calibrate them then with GetTickCount, or time functions for example.
Answer: Windows can't sleep for less than a millisecond. Time slices tend to be much higher than 1ms, so it isn't really possible even with a thread a highest priority.
If you don't care about burning CPU, you can spin until QueryPerformanceCounter has elapsed your time.
Answer: I just wrote a detailed comment about the sleep() function and spinning the
performance counter. To avoid typing it here again, here is the link:
c++, usleep() is obsolete, workarounds for Windows/MingW?


Is this proposition incomplete?

Question: In mendelson logic textbook , there is this proposition,(I will replace some letters to make it easier to read)
"If $P$ is a tautology containing as statement letters $A_1,A_2,...,A_n$ and $Q$ arises from $T$ by substituting statement forms $B_1,B_2,...,B_n$ for $A_1,A_2,...,A_n$ ,respectively, then $Q$ is a tautology;that is ,substituting in a tautology yields a tautology"
For me , this seems incomplete.Shouldn't there be this line also that ,"$A_1 \equiv B_1 , A_2 \equiv B_2 , ... , A_n \equiv B_n$ "?
Answer: No.
$p \lor \lnot p$ is a tautology. According to the proposition, also $(p \lor q) \lor \lnot (p \lor q)$ is.
But $p$ and $p \lor q$ are not equivalent.
Answer: As Mauro showed: No, this is not necessary.
In fact, the fact that the $B_i$'s need not be equivalent to the $A_i$'s reveals the real 'power' of this proposition. It shows that once you know that a certain statement is a tautology, then anything with that same abstract 'form' will be a tautology as well. And, since the $A_i$'s are statement letters, it doesn't matter what you substitute them with: the abstract form will be retained, and hence the result is still a tautology.
To illustrate this with Mauro's example: we know that $p \lor \neg p$ is a tautology, and indeed anything of the form $[something] \lor \neg [something]$. So, no matter what $[something]$ you substitute for $p$, the result is a tautology.
And finally, to demonstrate the importance that we are subsitutiong statements for statemwnt letters, note that $p \lor \neg p$ could also be seen as being if the form $[some statement]$, as of course every statement is ... but clearly just substituting justanything  for $p \lor \neg p$ as a whole does not mean we end up with a tautology.
And if that latter example is a bit too abstract for you:
Consider the statement $(p \lor \neg p) \land (q \to q)$
This is a tautology, as of course anything of the form $[something1] \lor [something1] \land ([something2] \to [something2])$ is. This is why you can systematically substitute anything for $p$ and $q$ and still have a tautology.
However, this statement is also of the form $[something1] \land [something2]$. But that is not a tautologous form: $r \land s$ is not a tautology. Hence, substituting just anything for the complex statements $p \lor \neg p $ and for $q \to q$ does not necessarily result in a tautology. It is only when you work with the atomic variables that you can be guaranteed to retain 'tautologousness'.
Comment: Then is there a rigorous proof of this proposition or is it too obvious to be proven? [To me  this proposition seems to be too obvious]
Comment: @Prithubiswas Yes, there is a rigorous proof for this. Look for 'Substitution Theorem' or 'Replacement Theorem'... although please keep in mind that there are two main such theorems: one is the one we are dealing with here, but another one is the one that I think you had in mind when you posted your question:  that as long as two expressions *are* equivalent, then we can substitute the one for the other one in a larger expression and have the result be equivalent to the original - so that latter is the one you rely on when you're doing Boolean algebra (DeMorgan, Distribution, etc)

Is this proposition incomplete?


Calling non static method from static method

Question: I have a class and portal_type Person and there are 2 methods in it:
class Person(BaseContent):
    def print_all(self):
        catalog = getToolByName(self, "portal_catalog")
        results = catalog(portal_type = 'Person')
        final_result = ''
        for result in results:
            final_result += result.getObject().print_person()
        return final_result

    def print_person(self):
        return self.name

But I realised that print_all is not associated with any object so it should be static method. What I want to do is get all the instances of the person and call print_person(). But the problem is: what should I write in the catalog since there is no self object after I make the print_all method static method. For instance now I cannot write
catalog = getToolByName(self, "portal_catalog")

I want something like:
@staticmethod
def print_all():
    instance = Person()
    catalog = getToolByName(instance, "portal_catalog")
    .
    .
    .

But it is giving me 'invalid syntax' error at instance = Person()! I hope my question is clear and any help will be appreciated!
Comment: In your example, print_all IS an instance method. If you want to make it static, you should use the @staticmethod annotation.
Comment: I have edited the question. The first code is what I have and the last one is what I need!
Answer: You can replace self with context, like this:
# this is needed only if you don't have a context to pass
from zope.app.component import hooks

def print_all(context=None):
    if context is None:
        context = hooks.getSite()
    catalog = getToolByName(context, "portal_catalog")
    results = catalog(portal_type = 'Person')
    final_result = ''
    for result in results:
        final_result += result.getObject().print_person()
    return final_result

Comment: @SadikshaGautam: you have to set the site manually; `from zope.app.component.hooks import setSite` and `setSite(app.site)`. This is normally done with the traversal machinery.
Comment: I am getting error in the getToolByName line it says 'raise AttributeError, name'
Comment: I am getting this hooks.getSite() as None when I call Person.print_all().
Comment: I've replaced `if not context` with `if context is None` as that test is a lot more precise *and* doesn't have any unexpected side effects and semantics.
Comment: @SadikshaGautam: Are you calling this outside of a request (so not through a HTTP call)?
Comment: @MartijnPieters: yes, I am in debugging mode and am just calling it from there. So, is there any other way how I can check this print_all method from the console that sets the value of context?
Comment: yes thank you that solved the problem! What I did was set the site explicitly from the console and that seemed to do the trick! :)


External login , in case internal login fail

Question: I have a website which needs to authenticate users using drupal users table.
If authentication fails, then I want to run the authentication against users table from another database.
lf authentication is successful , then I want to register this user inside drupal, so the next this user next time he logs in , he get authenticated from drupal users table , not the external users table.
I wish to get a complete solution for that.
the following code is my attempt :
function external_auth_form_user_login_alter(&$form,$form_state){

$form['#validate'] = array( 'user_login_name_validate' );
user_login_authenticate_validate( $form, $form_state );
if(!empty($form_state['uid'])){

db_set_active('barakah');
$result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =>$form_state['input']['name'],':pass'=>$form_state['input']['pass']));
db_set_active('default');
if(!empty($result)){
$username = $form_state['input']['name'];
user_external_login_register($username, 'external_auth');

}

}

}

but as if the code doesn't exist, nothing happens
Comment: Can't you just import the user from the old DB to Drupal?
Comment: You should extract user informations from the DB and use the User Import module : https://drupal.org/project/user_import. What might be tricky is keeping the password, it depends how it's encoded in your old database.
Comment: my solution should work, it is similar to many tutorials, but as if my code is not executing, external_auth_form_user_login_alter should alter user login form, but in my case it doesn't
Comment: This is never going to work with hook_form_alter. This hook is called when displaying the form, not on form validation. You should add a hook_validate on the form.
Comment: can you post a solution please ? modify my code and then let me copy it and try it for my self
Answer: You can use:
drupal_external_login_register

Helper function for authentication modules. Either logs in or
  registers the current user

An example implementation is detailed here:
https://api.drupal.org/comment/13434#comment-13434
Comment: you are absolutely right, but what i want is that external authentication undergo only if internal authentication fails, i hope that you got any clue for that.
Comment: i am doing this because i have upgraded a system to drupal, and i have users on the new website, and also i have users on the old website, when i tried solution for external drupal login, external login works, but internal login fails !
Comment: You just need to add the user login validate handlers in the correct order, so local drupal ones run first.
Comment: i edited the question, and i hope that you got any clue about why my code is not working
Answer: Try something like this :
function custom_user_validate_login_validate(&$form,$form_state){
    $form['#validate'][] = 'custom_user_validate_login_validate';
}

function custom_user_validate_form_user_login_alter($form, &$form_state) {
    drupal_set_message("Custom Validation"); //Just to check if the hook_validate is called
    user_login_authenticate_validate( $form, $form_state );
    if(empty($form_state['uid'])){ // remove the ! here
        db_set_active('barakah');
        $result=db_query('select username,password from users where username= :name   and password= :pass',array(':name' =>$form_state['input']['name'],':pass'=>$form_state['input']['pass']));
        db_set_active('default');
        if(!empty($result)){
        $username = $form_state['input']['name'];
        user_external_login_register($username, 'external_auth');
        }
    }
}

[Edit] Need to remove ['submit'] from hook_form_alter
[Edit2] Renaming the function names: replace custom_user_validate by your module name
[Edit3] Updating the name of hook_validate to match function names
Comment: i just tried it , it didn't work, not even print the custom message !
Comment: Just edited the answer, you need to remove ['submit'] from hook_form_alter
Comment: didn't work, not even custom message display
Comment: One last try: the hook validate gets called with this code.
Comment: Also, you should remove the "!" in front of empty


Criar um programa que seja utilizável no Windows

Question: Sou estudante de programação, ainda no primeiro ano do meu curso. Até agora estudei Java, C, Haskell e Script Shell. Sou bastante funcional em Java e C.
Eu sei escrever código, compilar e excecutar num terminal do Linux, mas imaginemos que eu quero criar uma aplicação que rode no Windows. Eu escrevo o meu código - em Java, por exemplo - criando uma simples calculadora.
Depois de ter o código, como faço para criar uma aplicação que possa ser rodada no Windows, um chamado "programa"?
Se for um processo muito complexo para o meu grau de competências, digam logo isso, por favor.
Desde já obrigado a quem me tentar ajudar :)
Comment: É só dar dois cliques no .jar?
Answer: Programas criados na linguagem Java rodam na maquina Virtual Java, logo não são stand-alone, eles dependem de que o usuário tenha JavaVM instalado, é impossível rodar um programa escrito em Java sem isto.
Compilar um programa em C, C++, etc, vai ser compilado baseado no compilador usado, não tem como rodar em Windows algo que foi compilado para Linux, assim como não tem como rodar algo que foi compilado para Mac OS X v10.1 rodar no Mac OS X v10.13, isto devido a arquitetura usada por ambos sistemas operacionais.
Compilar em Windows geralmente tem compatibilidade entre os sistemas da familia Windows, mas depende muito do compilador que usoue das APIs usada para escrever o código.
Então para resumir, se é Java vai rodar em diversos sistemas desde que tenha JavaVM instalado, se for C vai ter que compilar em arquitetura por arquitetura que desejar executar o programa.
Linux geralmente não tem compatibilidade entre diferentes distros Linux, por este motivo algumas aplicações geralmente são distribuídas em sources e você tem que compilar com GCC (ou outro compilador que a distro e/ou repositórios disponham), claro que não há garantias de funcionamento, vai depender de quem escreveu o código.
Comment: @VictorStafusa todos programas que prometem tornar seu programa Node.js, Python e Java fazem o uso disto. A questão é que o JavaVM tem que ser compativel com a arquitetura, então isso não pode ser considerado, pois uma javavm para windows não vai funcionar em linux e provavelmente o gerador de executável copia o JavaVM da maquina aonde foi gerada, a não ser que exista um programa muito bom que crie um stand-alone com as javavms para os sistemas mais populares, o que provavelmente vai fazer um programa simples pesar horrores.
Comment: Na verdade, já vi alguns programas em Java que são stand-alone ao usar o seguinte truque: Eles têm uma JVM inteira exclusiva embutida dentro deles. Essa abordagem é bastante incomum e eu só recomendaria para casos muito específicos, mas existe sim.
Answer:
Tendo como base um exemplo bastante simples: criar uma calculadora. Depois de ter o código, como faço para criar uma aplicação que possa ser rodada no Windows, um chamado "programa"?

Supondo que você esteja no Windows e que as as classes da sua calculadora estejam localizadas em uma pasta src, sendo a classe com.example.Calculadora a classe principal, você pode fazer isso para compilar o seu programa em um arquivo calculadora.jar (supondo que a sua JDK esteja corretamente instalada):
cd src
dir /s /B *.java > ../sources.txt
cd ..
javac -encoding utf8 -d bin @sources.txt
jar -cfe calculadora.jar com.example.Calculadora -C bin .

Se você quiser compilar no unix/linux, mesmo que depois vá (ou não) usar o JAR produzido no windows, pode fazer assim (mudando apenas a segunda linha):
cd src
find -name "*.java" > ../sources.txt
cd ..
javac -encoding utf8 -d bin @sources.txt
jar -cfe calculadora.jar com.example.Calculadora -C bin .

Para executá-lo em um ambiente (unix/linux ou windows) onde haja uma JVM compatível corretamente instalada, você pode clicar duas vezes no arquivo calculadora.jar ou então fazer isso:
java -jar calculadora.jar


Confidence intervals of coefficients in polynomial regression

Question: Given a model $a_{n}\cdot x^{n}+ a_{n-1}\cdot x^{n-1}+...+ a_0 = y + e$, where $e$ is some unknown (but assumed normally distributed) error and $x$ and $y$ are observations.
Now, how would one to estimate the confidence intervals of the coefficients $a_.$?
AFAIU, a simple procedure based on the covariance $(X'X)^{-1}$ is not sufficient, where $X$ is the $n$'th order (zero mean) Vandermonde matrix of $x$.
First of all $X'X$ is singular. Also calculation $var(a)= (r'r/m)\cdot diag(pinv(X'X))$, where $r$ is the residual and $m$ number of observations, seems to be vague, because high correlation between columns of $X'X$.
Comment: If all $x_i$ are distinct both $X$ and $X^\prime X$ are non-singular. In your case it means you can have the same $x$? Have you considered http://en.wikipedia.org/wiki/Scheff%C3%A9%27s_method?
Comment: The Vandermonde matrix can be *terribly* ill-conditioned. So, even though $X^T X$ is (theoretically) nonsinguler, it can very easily be numerically singular/unstable.
Comment: I have merged your accounts. Now you can edit all your content directly.
Answer: I think the practical answer is that in this situation you wouldn't regress using power functions, $x^n$, in the first place, for the reason that you give -- that the Vandermonde matrix is very ill-conditioned.  Rather, you use some sort of orthogonal polynomials, which should be better conditioned.
If you specifically need confidence intervals on the coefficients of the power functions, then these will be linear combinations of the coefficients of the orthogonal polynomials, so you can use that to compute the desired confidence intervals.


React js loop through array received from blade

Question: Im using React js for the front-end in a Laravel project. From a controller , im passing an array to my view:
return view('shopCart')->with('items',$it);

Now in the view a could loop through the array like this:
@foreach($items as $item)

<input type="checkbox" name=""> {{$item->Name}}   {{$item->Cost}}

@endforeach

And this is working fine. But i would like to make the view more dynamic(by the way this is a list of products in a shopping cart). For example , by default all the checkboxes will be checked, meaning the user is buying all items. I want that if the user uncheck a box, the total price changes . So i made a React component , and im passing the $items array to that component via props:

And there's the component:
class Items extends Component {
    render() {

        return (

               Continue shopping
               //LOOP THROUGH THE ARRAY OF PRODUCTS

        );
    }
}

export default Items;

window.onload=function(){
if (document.getElementById('listshops')) {
    var data=document.getElementById('listshops').getAttribute("datas");
    ReactDOM.render(<Items items={data}/>, document.getElementById('listshops'));
}

}

How can i loop through that array i passed to the component so i can display the product like in the @foreach in blade ?
Comment: This is a duplicate question of the following: https://stackoverflow.com/questions/46908480/how-do-i-use-for-loops-with-react
Answer: Array#map, don't "loop". You're mapping one dataset (your products) into another dataset of equal size (React components)
const { items } = this.props;

return (

    Continue shopping
    {items.map(({ Name, Cost }) =>

      <input type="checkbox" name="" /> {Name}   {Cost}

)}

);

Often when you map, it's a good indication that you're using a component that could be reusable too. This could be a cleaner approach for you:
const Product = ({ Name, Cost }) => (

    <input type="checkbox" name="" />
    {Name}

    {Cost}

);

Then in your render:
const { items } = this.props;

return (

    Continue shopping
    {items.map(({ Name, Cost }) => <Product {...{Name, Cost}}/>}

);


Neyman-Pearson Lemma and hypothesis-testing

Question:
Consider testing $H_0:\theta=\theta_0$ vs $H_1:\theta=\theta_1$, where
  the pdf or pmf corresponding to $\theta_i$ is $f(x|\theta_i)$, $i=0,1$
  using a test with rejection region R that satisfies
$x\in R$ if $f(x|\theta_1)>kf(x|\theta_0)$ and $x\in R^c$ if
  $f(x|\theta_1)<kf(x|\theta_0)$ for some $k\geq 0$ and
  $\alpha=P_{\theta_0}(X\in R)$
And any test that satisfies it is a UMP test with $\alpha$ level.

How do I find the value of k?
Suppose I have a test $H_0:\theta=\theta_0$ vs $H_1:\theta=\theta_1$ with pdf $f(x|\theta)$ and I want a test with size $\alpha=0.1$.
Then $x\in R$ if $\frac{f(x|\theta_1)}{f(x|\theta_0)}>k$ so for I find $k$ I did $P_{\theta_0}(X\geq k)=0.1$?
and my critical region is $x\geq k$?
Comment: One example has been worked out [here](http://stats.stackexchange.com/questions/142754/how-to-get-the-critical-region-for-a-uniformly-most-powerful-test-for-mean-of-no?rq=1), among others on CV.
Answer: The false alarm probability $\alpha$ (also called the Type I
error probability) is the probability that the value of the single
observation $X$ lies in the rejection region $R$ when $H_0$ is the true
hypothesis.  Note that when $X \in R$, the null hypothesis
$H_0$ is rejected
(and in this case, the alternative $H_1$ is accepted).
So, (for continuous random variables)
$$0.1 \geq \alpha = \int_R f(x\mid \theta_0)\,\mathrm dx.\tag{1}$$
Any region for which $(1)$ holds is a possible candidate that can
serve as the rejection region. Which of these should we choose?
Well, the power $\beta$ of the test is the probability of correctly
declaring in favor of $H_1$ (rejecting $H_0$) when $H_1$ is indeed
the true hypothesis, that is,
$$\beta = \int_R f(x\mid \theta_1)\,\mathrm dx
= \int_R f(x\mid \theta_0)\times
\frac{f(x\mid \theta_1)}{f(x\mid \theta_0)}\,\mathrm dx
= \int_R f(x\mid \theta_0)\Lambda(x)\,\mathrm dx\tag{2}$$
where $\Lambda(x)$ is the likelihood ratio.  Maximizing
the power $\beta$ while still managing to avoid the abyss
of $\alpha$ exceeding $0.1$ seems like a reasonable goal to
strive for. But how should we go about doing this?
Clearly, we want to include in $R^*$, the optimum region
for which $(1)$ holds and $\beta$ is maximized, those $x$
for which $\Lambda(x)$ is as large as possible. So,
start with the global maximum of $\Lambda(x)$ as the
point we definitely want to include in $R^*$ and then
search for points where $\Lambda(x)$ is smaller than the
global maximum but still large, including such points in $R^*$.
Keep your eye on $(1)$ though, and stop as soon as you
have achieved the desired $\alpha$.  The region $R^*$
depends on what the likelihood ratio looks like. It is
not the case that $R^* = \{x\colon x \geq k\}$ as you think
but rather that
$$R^* = \left\{x\colon \Lambda(x) \geq k\right\}.$$
This translates into $\{x\colon x\geq \hat{k}\}$ only if
$\Lambda(x)$ is an increasing function of $x$.