How to modify content of the original variable which is passed by value?

Question: There is an existing API function which does only allow the plugin(DLL) to receive three parameters and perform some action:
int ProcessMe(int nCommand, unsigned int wParam, long lParam);

Now, from the main program(exe), would like to pass two variables to the plugin, and require plugin to modify their content, and main program will read them again, to perform some task.
My question is, from the above function, can I perform this, without changing the function parameters?
Example:
int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
  // modify the parameters//
  return 0;
}

int main()
{
  BOOL bSave = TRUE;
  int nOption = 0;
  ProcessMe(0, (unsigned int)(&bSave), (long)(&nOption));
  if(FALSE==bSave)
    printf("bSave is modified!");
  return 1;
}

Comment: No. You need to pass by reference, which you cannot do without changing the API. You'll either have to reimplement the interface with pointers, or learn to live without.
Comment: This doesn't make sense. The function won't be expecting to use the parameters to store results. They are not for output. You need to declare a new function.
Comment: Sadly i'm not allowed to change the interface, as there are currently many other DLLs running with the exe using the similar interface.... backward compatibility concern for me :(
Comment: Yes can be done: the parameters passed to your function are only passed by value, but the last argument can in fact be an address (passed by value) such that ProcessMe can manipulate the data at that address: in the calling program cast a pointer to long and vice versa in ProcessMe.
Comment: While passing a pointer as the lParam will work with care, (see all the other posts re. issues), you should note that the format of this call is suspiciously like Windows SendMessage/PostMessage.  If this call is a PostMessage wrapper, it is possible that the request made is not complete when the call returns and so any vars referenced in the call may not have been written yet.
Answer: Place the variables to modify in a struct and pass the pointer to the sturuct to the plug in:
struct MyStruct
{
    BOOL bSave;
    int nOption;
};

int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
    ((MyStruct*)lParam)->nOption = ...;
    return 0;
}

Use it like this:
int main()
{
  MyStruct struct;
  struct.bSave = TRUE;
  struct.nOption = 0;
  ProcessMe(0, 0, (long)(&struct));
  if(FALSE==struct.bSave)
    printf("bSave is modified!");
  return 1;
}

Strictly speaking this is undefined behavior. You need to check, whether it works on your platform.
Note: I used a struct here, because this way you can also pass more variables or larger variables such as double to the function.
Comment: @LuchianGrigore - of course! The intent is to modify the contents of the struct.
Comment: Wrong, this won't modify the original parameters. `wParam` will still be the same.
Comment: What struct? There's no struct in his code. Your answer answers a whole different question.
Comment: @Luchian Grigore: The author meant that the caller may pass a pointer to an arbitrary struct instead of the `lParam`
Comment: Casting pointers to integer types falls under implementation defined behavior.  It is undefined in this case if `long` happens to not be sufficiently large enough to hold the pointer value after conversion.
Comment: @jamesdlin: As an exception to the "implementation-defined" part, roundtripping is guaranteed by the Standard if the integral type is large enough.  Most likely `long` is a typo, all the WinAPI functions with parameters named `lParam` actually use a pointer-sized integer for that.
Answer: No, there's no way to do that.
Passing by value means copies of the original ones are created. In the method scope, you will have no information about the original variables.
You need to either pass by reference or by value.
Comment: I know it is not type-safe, and I said that. This all stems from the fact that some older API were designed in an era when C programmers didn't care much about type-safety. When you cannot change the code of the API, you'll have to resort to an ugly, unsafe, non-portable and possibly dangerous solution anyway.
Comment: This is not correct. Although you cannot do it in a type-safe way, you can do it by reinterpreting the contents of the `lParam`. This in fact happens a lot in Win32 API. Henrik has already shown a solution that works.
Comment: @AlefSin dereferencing NULL pointers also happens in Win32 API. That's why we have a standard to guide us, not the MSDN documentation.
Comment: +1 for AlefSin ' ugly, unsafe, non-portable and possibly dangerous' maybe, but also, as in the case of kernel API, often 'unavoidable'.  Unavoidable wins.
Comment: @AlefSin: Roundtripping through an integer of sufficient size is guaranteed by the Standard.  If you have to do it with an integer of insufficient size, using an index to a global array of pointers can work.
Answer: Try this... it is POSSIBLE!!!
include
int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
int *nCommand_ptr = (int*)nCommand;
unsigned int *wParam_ptr = (unsigned int*)wParam;
long *lParam_ptr = (long*)lParam;
*nCommand_ptr = 10;
*wParam_ptr = 10;
*lParam_ptr = 10;
return 0;

}
int main(){
int nCommand = 5;
unsigned int wParam = 5;
long lParam = 5;
printf("\n %d %u %lu",nCommand,wParam,lParam);
ProcessMe((int)&nCommand,(unsigned int)&wParam,(long)&lParam);
printf("\n %d %u %lu",nCommand,wParam,lParam);
return 0;

}
Output:
$>g++ passbyref.cc
$>./a.out
5 5 5
10 10 10$>
Answer: Compiling for 32 bits platform you could cast to pointer the parameter:
#include <stdio.h>
typedef int BOOL;
#define FALSE 0
#define TRUE 1

int ProcessMe(int nCommand, unsigned int wParam, long lParam)
{
  // cast to match what you passed in
  *((BOOL*)wParam) = FALSE;
  return 0;
}

int cast_arguments_main(int, char **)
{
  BOOL bSave = TRUE;
  int nOption = 0;
  ProcessMe(0, (unsigned int)(&bSave), (long)(&nOption));
  if(FALSE==bSave)
    printf("bSave is modified!");
  return 1;
}

On a 64 bits platform the compiler complains about the impossibility to represent the pointer:
cast_arguments.cpp:17:37: error: cast from 'BOOL*' to 'unsigned int' loses precision

I had to change the unsigned int wParam parameter declaration to unsigned long wParam, and similar change at call point: ProcessMe(0, (unsigned long)(&bSave), (long)(&nOption));
but then you could simply declare the right type for your parameter, to be BOOL *. Thus feasibility depends on your target machine architecture...
Comment: On 64-bit Windows (which is where the name `lParam` pops up the most), the type of lParam isn't `long`.  Actually he probably should just be using `intptr_t` to begin with.


TOST for equivalence test

Question: Let's say that we are measuring the tracking position error of two controllers and we want to know if both controllers are similar (we already perform a "differences" test but we are requested to perform an equivalence test).
For example, if the mean $\mu$ (in meters) of one controller (12 samples) is 0.00344 (standard deviation $\sigma=0.0006481424$), the other (12 samples) is 0.00331 ($\sigma=0.000498$).
If $\varepsilon$ is the magnitude of region similarity. How do we define this $\varepsilon$?
I could consider $\varepsilon$ as $N \cdot \sigma$ as the region of similarity so, for example if $N=3$ then $\varepsilon=3\cdot(0.00064)=0.0019$ (using the data of the first controller).
Or, I could use something like $\varepsilon=\mu \cdot 0.05$, this takes 5% of the mean (of the first controller) which gives $\varepsilon =  0.0172$.
The question is, should we use the data for controller 1 or 2---as in the previous options---to define this parameter; or should do we consider other kind of difference measure between them in order to determine the epsilon parameter?.
Finally, why not use the epsilon as a 0.9 which may indicate that the 90% of the 'data (or the area of the distribution)' should be similiar?
I appreciate any advice in order to determine the epsilon.
Please see e.g. the function here:
https://github.com/cran/equivalence/blob/master/R/rtost.R
http://www.inside-r.org/packages/cran/equivalence/docs/rtost
Thanks
Comment: This is a little hard to follow. You have a real statistical question here, so it is on topic, but note that asking about how to use R can be off topic. You may want to edit this to make your statistical question clearer & more accessible to people who don't use R.
Comment: You might find the [write up on the tost tag](https://stats.stackexchange.com/tags/tost/info) (especially the final paragraphs) a useful answer to your question.
Answer: Since no one answered, I will try to show what I understood and how it should be choosen the region of similarity.
The  null hypothesis is $H_0 : |\mu_1 - \mu_2| > \varepsilon$ (where $\mu_1$ and $\mu_2$ are means for controller 1 and 2).  Thus $\varepsilon$ is the minimum value by which we will define how similar is the response (tracking error) of the controller.
Thus, I think that  due to the equipment and the resolution of the mechanical device, $\varepsilon$=1mm is a good choice. But this value is defined
subjectively, by experience or taken into account any advice on the  particular field of interest.
Answer: Generally, the value of $\varepsilon$ should be selected with the meaning "the smallest magnitude of difference between $\mu_1$ and $\mu_2$ that I care about."
In practice, there may be specific standards to adhere to (e.g., FDA guidelines about choice of $\varepsilon$ in equivalence and bioequivalence trials).

TOST for equivalence test


Como usar ancora no vuejs/vue-loader?

Question: Estou criando um projeto com vuejs webpack (vue-loader) e recentemente me deparei com um problema, não consigo ancorar nenhuma tag, pois o vue entende que ao usar o hash #, vc esta querendo direcionar para uma rota...
Alguem sabe como resolver isso ?
Quero que quando houver um click na tag , a pagina seja ancorada para a div de baixo:
 Teste

 Oi, eu sou uma div

No href da tag  ja tentei colocar das seguintes formas:  #ancora, /endereço-url#ancora , /endereço-url/#ancora , /#ancora.
Mas tudo sem sucesso
Comment: Talvez isto ajude, http://stackoverflow.com/q/40341939/3162303
Answer: Descobri que ao usar a tag <router-link> ao invés da tag , é possível resolver este problema, alem de também resolver outros problemas como o de links-ativos por exemplo.
No caso ficaria assim:
<router-link to="#ancora"> Teste </router-link>

 Oi, eu sou uma div

Muito obrigado a todos pela ajuda
Answer: Acredito que esteja utilizando o vueRouter, caso sim, é preciso alterar a forma como a função scrollBehavior se comporta. O exemplo abaixo demonstra como navegar até o elemento na página em vez de mudar de "página".
new VueRouter({
    mode: 'history',
    scrollBehavior: function(to, from, savedPosition) {
        if (to.hash) {
            return {selector: to.hash}
        } else {
            return { x: 0, y: 0 }
        }
    },
    routes: [
        {path: '/', component: abcView},
        // your routes
    ]
});

A documentação pode ser encontrada no link:
http://router.vuejs.org/en/advanced/scroll-behavior.html
O exemplo foi retirado do seguinte link:
https://stackoverflow.com/questions/40341939/how-to-create-anchor-tags-with-vue-router
Answer: Olá
Veja uma outra solução, talvez seja mais simples.

    {{textLink}}

 Oi, eu sou uma div

Como usar ancora no vuejs/vue-loader?


Why pressing back button inside of cordova WebView closes app?

Question: Given two initialized and added in the backstack fragments  (one of them i see on the screen). Each fragment has CordovaWebView as view. In one web view i have loaded "www.google.com" in another "www.bing.com". Now, if I press a back button - i am awaiting, that the fragment with "www.bing.com" will be poped from the stack and I will see google site on my device screen. Instead of this, the app immediately exits (for a very short time I can see google.com, but then app completly exits)
small part of Activity:
cordova.getActivity().getFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container, webViewFragmentGoogle)
.addToBackStack(null)
.commit();

cordova.getActivity().getFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, webViewFragmentBing)
.addToBackStack(null)
.commit();

Fragment:
public class WebViewFragment extends Fragment {

    private String mUrl = "file:///android_asset/www/main.html";
    private CordovaWebView mWebView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.webview_fragment,container, false);

        if (view != null)
            mWebView = (CordovaWebView)view;

        Bundle bundle=getArguments();
        String iframeUrl = bundle.getString("iframeUrl");

        if (!mUrl.isEmpty())
        {
            mWebView.loadUrl(iframeUrl);

        }

        return view;
    }

    public void goToUrl(String url) {

        mWebView.loadUrl(url);

    }

    @Override
    public void onResume() {
        super.onResume();

        if (mWebView!= null) {
            mWebView.handleResume(true, false);
        }

    }

    @Override
    public void onPause() {
        if (mWebView != null)
        {
            mWebView.handlePause(true);
        }
        super.onPause();
    }

    @Override
    public void onDestroy() {
        if (mWebView != null)
        {
            mWebView.handlePause(true);
            mWebView.handleDestroy();
        }

        super.onDestroy();

    }

}

Answer: This happens because of CordovaWebView.onKeyUp() logic - it intercepts your key strokes and hooks some actions on them: in this case action is:
this.cordova.getActivity().finish();

Personally I also find killing my activity a bit intrusive, especially in case, when I cannot configure it in any way. Please check CordovaWebView messes up with onBackPressed method in android for some details.


Close modal but the widget condition is same when open it again

Question: Behavior of modal is always dispose when we close it. How to prevent the modal from dispose? So when i close it then open it again, the condition still same.
Answer: I resolve using Page Storage widget. I think it is the simple way and it can save the scroll position of page.
It can combine with @Ashutosh Sharma's answer based on your need.
Answer: To prevent the modal from being disposed in Flutter, you can manage its state outside of the modal itself. Here are some tips on how to achieve this:
State Management: Use a state management solution (like Provider, Bloc, or setState) to manage the state of the content inside the modal.
Preserve State: Store the state of the modal's content in a variable that exists outside of the modal. This way, the state is preserved even when the modal is closed.
Pass State to Modal: When opening the modal, pass the preserved state back to it.
Comment: I have another solution, but i appreciate your answer.


Show that the space of superharmonic functions is not a linear space

Question: Let $(X_n)_{n\in\mathbb{N}_0}$ be a Markov chain with state space $E$ and transition matrix $P=(p_{i,j})_{i,j\in E}$.
A real valued function $h$ on $E$ is called superharmonic if $h(x)\geq Ph(x)$ for all $x\in E$, where $Ph(x)=\sum_{y\in E}p_{x,y}h(y)$. Define the space of superharmonic functions by
$$
\mathcal{S}(X,P):=\left\{h\colon E\to\mathbb{R}: h\geq Ph\right\}.
$$

Show by way of example that the space of superharmonic functions $\mathcal{S}(X,P)$ is no linear space.

Edit
Consider a superharmonic function $h\in\mathcal{S}(X,P)$ with $h(x)>Ph(x)~\forall x\in E$.
Set $g(x):=-h(x)~\forall x\in E$. Then for any $x\in E$ it is
$$
g(x)=-h(x)<-Ph(x)=P(-h(x))=Pg(x).
$$
Thus $g\notin\mathcal{S}(X,P)$, hence $\mathcal{S}(X,P)$ is not a linear space, because in order to be a linear space it has to be $\alpha\cdot h\in\mathcal{S}(X,P)~\forall\alpha\in\mathbb{R}$. But this is not the case for $\alpha=-1$ as shown.
Am I right?
Comment: Exactly. Notice also that only $f(1)$ determines which of the inequalities hold, hence any function for this chain is either superharmonic, or subharmonic.
Comment: is my example clear to you?
Comment: Let's see if I got it. State space: $E=\left\{0,1\right\}$, transition matrix $P=\begin{pmatrix}1 & 0\\1 & 0\end{pmatrix}$; consider $h(x):=x$. Then $h(x)\geq Ph(x)$ for $x\in E$, especially $1=h(1)>Ph(1)=0$, thus $-1=-h(1)<0=-Ph(1)=P(-h(x))$. Thus there is a $x\in E$ such that $-h(x)<P(-h(x))$ and hence $-h\notin\mathcal{S}(X,P)$, meaning that $\mathcal{S}(X,P)$ is not a linear space. --- Ok?
Comment: Thank you very much for your help!
Answer: Your approach is certainly right: superharmonic functions form a convex cone, that is if $f$ and $g$ are superharmonic, then $\alpha f + \beta g$ is superharmonic for non-negative $\alpha$ and $\beta$. Moreover, if $f$ and $-f$ are superharmonic then $f$ is harmonic, so the whole question is to construct an example when there are superharmonic functions that are not harmonic. My guess is that example must be concrete: you have to provide a particular Markov Chain and a particular function. Can you think of such a particular example?
Example: since a single-state MC is not enough, let's go for two-state one: X = $\{0,1\}$. Put all the transitions to $\{0\}$ so that $Pf(x) = f(0)$. Hence harmonic functions must be constant, and any other function is either superharmonic, or subharmonic.
Comment: @Salamo: no, define the MC by $p_{00} = p_{10} = 1$.


Problemas com NaN ao obter valores de um input

Question: Estou tentando fazer uma calculadora em JavaScript/HTML, mas está dando um erro de NaN nas entradas do usuário, mesmo usando um parseFloat, ele ainda diz que não é um número, alguém poderia me dizer como resolver isso?

var num1 = parseFloat(document.getElementById("n1").value);
var num2 = parseFloat(document.getElementById("n2").value);
function calculate(op) {
    var opV = document.getElementById("op");
    var operator = op.value;
    opV.value = operator;
    var res = 0;
    res = eval(num1 + operator + num2);
    var resV = document.getElementById("result");
    resV.value = res;

}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
    <link href="https://fonts.googleapis.com/css2?family=Lexend+Tera&display=swap" rel="stylesheet">
    <link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAAADhCAMAAAAJbSJIAAAAsVBMVEX///+Vpabs8PE0SV5/jI0sPlCRoqPFzM3nTDyZqamNnJ29xscwQ1fb4eI3SFcwRlxbbHmhr7Dx9faHlZbo7O12hIXQ19gnOk3s9fYcMkefp6znRzZOXGpOYXDpjoboenHnV0jppJ/qura3vcLnQC0hNUmyvb6stLoTLEJzg4lqeoFcbXbJ0dKHmJs+UmV6i5EAITrrzcsAFDLnOSOMlZ3plo+psLYJJz7ogHbocmfr1dMKW/CjAAAIhklEQVR4nO2da2ObNhSGAwG5mBAHmUudOuvaBGK7zmVb1677/z9sgMHB5kiWYt3s6e2nOrbQwxHSQdILFxdWVlZWVlZWVqCSaD0KVWu0jhI1eFHpIF1yykg6XxZUx9EnhIJMKl8S68RrIWOJjTXTGr9OCEkL48gEvlpodOaAshAzcwArRAkN1TUJsEJ0hRMa0Iv2hWLRgJFZgBWi6LE/1k00kOAgJqaFsAqi2IE/NJAwFEpoXiMV3EyxeSGsgogFEhp4GQq+EI3KZzoJzWvIhIF8KSFcw4SBs7y7lq27pQNDorV8wlVe5LkvV3l1jJUmQjQvJNN1Kubg8WUTBsoAa0SgocomDJbqACvE5RBRNiG6Ugjo+1dADSQTvhRKCYsX1YTBN9md6K7yb4NmKptwrphw2NcIJRxOswXzK7UCCEVOuAGEd5NLlZrcWUJLaAktoSW0hJbQElpCS2gJLaEltISW0BK+i/BGMeGNakJnqZhwOaiBbMKxUsDLy7FywuCbyiBOhhPC0gkd51Id4uQSOL58widliJPLJy2EztOzGsTJMwSogtBBq4kKrQhHV0DoBM7L6kauVi+EjQpqCB0F202IR1ZFqE+W0BJaQv2yhJbQEuqXJbSEllC/LKEltITdYQ4+JOBgRd9bghJCFJSjjKZ1GFMhEYrDNbWEURmQDi6fEMWZi7FLFXajkoyIysg9VAB2M9ihK58QlfS6betI8KPUu3wP4HUCT5J0QlQyVs/FBNsUyphLgBClE8aMtasrCFpQUcgKWAmweMomRBl79VwXmhMMeAoAmoFsQo4QVkGETtGII4RQECUTcjUx1wXs/CjiOkfDhi6bEGikuNPwT8mwmQYJDyHQTGUTAhEYdQL+NmxkXM0cagXqCSN/ttHr/TCKZ0GYXLcOnpkltISW0BJaQku4T1jlJkmdn0TXeUfoNh8lvayFSlh/cfP1+lf9f4kBhPj+ed5qa2ndfrLEDIR4OSfqedscNBI+LvJWPdfuRsUNE+FNkZO0eDSBcEa2JzMSkk3TM0toCS2hJfyfEL62N77Ftl5F+8mCkXAxI+nVAEI3u+3UPc+leOk+eXQZCN3HW7K200E6s7Zu/qmflw7mpGiEmCLXBMJO55t5W0JLaAktoULCq+6m7mwJ7wY35idNCKw9NZMsrusCi0qnuPbEt74JPMQWcRECa6zS14C5CLOhQXLMtUyOla8BO1OeEGBgRwziOkfJVDmhx7zZpK5fChCmHOcIl576GKYRMyIeewChN2YvIErVx3DqTZkR4xQkTFkHDBxVR9NA6HlMm7Zw4qQeSOilTsJUwro6lh7C1Mmot6+1otKrBRJWKqNDBbhZfYY0EVaMwJH7GnupRyWs/j4cSHaPsylBFyGzgLrzFaCecHw0Id85Uv9MBXRk/XjPkfqde3whAAD5milwucvfI8xRP7gz4Qki8HMFu6CPCQBnM9CyC5odkTwcsEZR0052xiBMqW4EphIIv1XjKBmPp1SND1lK0KECiC3AuoIsoSXUL0toCS2hfqkhRIj+GCXnoIn0/SUoedZXEEYJXdGa+gJTFK8PlhASTKQqMu+QYaoMuxnJ5lqdoeyQhbSZrIPfL6ng7onVIEl6mzeKGWe9YYumfA8pswMUWlurxb6+BiJKn6fhWbcA37XLY8+DbLLSCbnWnqAK8pwicAFS8gopo5G7FWRy5Vs/HJ4j2YSsRvM2BANAx+FbAx5a3jWs4/crtE9IW8f/SFP3Je0eUhz1g5oMdmNQ9mJ8/PIbWX90iNp3myTX/ttyIl7+uY9II/z18Imkv74aQ3hT5POu2eHvi7zY26tBI/z86QNJD6YQ4tXM9zuHDL5d+H5+tbtCfOKE+GXR7Gdb1VD4vvlPfp2cDyG+/dlu2fuOXTwqNlvvi/nZEPb8CItbnPmdt2AT0jMgxGHPcDF7fH4zT8xezoPQjfovBp713CFFb8g46dECJ+C7j/OdjbQ0wr8/E/XLjBEfJ88A4u4+Wtr+UqasTfNoAURxbyv0Ce6g3R3xB4jFPXNOcxKEFeLdjgGt2H9Az8kTVvcWfZNe8f1ir4InT4i3Zvy2m3k8sxjuA1aIP87qOhwCVn3pjzPqS3HkAz7X3Sie9HgIA/r+z1vGnOaf34n6YETWlvWaaF70YBe3bITGZ97Z1ZYqz0c3sx4hW+ZtPCGOOsTcX2N3i7hzIZ404bYrbQDdDnHG2tOcAGGLmOftlGmDyD5anAJhg7gFbBA5RvyTIKwR/bf1RLx65cjaToPwqFn9Xw9EmTGLAWmwMEUj/PqFrH+7bxnhIaXo3WtP2xLUrz2d/TNo+Z5zjEeAh5TPZ6v+HZYeTwgwsBkasdsPK0XqHZaew15BvAY9pBwL5djR4SFlvhJxRPCuMVs0cajFQ8qKWDtAYUJWF2oFqMedl8bJoVcj1A8QCmFPSONHCVkKSOJUm/8wDUb0rYVRVm4ckgTC1CuzAyWMghS2lShyWKaHRPT1dJ4ixhIkEwJvqDDAQ7oWSHi0hxSyLpnuIeULwXHuvlrA74USAvYqniDC7jOeIEIVEEkYQq+N5qggYY/wcafoKRRJCBp5mRGJ+7yPAXQ8kYQjIK9kRqRYLJkMlgRAlAq9DoG0kLGGU/ojE8YMJcBnaCqYkNzSjnwp2XtLQJ5QwnVKsNTrU5UMiRzxMzD11ak68c8EErp1cki/oNSqHoxTVyAhbvoDcxCbbGOKBRJexOReW4M2/W8sErC5EOlDmzq1Q5TQy7ASdfBVqu0AKhbwIky3jDrj+JZipCJztkY7WcZ0rEPTnfxHNGAz6BskocN9q9gkxFRsR9qK89lXUjWWAVgN+6ZEMRU72Pc0NgMxlRPBRqUJiGkpD/DiIkG6GVOUyASsFMVvE9nK6dI0jiTz1cJRGXPOeAvRNC6jd/Qw/wHdNfwdNOd19wAAAABJRU5ErkJggg==" type="image/x-icon">

        Calculator

            <input type="number" name="number1" id="n1" placeholder="Enter a number">
            <input type="text" name="operator" id="op" value=" " disabled>
            <input type="number" name="number2" id="n2" placeholder="Enter a number">

            <button name="+" id="opr" value="+" onclick="calculate(this)">+</button>
            <button name="-" id="opr" value="-" onclick="calculate(this)">-</button>
            <button name="x" id="opr" value="*" onclick="calculate(this)">x</button>
            <button name="/" id="opr" value="/" onclick="calculate(this)">/</button>

        <input type="text" id="result" disabled placeholder="Result">

Comment: já experimentou colocar as duas linhas dentro da função?
Comment: @LeoCaracciolo valeu, nem pensei que poderia ser isso, funcionou.
Comment: Sobre o uso de `eval`, vale a pena ler [aqui](https://pt.stackoverflow.com/q/4154/112052) e [aqui](https://pt.stackoverflow.com/q/128845/112052)
Comment: Ok valeu @hkotsubo
Answer: Como já disseram, o problema é que você carrega os valores do input antes que eles sejam preenchidos, então o valor deles não é um número, e por isso parseFloat retorna NaN.
Mas ao contrário do que afirmou a outra resposta, eu acho importante chamar parseFloat sim. Pois se você clicar em uma das operações sem preencher os números, a string gerada terá apenas o símbolo correspondente à operação, dando erro no eval. Mesmo se apenas um deles não for preenchido, ainda sim gerará uma expressão inválida.
E vale lembrar que usar input type="number" não te garante que só serão digitados números. O Firefox, por exemplo, permite que se digitem letras e quaisquer outros caracteres, o que com certeza irá gerar uma expressão inválida e dar erro no eval. E o Chrome, mesmo não permitindo qualquer texto arbitrário, ainda permite que se digite coisas como e....eeee (já que o ponto é um caractere válido para digitar números com casas decimais, como 2.5, e o e é usado em notação científica, como 3.4e2 para representar o número 340, então ele permite esses caracteres, mesmo que o resultado não seja um número válido), então se você não chamar parseFloat e concatenar as strings diretamente, o eval dará erro também.
Quanto ao uso do eval em si, eu particularmente prefiro não usar (veja mais detalhes aqui e aqui). Para o caso em que qualquer coisa for digitada (como no já citado Firefox), a pessoa pode digitar qualquer comando válido em JavaScript, e este será executado.
Claro que para um exercício simples isso não é um grande problema, mas de forma geral, você não precisa do eval (pode parecer fácil e eu entendo a "tentação" de usá-lo, mas se for fazê-lo, deve tomar os cuidados de sanitizar as entradas para evitar maiores problemas - leia os links já indicados para saber mais).
Enfim, uma forma de fazer, verificando se foram digitados números e sem usar eval, seria:

function calculate(op) {
    document.getElementById("op").value = op.value;
    var num1 = parseFloat(document.getElementById("n1").value);
    var num2 = parseFloat(document.getElementById("n2").value);
    if (isNaN(num1) || isNaN(num2)) {
        alert('não foram digitados os 2 números');
    } else {
        var res = document.getElementById("result");
        switch(op.value) {
            case '+':
                res.value = num1 + num2;
                break;
            case '-':
                res.value = num1 - num2;
                break;
            case '*':
                res.value = num1 * num2;
                break;
            case '/':
                res.value = num1 / num2;
                break;
        }
    }
}

        <input type="number" name="number1" id="n1" placeholder="Enter a number">
        <input type="text" name="operator" id="op" value=" " disabled>
        <input type="number" name="number2" id="n2" placeholder="Enter a number">

        <button name="+" id="opr" value="+" onclick="calculate(this)">+</button>
        <button name="-" id="opr" value="-" onclick="calculate(this)">-</button>
        <button name="x" id="opr" value="*" onclick="calculate(this)">x</button>
        <button name="/" id="opr" value="/" onclick="calculate(this)">/</button>

    <input type="text" id="result" disabled placeholder="Result">

Removi aquele monte de CSS e HTML do código original, para deixar mais simples, pois o importante era focar no JavaScript e mostrar a ideia geral do código.
Answer: Você está fazendo o caching dos valores dos inputs logo ao inicializar a página.
var num1 = parseFloat(document.getElementById("n1").value);
var num2 = parseFloat(document.getElementById("n2").value);

Como esse comando executa apenas uma vez ao inicializar, ele irá buscar os valores dos inputs (que são uma string fazia a esse ponto) e fazer o parse da string vazia (resultando em NaN). Variáveis do tipo string são valores, não referencias, então não importa o que o usuário digitar, esses valores não serão atualizados, eles sempre serão NaN
O que você deveria fazer é o seguinte:
// se for fazer caching, faça caching das referências
var num1 = document.getElementById("n1");
var num2 = document.getElementById("n2");
var resV = document.getElementById("result");
var opV = document.getElementById("op");

function calculate(op) {
    // também não há a necessidade de fazer parseFloat, se você irá
    // converter os números de volta para string
    opv.value = op.value;
    resV.value = eval(num1.value + op.value + num2.value);
}

Comment: Valeu pela explicação! Funcionou!


Expand and collapse rows through a button

Question: Is it possible to expand and collapse the last 2 rows in a table via button?
When the page loads those rows has to be hidden.
here is the table:

        Match Schedule

        asd

- Start 15 Aug 2015 21:00</p1>

        asd

 - Start 15 Aug 2015 21:00

        asd

 - Start 15 Aug 2015 21:00

        asd

 - Start 15 Aug 2015 21:00

        asd

 - Start 15 Aug 2015 21:00

        asd

 - Start 15 Aug 2015 21:00

Answer: Depending on your current markup, you can

Select the last two elements using
tbody tr:nth-last-child(-n+2) and then
Use toggleClass to switch between the classes defined to hide and show it.

$('button').on('click', function() {
  $('tbody tr:nth-last-child(-n+2)').toggleClass("display");
});
tbody tr:nth-last-child(-n+2) {
  display: none;
}

.display {
  display: block !important;
}

      Match Schedule

      asd

- Start 15 Aug 2015 21:00

      asd

- Start 15 Aug 2015 21:00

      asd

- Start 15 Aug 2015 21:00

      asd

- Start 15 Aug 2015 21:00

      asd

- Start 15 Aug 2015 21:00

      asd

- Start 15 Aug 2015 21:00

<button>Press me</button>
Answer: You could use bootstrap's collapse function in order to wrap the last two rows in a div and control is via a button.
More information: http://getbootstrap.com/javascript/#collapse


Find eigenvalues and eigenvectors of a matrix

Question: $\begin{pmatrix} 2 & 12 \\ 2 & -3 \end{pmatrix} \textbf{v} = k \textbf{v}.$
For what values of $k$ which are real there exists a 2-vector $v$ satisfying the above equation?
How do I start this problem? Should I just let $n=\binom{a}{b}$ and plug it in?
Thanks!
Comment: Have you heard of eigenvalues and eigenvectors?
Comment: This problem is a very basic question on this subject. This is not to say you can't solve it using other, even elementary techniques, but eigenvalue/eigenvectors is the natural way to tackle this problem.
Comment: No, are they necessary for this problem?
Comment: Ok, but I've never heard of those. Could you guide me through with another form of solution?
Comment: Your own suggested course of action is plausible. Plugging it in will gt you a system of two equation with three variables: that's okay, because if $(k,v)$ is a solution then $(k,t\cdot v)$ is also a solution for all $t \in \mathbb{R}$.
Comment: I don't know how to find k, I have $\binom{a}{b}k=\binom{2a+12b}{2a-3b}$
Answer: For a matrix $A$ if $Av=kv$ for $v$ a non zero vector then $k$ is an eigenvalue of $A$ and $v$ an eigenvector.
$$
\begin{pmatrix} 2 & 12 \\ 2 & -3 \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix}2v_1+12v_2 \\ 2v_1-3v_2 \end{pmatrix}
$$
So we want:
$$
2v_1+12v_2=kv_1\\
2v_1-3v_2=kv_2
$$
This system is equivalent to the following:
$$
(2-k)v_1+12v_2=0\\
2v_1+(-3-k)v_2=0
$$
which corresponds to:
$$
\begin{pmatrix} 2-k & 12 \\ 2 & -3-k \end{pmatrix} \begin{pmatrix} v_1 \\ v_2 \end{pmatrix} = \begin{pmatrix}0 \\0 \end{pmatrix}
$$
This systems has a non trivial solution $v=(v_1,v_2)$ when the determinant of the matrix is $0$, namely when:
$$
(2-k)(-3-k)-24=0 \Leftrightarrow k^2+k-30=0 \Leftrightarrow (k+6)(k-5)=0 \Leftrightarrow k=-6, \quad k=5
$$
For each of these values of $k$ you can find $v\neq (0,0)$ that satisfy the above equations.
Can you find such $v$'s for each of these $k$'s? If not, I can elaborate further.
Comment: Ahh, ok! are the v's $\binom{4}{1}$, $\binom{-3}{2}$ for k=5, -6 respectively?
Comment: I was just learning what an eigenvector was! So you produced a system of equations out of that.
Comment: @user406996 I didn't use anything apart for a system of equations corresponding to the equation you have. I only mentioned for reference the terms eigenvalue and eigenvector. You don't seem to appreciate my answer for what it is!
Comment: Hmm, then I was mislead by your solution, sorry. I'm not quite sure how to use the eigenvalues and vectors, so its a rough ride trying to learn what they are.
Comment: Ohh, now I see how you did it. I saw "system" and I immediately thought you were using system of equations.
Comment: @user406996 It's only doing a bit of algebra with the initial equation given in your post.
Answer: Let's try doing it via elementary means. Using your notation, we have the system:
\begin{align}
\tag{1}\label{eq1}2a+12b &= k \cdot a\\
\tag{2}\label{eq2}2a-3b &= k\cdot b
\end{align}
With $\eqref{eq1}$, we find that $(k-2)a=12b$ $\,\,(*)$.
Multiplying both sides of $\eqref{eq2}$ by $12$, we get $24a-3\cdot 12b=k\cdot12b$. We now substitute $(*)$ into this equation, obtaining
$$24a-3(k-2)a=k(k-2)a$$
which we may rearrange to obtain $$(k^2+k-30)\cdot a = 0$$
This implies that either $a=0$, $k=5$ or $k=-6$.
We see via $(*)$ that $a=0$ implies $b=0$, and then any $k$ will do. These are the trivial solutions.

Now, suppose $k=5$. Then we get from $(*)$ that
$$3a=12b \iff a=4b$$
So we get a family of solutions $n=(4t,t)$ and $k=5$. For instance, $n=(4,1)$ and $k=5$ is a solution.

Now, suppose $k=-6$. Then we get from $(*)$ that
$$-8a=12b \iff -2a=3b$$
So we get a family of solutions $n=(-3t,2t)$ and $k=-6$. For instance, $n=(-3,2)$ and $k=-6$ is a solution.
Comment: Thanks for the non eigen solution! Very much appreciated! :) Either way, you need to produce a system of equations with the top and bottom of the vector, correct?
Comment: Yes. Notice that we had to solve a quadratic equation to get the values of $k$. That's because our system has two equations. In geneal, if the system has $n$ equations, we'd have to find the roots of degree $n$ polynomial, and this can become hard fairly quickly.


Is error term in MA model in univariate time series the same as white noise

Question: I what to know if the error term referred to in moving average model of time series the same as white noise? which is usually define in r as
e <- rnorm(n=20, mean=0, sd=1)

If y[t] = e[t] + theta*e[t] where theta is a parameter provided makin the ma(1) model to be y[t] = e[t] + 0.8*e[t] if `t = 1,2,...,100. Can I figure it out in ar as:
n=100
theta <- 0.8
wn <- ts(rnorm(n, mean=0, sd=1))
ma1 <- wn[1]
for(i in 2:n){
  ma1[i] <- wn[i - 1] * theta + wn[i]
}

Answer: Yes, the error term in the formula is white noise. Couple of caveats,

There is a difference between a theoretical white noise process, and simulated samples from it, which you can get with the rnorm formula. The formula is more like the idealized version, a hypothesis for how the real world works, while with rnorm, you get real numbers that are an example of how it works out
White noise with discrete time steps is quite simple to construct and think about, but if you want to define or sample from white noise in continuous time, it is a lot more involved and this difference may be confusing when looking at books or articles on the topic

Edit
See the answer by Ben below, he is absolutely right by adding that the error terms in a MA model can actually also come from other distributions. So to be more precise, the answer is No, it doesn't have to be.
Answer: One of the nice things about MA models (and ARMA models more generally) is that we can based them on an underlying "error" sequence that is of whatever form we want it to be.  Usually we want the underlying error sequence to be a white noise series, but there is no necessity in this.  When you encounter an ARMA model, the underlying error sequence should be stipulated in the model, but if it is not, it would be reasonable to presume that Gaussian white noise is intended.
Comment: Try writing out the recursive equation for the model and then take the variance of both sides --- see what you get.
Comment: Unfortunately, no.  There are other problems with what you did.  When you generate an MA(1) process recursively, the first value in the generated vector needs to be set to have variance equal to the stationary variance of the series.  Your present code does not do this.
Comment: For an MA(1) you have $\mathbb{V}(Y_t) = (1+\theta^2) \sigma^2$ so your starting values should have this variance.  Your code should have ```ma1 <- sqrt(1+0.8^2)*wn[1]``` instead of ```ma1 <- wn[1]```.
Comment: @Daniel Your comments asking for answers are an abuse of this system.  For constructive and acceptable ways to bring attention to a question please visit https://stats.stackexchange.com/help/no-one-answers.
Comment: @whuber Ok, I will check it out
Comment: You mean what I did is correct?
Comment: can you please give me what the starting point of this my MA(1) should be so I can learn from it
Comment: In my attempt to know more, why the square root in `ma1 <- sqrt(1+0.8^2)*wn[1]` from `$V(Y_t)=(1+\theta^2)\sigma^2$`


Swift delegate beetween two VC without segue

Question: I have 3 classes:

ChatLogControoller
GetImageFromLibraty(NSObject class)
ImagePreviewViewController

I want to press a clip from the first VC, then open the media library to pick an image. Then the selected image is passed to the third VC as a previewController. Then if I select 'done' I want to pass it to the first VC.
1st VC
class ChatLogControoller: UICollectionViewController, UICollectionViewDelegateFlowLayout, NSFetchedResultsControllerDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, DataSentDelegate {

func recievePhoto(data: UIImage) {
    imageFromView = data
    print("-------\(imageFromView = data)")
}

override func viewDidLoad() {
    super.viewDidLoad()

    let vc = ImagePreviewController()
    self.vc.delegate = self
}

2nd class its just picker of image, so i pass image to 3rd VC and this image appears on imageView of 3rd VC successfully!
my 3rd VC
protocol DataSentDelegate {
    func recievePhoto(data: UIImage)
}
class PreviewController: UIViewController, UIScrollViewDelegate {

var delegate : DataSentDelegate? = nil

var aImageView: UIImageView!
var aImage: UIImage!

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(actionSend))
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(actionBack))

}

@objc func actionBack() {

    dismiss(animated: false, completion: nil)
}

@objc func actionSend() {

    let data = aImageView.image
    delegate?.recievePhoto(data: data!)
    dismiss(animated: true, completion: nil)
}

Comment: what problem you are facing?
Comment: @V_rohit what i miss in code to pass data from 3rd VC to 1st VC?
Comment: call the delegate method in 2 VC from which you are passing the photo to 3rd VC
Comment: @V_rohit but how i can pass it from 3rd VC to 1st vc in this situation?
Comment: you created the protocol in your 3rd VC just call this protocol in your 1st VC by using protocol you can pass the data to the 1st VC
Comment: @V_rohit i provide sample of my code... is it correct? Because recievePhoto if 1st VC is empty
Comment: you just want to pass an image from 3rd VC to 1st VC
Comment: @V_rohit exactly...
Comment: I am not sure it looks correct...I think the missing part is calling delegate at right... I need to do it by myself first... just wait for few moments let me do that
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/174795/discussion-between-george-heints-and-v-rohit).
Comment: Hey... I got your solution.... sorry for reply very very late.. I am giving the answer hope it will help you... I will explain that later just use that and you will get your solution
Answer: You need to create one more protocol in your SecondViewController to Pass that delegate from ThirdViewController to FirstViewController.
FirstViewController:
import UIKit

class ViewController: UIViewController, DataSentDelegate, dataSentDelegate  {

    @IBOutlet weak var imagefromThirdVC: UIImageView!

    var thirdVCImage: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func buttonTapped(_ sender: Any) {
        let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController2") as! ViewController2
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func goToThirdVC() {
        let vc = storyboard?.instantiateViewController(withIdentifier: "ViewController3") as! ViewController3
        vc.delegate = self
        self.navigationController?.pushViewController(vc, animated: true)
    }

    func recievePhoto(data: UIImage) {
        thirdVCImage = data
        imagefromThirdVC.image = thirdVCImage
    }
}

SecondViewController:
import UIKit

protocol dataSentDelegate {
    func goToThirdVC()
}

class ViewController2: UIViewController {

    @IBOutlet weak var passingImage: UIImageView!

    var delegate: dataSentDelegate? = nil

    var images: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()

        images = UIImage(named: "screen")
    }

    @IBAction func actionButton(_ sender: Any) {
        self.delegate?.goToThirdVC()
    }

}

ThirdViewController:
import UIKit

protocol DataSentDelegate {
    func recievePhoto(data: UIImage)
}

class ViewController3: UIViewController {

    var delegate: DataSentDelegate? = nil

    @IBOutlet weak var passedImageView: UIImageView!

    var passedImage: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()

        passedImage = UIImage(named: "screen")
        passedImageView.image = passedImage
    }

    @IBAction func action(_ sender: Any) {

        let data = passedImageView.image
        delegate?.recievePhoto(data: data!)
        //   delegate?.goToFirstVC()

        guard let viewControllers = self.navigationController?.viewControllers else {
            return
        }

        for firstViewController in viewControllers {
            if firstViewController is ViewController {
                self.navigationController?.popToViewController(firstViewController, animated: true)
                break
            }
        }

    }

}


Move DB from Apache to IIS

Question: I've been working on a Drupal site under a LAMP configuration. My client uses SQL Server, so after I'm done with development I need to move the site over to their configuration. I work on Linux, so I have no way to test the site live (I can remotely connect to my client's server but if I want anything changed I have to go through their IT department, which is painful and slow at best).
I found this module, driver for SQL Server, but from the instructions I gather this is for a fresh Drupal install. Could it work, if I already have some work done, to move my current DB over to their server? If not, is there another option to keep working on MySQL and later migrate to SQL 2008?
I'm not familiar with SQL Server, so any help is appreciated.
Comment: Not a good answer, but I would beg and plead with the customer not to do this thing.
Comment: I already exhausted that option, but as you can see it didn't work. And to add insult to injury, the site must  work on IE7 & IE8 :(
Answer: Here is the way I would approach your issue:

Prepare two IIS+MSSQL servers, Staging and Production
Do a fresh install on Staging
Use tool like Features, UUID, and data migration module of your choice to move configuration and data from Development to Staging
Tie loose ends on Staging
Copy Staging to Production
Replace my dev with something less unlike production

Move DB from Apache to IIS


Send messages to IBM MQ Uniform Cluster from stand alone queue manager

Question: We're trying to send messages from a standalone Queue manager on 1 server) to Uniform IBM Cluster (UCL) with a set of Queue managers (QM1, QM2 and QM3). on 3 different servers
================================================================
Objects created and running on Uniform cluster with a set of Queue managers (QM1, QM2 and QM3):
Listener object 1415 on all 3 queue managers, listening on all 3 servers.
A receiver channel matching sender channel name created on QM1T created on all the queue managers QM1, QM2 and QM3 of the cluster UCL.
A local queue created to hold messages on all the queue managers QM1, QM2 and QM3 of the cluster UCL.
================================================================
Objects on our stand-alone queue manager. QM1T
Sender channel with CONNAME of all the 3 hosts of queue managers and their ports.
Transmission queue associated with Sender channel.
We'll need clarity on creation of QREMOTE, specifically how we could associate a QREMOTE with all the clustered Queue managers all at once ...is there a better way to do this and avoid single point of failures ? please let us know.
DEFINE QREMOTE('TEST.UCL') DEFPSIST(YES) CLUSTER('UCL') RQMNAME(???????????????) RNAME('UCL.TEST') XMITQ('QM1.TEST.XMIT')

While I can create QREMOTE definitions like below ?  now we have multiple remote queues that stand alone queue-manger needs to deal with and multiple Remote queue managers it needs to deal with...there can be single point of failure.
Specifically, I'm looking for is there something that does like RQMNAME(ANY QM)
DEFINE QREMOTE('TEST.UCL3') DEFPSIST(YES) CLUSTER('UCL') RQMNAME('QM3') RNAME('UCL.TEST') XMITQ('QM1.TEST.XMIT')
DEFINE QREMOTE('TEST.UCL2') DEFPSIST(YES) CLUSTER('UCL') RQMNAME('QM2') RNAME('UCL.TEST') XMITQ('QM1.TEST.XMIT')
DEFINE QREMOTE('TEST.UCL1') DEFPSIST(YES) CLUSTER('UCL') RQMNAME('QM1') RNAME('UCL.TEST') XMITQ('QM1.TEST.XMIT')

Comment: Your question suggests you are creating a SENDER channel with a comma-separated CONNAME pointing to three different queue managers. Do not do this. If you need to make connections to each of three different queue managers, make three different channels, or better yet put that stand-alone queue manager into a cluster with the three target queue managers.
Comment: @MoragHughson Can you explain why using CONNAME pointing to three different queue managers is not a good idea? The alias Qmanager setup  which is suggested by JoshMc did work for our use-case. With the approach that you suggested, can the messages be directed into a single remote queue with 3 different channels in play ?
Comment: Using a conname with three IP addresses that don't point to the same target qmgr can result in the channel being indoubt to a different partner and not being able to resolve that UoW because it is now connected to another one.
Comment: If you want to do this without a cluster you will need 3 channels and 3 QREMOTEs. Then you will need some logic in your code to decide which to use.  Better off just to use a cluster
Answer: The best option would be to create an overlapping cluster that includes all four queue mangers, cluster UCL.TEST in the overlapping cluster on QM1, QM2 and QM3 then on QM1T define a QALIAS instead of a QREMOTE, this will allow the messages to be work load balanced across the three instances.

If you can only have a SDR channel from QM1T then below is another option that will work with your current channel setup with the restriction that messages will only flow initially to one of the three based on availability in the order you specify the CONNAME, but once it gets to the initial queue manger it will round robin across all of the available clusters queue instances.
First on QM1, QM2 and QM3 define the following queue manger alias to allow all three queue managers to accept messages and allow them to resolve to clustered queues:
DEFINE QREMOTE(UCL.QMA) RNAME('') RQMNAME('') XMITQ('')

Next on QM1, QM2 and QM3 cluster the QLOCAL and set CLWLUSEQ to ANY so that messages put to the clustered queue on any queue manger will round robin over all the instances:
ALTER QLOCAL(UCL.TEST) CLUSTER(UCL) CLWLUSEQ(ANY) DEFBIND(NOTFIXED)

Next on QM1T alter the QREMOTE like this:
DEFINE QREMOTE('TEST.UCL') DEFPSIST(YES) CLUSTER('') RQMNAME(UCL.QMA') RNAME('UCL.TEST') XMITQ('QM1.TEST.XMIT')

Comment: Thanks for your help on this, we're able to accomplish our need using the Queue Manager Alias. However, we have a question on workload balancing ...while the MQPUTs are distributed across queue managers cluster queues, we have a problem with reads ...Reads are happening on one queue manager while others wait.
Comment: Uniform cluster should handle ensuring you have readers spread equally across the three member queue mangers,  you would need to run at least three instances of the reader for this to work,  best practice would be to run more than three so that you can self heal if one goes down.   Since the original question was not about readers,  you should open a new question with more details on the configuration, application setup, and problems faced with readers.   If my answer was helpful please feel free to also up vote it in addition to the accept you already gave.


Find the line passing thought the point $p=(1,2,0)$, paralel to the plane...

Question: Find the line passing thought the point $p=(1,2,0)$, paralel to the plane $P=\{x,y,z \mid x+2y-z=-4\}$ and crossing the line $L=\{(x,y,z):x+2y=2, y+z=4\}$
So I've tried to put the equation of plane and insert the point, because I think that if line is paralel to the plane, then line is contained in the plane.
But I've checked, that the point don't lay in the plane, because
$x+2y-z=1+4-0=5 \neq -4$
So I'm stuck here.
-- EDIT --
Is that correct:
$x+2y-z=k\,\,\, k\in\mathbb{R}$
Intercepting point
$
\begin{cases}
x+2y=z\\
x+2y=2\\
x+z=4
\end{cases}\implies\begin{cases}
z=2\\
x=2\\
y=0
\end{cases}$
General line equation
$p_{1}-\lambda p_{2}=0 $
$(1-2\lambda,\,\,2,\,\,\,-2\lambda)$
$
x=1-2\lambda$
$y=2$
$z=-2\lambda$
So the answer is
$x=1-z$
$y=2$
Comment: You find it.${}{}{}{}$
Comment: Please have a *thorough* look at the [FAQ about homework questions](http://meta.math.stackexchange.com/questions/1803/how-to-ask-a-homework-question).
Comment: OK, I'll look now
Comment: @AlexanderGruber Fixed. I don't know how to find it
Answer: It says that the line you need to find is parallel to the given plane, not that it's on that plane.
As this is a homework problem, I'm not going to do it for you, but I will say that you've already done one step, although you may not have realised it.
There are three steps - find plane, find intercept point, construct line through points. I'll leave it to you to figure out what I'm saying from there.
Comment: How to find intercept points? I need to solve equation system with the $x+y2-z=k$ and equations for line $L$ ?
Comment: This point will be (2,0,2) ?
Comment: You need to find the plane first. You haven't done that, yet.
Comment: If at any point you think you've solved it, check if it satisfies the three conditions - does it pass through the appropriate point? Does it have an intercept with the given line? Is it parallel to the given plane?
Answer: Hint: The possible directions of your line are given by the equation
$$
x+2y-z=0
$$

Your solution isn't correct: it is true that $(1,2,0)$ is on your line, but the intersection with $L$ is empty:
$$
\begin{cases}
2+z=4\\
(1-z)+4=2
\end{cases}
$$
gives $z=2$ (first equation) and $z=3$ (second equation.

Here is one possible solution, using Cartesian equations, like yours (my hint would have provided a solution in parametric equations).
What we're going to do is find the required line as the intersection of two planes: one parallel to the given one and the other containing $L$, both passing through $P=(1,2,0)$.
For the first plane we just have to put $(1,2,0)$ in the equation $x+2y-z=k$, giving
$$
\pi_1: x+2y-z=5
$$
Now, the pencil of planes containing $L$ is simply
$$
\mathcal{F}: \lambda(x+2y-2)+\mu(y+z-4)=0
$$
thus to find the plane through $P\notin L$ we just need to substitute $(1,2,0)$
$$
\begin{gather}
\lambda(1+4-2)+\mu(2-4)=3\lambda-2\mu=0\\
3\lambda=2\mu
\end{gather}
$$
therefore our second plane is given by
$$
\pi_2:2(x+2y-2)+3(y+z-4)=2x+7y+3z-16=0
$$
hence the required line is given by
$$
R:\left\{(x,y,z):x+2y-z=5, 2x+7y+3z=16\right\}
$$
You can now check that $R\cap L\neq\varnothing$ and that $P\in R$.
Comment: So every paralel plane is described by $x+2y-z=0$?
Comment: No, every parallel plane is described by $x+2y-z=k$ with $k\in \Bbb R$ (same orthogonal direction, but passing through different points). If you are taking values in $\Bbb R$, of course.
Comment: Thanks. Could You check if I've done it correctly, in question edit?
Comment: I'm sorry but no, it isn't.
Comment: I provided a full solution in my edit.


Unable to Get Image to Un-Cache

Question: I've replaced an image on my home page with another image. I've verified that the new image is there (with the same name as the old image). And it's the only copy. I've run cron and cleared caches multiple times but the old image is still showing!
I'm using the following modules:
Advagg
Global Redirect
Cache Expiration (File update set under File Actions)
Elysia Cron
Boost
Boost Crawler
HTTPRL
Metatag
Metatag: Views
XML Sitemap
Anyone know what might be causing the problem?
Comment: have you tried clearing your browsers cache?
Comment: Are you using image styles to render the image? If so, this is probably a duplicate of http://drupal.stackexchange.com/questions/12864/rebuild-images-from-image-style
Comment: You can right click on the website and choose inspect element to check have you change your image successfully.
Comment: @FreeRadical it's not image styles because I'm just manually linking to the image from a block using the  tag.
Comment: @Geoff yes, I have. It doesn't help.
Answer: Ok, well, I don't know what the problem was. I tried everything I could think of (see above). So I just changed the name of the image in 'default/files' and changed the name of the file in the link to it in the block. Now it's showing correctly.

Unable to Get Image to Un-Cache


Different ways to understand neural networks

Question: I have come across a few main ways of understanding neural networks.

Neural networks as neurons with synapses.
Neural networks as probabilistic inference machines. (Bayes, information etc)
Neural networks as transformations on data. (similar to the matrix transforms you see in graphics)
Neural networks as aggregations of experts (also called features). (each node is some sort of expert, wisdom of crowds etc..)
Neural networks as a player in a game with nature. Where nature is an adversary trying to get the NN to make as many mistakes as possible

Are there other ways to think about what neural networks?? What are they?
Answer:
Neural networks are a generalization of regression. http://briandolhansky.com/blog/artificial-neural-networks-linear-regression-part-1
neural networks are universal function approximators (Wikipedia)
Turing Machines are Recurrent Neural Networks (http://lipas.uwasa.fi/stes/step96/step96/hyotyniemi1/)
Comment: cool. yea, of course. like parameter fitting, except for functions. and the turing thing makes sense as well, were we are considering a (R)NN as a finite state machine/automata.
Answer: Neural networks as finite approximations of continuous functions:
https://en.wikipedia.org/wiki/Universal_approximation_theorem
In short, neural networks can approximate continuous functions with arbitrary accuracy (that depends on the number of neurons) and consequently form a dense set in the space of continuous functions on any closed and bounded sets. This is tangentially related to stuff like fourier series, and polynomial approximation.


Obtaining p-values in a robustlmm mixed model via Satterthwaite-approximated DFs of the equivalent lme4 model?

Question: I've used lme4 to fit a mixed model and could obtain p-values by using the lmerTest or afex packages. However due to heteroskedasticity (Levene Test) I also fit a robust model (rlmer command in the robustlmm package). Unfortunately lmerTest and afex do not work with rlmerMod objects. So I was looking for other ways to obtain p-values.
Doing some online-research I found the recent publication by Geniole et al. (2019) and they used the Satterthwaite-approximated degrees of freedom generated by the lme4 model in combination with the output of the robustlmm model to obtain p-values for the robust model (see their Supplemental Material).
As the the summary of the rlmer model gives me a t-value I could calculate the p-values for the robust model with the help of the Dfs from the non-robust model via the following formula:
p.value.robust = 2*pt(abs(t.value.robust), Satterthwaithe.DF.non.robust, lower=FALSE)
Is that a correct way to do this? Do you know other ways to calculate p-values for the robust model?
Literature:
Geniole Shawn N., Proietti Valentina, Bird Brian M., Ortiz Triana L., Bonin Pierre L., Goldfarb Bernard, Watson Neil V. and Carré Justin M. 2019. Testosterone reduces the threat premium in competitive resource division. 286. Proceedings of the Royal Society B. http://doi.org/10.1098/rspb.2019.0720
Answer: I'm going to answer that myself in case that others may be interested at some point. In the end I did follow the approach mentioned above. The code would look like this:
<code>library(lme4)
library(robustlmm)

data(Dyestuff, package = "lme4")

# fit a mixed model
model <- lmer(Yield ~ 1|Batch, data=Dyestuff)
# fit the robust equivalent
robust.model <- rlmer(Yield ~ 1|Batch, data=Dyestuff)

# get coefficients from non-robust model to extract Satterthwaite approximated DFs
coefs <- data.frame(coef(summary(model)))

# get coefficients from robust model to extract t-values
coefs.robust <- coef(summary(robust.model))

# calculate p-values based on robust t-values and non-robust approx. DFs
p.values <- 2*pt(abs(coefs.robust[,3]), coefs$df, lower=FALSE)
p.values
</code>
Comment: You need `lmerTest` packages. Typical `lmer` packages does not output degrees of freedom. After `library(lmerTest)`, use `coef(summary(model))` again.
Comment: Thanks for sharing!!!
Comment: I have a doubt. When I run `coefs$df` I get `NULL`. I guess it should be `coefs[1,3]` instead of `coefs$df` to extract the `t- value` from `coefs`, right?
Comment: This is odd. You can run `coefs` to see the columns names. In my case the third column is called "df" so, `coefs$df` is equivalent to `coefs[1,3]`. Which command you use doesn't really matter as long as you access the correct column including the dfs.
Answer: I would like to add for future reference, that the tab_model function of sjPlot package can also calculate p values based on Satterthwaite-approximated dfs.
Comment: That's awesome, thanks for sharing this information!


Is there a non-constant polynomial such that...

Question:
Is there a non-constant polynomial $p$ with positive coefficients such that function $ x \mapsto p(x^2) - p(x)$ is decreasing on the interval $[1,+\infty)$?

This was a question from the last year's math analysis exam. The answer was the following:

For $1\le x \lt y$ and $n \in \Bbb N $ we have $y^{2n}-x^{2n} = (y^n+x^n)(y^n-x^n) > y^n - x^n$, so $ x \mapsto p(x^2)-p(x)$ is strictly increasing function on $[1,+\infty)$, for every $n \in \Bbb N$. Because polynomial p has positive coefficients and is not constant, such function does not exist.

I have only recently started this class so I have hard times wrapping my head around this. Why is $y^{2n} - x^{2n}$ used to prove that the function is increasing? Why does this ($y^{2n}-x^{2n} > y^n - x^n$) mean that the function is increasing?
Does it mean that $p(y^{2n})-p(x^{2n}) > p(y)-p(x)$ so that means  $p(y^{2n}) - p(y)- (p(x^{2n})- p(x))>0$ or something like this?
If somebody could just explain the answer, it would be much appreciated!
Comment: The answer is a bit unclear, but it is suggesting that you first try the case when $p(x)=x^n$ and look at $p(y^2)-p(y)- (p(x^2)-p(x))$ for $y>x$. Their argument shows that this is positive, so the function $p(x^2)-p(x)$ is increasing.  Now you use the fact that if $f$ and $g$ are increasing and $a,b\geq 0$ then $af+bg$ is increasing too to get the result for any polynomial $p$ with positive coefficients.
Answer: Say $p(x)=ax^n+...$ and $a\ne 0$, $n\geq 1$.  Then $$f(x) = p(x^2)-p(x)=ax^{2n}+...$$ Since
$f(x)\sim ax^{2n}$ for $x\to \infty$ we see that $a<0$ since it is decreasing. So it is impossible.
Comment: This argument is perfectly valid for polynomials. To elaborate just a bit further, $f(x) = ax^{2n} + g(x)$ where $g$ is a polynomial of degree at most $2n-1$. Then $f'(x) = 2nax^{2n-1}(1 + \frac{g'(x)}{x^{2n-1}})$. Since $\frac{g'(x)}{x^{2n-1}} \to 0$ as $x \to \infty$, we obtain $f'(x) > 0$ for sufficiently large $x$. This is true as long as the leading coefficient of $p$ is positive. The answer given to the OP is (a) complicated and (b) uses assumptions that may be relaxed, hence it is less than optimal.
Comment: Why is this down voted? Is it to simple argument to be true?
Answer: Okay so I think I got it, but I'm still not sure.
Let's say that $f(x)= p(x^2)-p(x)$. If this function is decreasing on the interval $[1, +\infty)$, that means that if $1\le x < y$, then  $f(x) > f(y)$, that is, $f(x)-(fy) >0$.
$$f(x)-f(y) >0 $$
$$p(x^2)-p(x) -p(y^2)+p(y)>0 $$
$$a_nx^{2n}+...+a_1x^2 + a_0 -a_nx^n-...-a_1x-a_0 - (a_ny^{2n}+...+a_1y^2 + a_0 -a_ny^n-...-a_1y-a_0)>0 $$
$$a_n(x^{2n}-y^{2n}-(x^n-y^n))+...+a_1(x^2-y^2-(x-y))>0$$
Then I just prove that $x^{2n}-y^{2n}-(x^n-y^n)<0$, for $1\le x < y$. And,
because $a_i$ are all positive, this function cannot be decreasing.
I'm pretty sure that this is the proof from the answer. Still, thanks for help, everybody!


How to programmatically set permissions for a custom content type created in a module?

Question: I have a module which creates a node type as part of hook_install. I want to be able to automatically set permission to authenticated users to create nodes.
I have tried the following code:
 /**
  * Implements hook_enable().
  */
function my_module_enable() {
  $permissions = array('create my_module_content_type content');
  user_role_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}

But I receive this error.
Notice: Undefined index: create my_module_content_type content in user_role_grant_permissions() (line 3111 of ...

If I delete the two lines of code, the module installs fine. And when I run those 2 lines of code in an "execute PHP" window after install, they work as desired.
I believe hook_install should execute before hook_enable so the content type should exist when hook_enable is run. Are permissions defined later? Thoughts on how to handle this?
Comment: Make sure you have defined this permission in a hook_permission (or hook_perm for Drupal 6) as well.
Comment: Ah, I didn't make clear. My module's hook_install creates "my_module_content_type". As part of that, I think the content module automatically creates the permission. (The two lines of code do run fine if I run them manually after the module is enabled.)
Comment: For which version of drupal is this?
Answer: The problem is that the user_permission_get_modules function fails to get the permissions at the point of install (too early in the process, not all the caches have been reset). So you would have to copy the user_role_grant_permissions function to your new module, it should look something like this:
/**
 * Custom user_role_grant_permissions function
 * does the same thing as user_role_grant_permissions
 * but it can run at install time
 * @see user_role_grant_permissions
 * @param int $rid
 * @param array $permissions
 */
function _my_module_grant_permissions($rid, array $permissions = array()) {
    // this line doesn't work on install / enable hooks
    // $modules = user_permission_get_modules();
    // Grant new permissions for the role.
    foreach ($permissions as $module => $permission_list) {
    foreach ($permission_list as $name) {
        db_merge('role_permission')
        ->key(array(
            'rid' => $rid,
            'permission' => $name,
        ))
        ->fields(array(
            'module' => $module,
        ))
        ->execute();
    }
    }

    // Clear the user access cache.
    drupal_static_reset('user_access');
    drupal_static_reset('user_role_permissions');
}

This is slightly different than the user_role_grant_permissions module in that the permissions are keyed to the module, so you call it like this:
function my_module_enable(){
    $permissions = array(
        // module key
        'my_module' => array(
           // permissions in the module
           'do module things',
           'modify module things',
        ),
    );
    _my_module_grant_permissions(DRUPAL_AUTHENTICATED_RID, $permissions);
}

Answer: Not all functions are available in the install file.
You will need to look at the code user_role_grant_permissions and probably copy the database statement into your hook_enable, also remember to remove it in hook_disable


Headers in SignalR response

Question: I am writing an application using SignalR which acts as a push service of resources for clients. The service sends notifications to its clients regarding state change of resources at regular intervals. Sometimes, the resource state remains the same. In such cases I need a way to convey the same to clients without sending the same resource again. In a way, I want to implement something like ETags with SignalR. To do that I need to modify SignalR response headers (or I could use query string).
Is there a way to do this?
Answer: you are saying to pass the same state to clients (But with NOT MODIFIED kind of header) as well not to pass if it is same.
In such case you should actually not pass any message to the clients if the server hasn't anything new to give to the clients. This is how realtime applications are supposed to work.
Also instead of adding an overhead of extra HEADERS why don't you just send a simple actual signalR ping to the clients saying "Hey, nothing modified. Just chill!"

Headers in SignalR response


String padding not taking up the same character spacing

Question: I am using padding in my UITableViewSource to format a cell. I have:
//cell declared somewhere in `UITableViewSource`

var name = rows[indexPath.Row].MachineName.PadRight(50);
I have tried this as well:
var name = rows[indexPath.Row].MachineName.PadRight(50, ' ');
I have some set the cell text:
cell.TextLabel.Text = "01234567" + " " + name + "01234567";
The output looks like:
01234567 SomeNameHere           01234567
-------------------------------------------
01234567 SomeNameHere           01234567
--------------------------------------------
01234567 SomeOtherNameHere         01234567
--------------------------------------------
01234567 ShortName            01234567
---------------------------------------------

I have checked the length of name and all of them are 50 but when its shown on my device in the cell it doesn't line up. Is there something special with Xamarin, iOS, UITableViewCell - something that may be different.
My work around for this would be to create a UITableViewCell using XCode but it would be nice if this could work.
Comment: By default, it is not using a Monospaced font.
Comment: Yes, use a monospaced font.  However, if you are trying to align data in columns, using a custom cell with individual labels is probably a better approach.  You could also try the tab spacing trick that Lawrence suggests.
Comment: @jharr100: I just found this: http://stackoverflow.com/a/18926262/1187415 . You can create an "attributed string" with tab stops.
Comment: One solution would be to use separate labels for each column
Comment: @MartinR Thats what I was thinking I would do if I couldn't get around this another way
Answer: Try:
var name = rows[indexPath.Row].MachineName.PadRight(10, '\t');

Comment: no this produces something that looks like            `01234567 SomeNameHere01234567`
Comment: Well, try changing it to a bigger count than 4. Maybe 10 or 12?
Comment: this isn't working...adding additional tabs worked for spacing but the alignment is still off
Answer: I ended up using a monospaced font as suggested by @Jason and it seems Courier New is the only one available in iOS just from my quick search.


Rails Routing: can't get helper route function to work

Question: I cannot figure out the magic to getting helper path's to work. My use case is this: "mydomain/articles/some_slug" to use to articles controller with the show action. The URL as given works perfectly. But I can't figure out how to make rails' helpers work for this case.
routes.rb:
  get '/articles/:slug',    to: 'articles#show', as: 'article'

   --- or ---

  get '/articles/:slug',    to: 'articles#show'

   --- or changing :slug to :id

rails routes (this and similar variations with other --- or --- conditions):
  articles GET    /articles/:slug(.:format)                 articles#show

I get an undefined method `path_to_article' error. This error occurs under these conditions:
my.html.erb:
  <%= path_to_article(locals[:article]) %>

   --- or ---

  <%= path_to_article(id: locals[:article].slug) %>

   --- or ---

  <%= path_to_article(slug: locals[:article].slug) %>

However, this code works fine, but I don't like it and this is exactly what I am trying to avoid:
<a href="/articles/<%= locals[:article].slug %>">

I have also tried with plural and non-plurarl combinations where I could and practically any other random ideas I could come up with or find online. In the end, I can't seem to figure out how to get rails to recognized 'path_to_article()'.
Rails 5.0.2
Thanks for your help!
Answer: You want to use:
articles_path(locals[:article])

or
articles_path(locals[:article].slug)

depending on how you have things set up
Answer: rails routes

returns :

The route name (if any)
The HTTP verb used (if the route doesn't respond to all verbs)
The URL pattern to match
The routing parameters for the route

see:
http://guides.rubyonrails.org/routing.html#listing-existing-routes

Basically, you should append _path to the route name in your views to call the routes helper.
In your case, the route name is articles so the helper method is articles_path.
Comment: I have had that guide open today and, well, I guess that I have spent too much time on small details and I'm missing obvious things. I was so hung up on the path_to_xxx that I had tunnel vision. Thanks for your help.


how to share odt/doc documents over git

Question: The idea is that I want to share and track documents over git
I thought about using Text Documents (markdown docs that look like docx,odt in functionality) that can be edited with any text editor (not binary). Where to find something like this?
any better solution?
Comment: is there any way to zip/unzip those files when using git commands ?
my problem is that git sees those files as binary (because they're zipped)
when conflict happens ,i can't resolve it any way !! :(
Comment: @LazyBadger: that's not 100% true. ODT is zipped XML...
Comment: @eckes: When zip became text? Did I miss something?
Comment: I also would be happy to see a git hook or workaround to make git recognize archives (and to be able to work with them as directories).
Answer: LaTeX is perfect for combining it for git. But if you cannot afford yourself the time to "translate" all to LaTeX, I think a great option that fits your needs is using LibreOffice and saving files in .fodt format (Open Document Text - Flat XML). These files are uncompressed XML, so you can use all the power of git as you can see addition and changes to the document line per line.
This will make merging an easy task. Even binaries (e.g. when you include an image) will be embedded in the document and shown as text. Of course you cannot manipulate them from there but you can remove the whole tag or edit attributes with the simplest text editor.
Comment: This actually answers the question best. Recommending alternatives (like LaTex) is fine, but this shows an easy workaround that does not require installing additional software (for diffs) and thus also works on repository hosting platforms like GitHub or GitLab.
Comment: Sadly, using this method, the file size increases a lot. One of my files, from 10 MB to 200 MB.
Answer: There are two tools which can be used to let git diff odt files: odt2txt and oodiff.
See this resource for details on how to set this up (also includes information on Mercurial and SVN.)
Snippet of above instructions (for git >= 1.6.1):

First, install odt2txt, and configure git to allow it to run it, by adding this to ~/.gitconfig:
[diff "odf"]
      textconv=odt2txt

Now, for each project, you just need to ask git to use this driver in .gitattributes or $GIT_DIR/info/attributes, like this:
*.ods diff=odf
*.odt diff=odf
*.odp diff=odf

Comment: You can add .odm files too. Versining is useful when you have multiple odt files, that are merged into one .odm.
Answer: Have you considered using LaTeX instead of doc or odt?
This way you can edit the documents with any text editor and get good looking results. Better yet: you have proper diffs between revisions (no matter the SCM you use).
If you don't like the idea of editing the document in a simple text editor take a look at LyX. It provides a gui for editing documents like you would get in normal document editors.
For git hosting solutions you can use:

github (if your documents are open-source, which I don't think)
bitbucket (offers unlimited repositories, with unlimited space and up to 5 users for project)
Comment: but any other tool won't understand LateX !! they will see it as complex text that i can't understand to merge ,is there any way to set the Lyx compare tool as the merge tool ?
Comment: Well, someone can find Markdown more appropriate for simple use-cases... Just a note.
Comment: is it easy to merge conflicts in Lyx ?
Comment: @MhdSyrwan: I would suggest you to use a specialized merge tool. For example I use: **p4merge** (from Perforce). More info in this question: http://stackoverflow.com/questions/426026/git-on-windows-how-do-you-set-up-a-mergetool
Comment: I haven't used LyX myself so I can't give you to many details related to it. As far as I know, p4merge will show you the content as text (not rich content).
Answer: You can use LaTeX for text documents with format (or rtf, Rich Text File, if you prefer a method accesible to anyone), and fods for spreadsheets.

how to share odt/doc documents over git


Protobuf import doesn't work, I've used the proto_path

Question: Here's my directory structure:
protobuf
├── commons.proto
└── operations.proto

Code in operations.proto:
syntax = "proto3";
import "commons.proto";

option java_multiple_files = true;
package tw.waterballsa.protobuf.operations;

message PlayerEnterSceneOperation {
  PlayerAppearance appearance = 1;
}

Code in commons.proto:
syntax = "proto3";

package tw.waterballsa.protobuf.commons;

message PlayerAppearance {
  int32 hair = 1;
  int32 skin = 2;
  int32 eyes = 3;
  int32 nose = 4;
  int32 mouth = 5;
  int32 shirt = 6;
  int32 pants = 7;
  int32 shoes = 8;
}

My compile command: protoc --proto_path=protobuf --java_out=<...> protobuf/operations.proto
The result (error message):
operations.proto:8:3: "PlayerAppearance" is not defined.

What's wrong?
Answer: It's confusing.
Here's the solution.
Represent your files using the following structure to correctly repreresent your proto_buf root (protobuf) and your protobuf sources packages name (tw.waterballsa.protobuf.[commons|operations]) converted to a folder strucutre.
.
└── protobuf
    └── tw
        └── waterballsa
            └── protobuf
                ├── commons
                │   └── commons.proto
                └── operations
                    └── operations.proto

In operations.proto, you must preserve the package reference in the fully qualified name for PlayerAppearance:
syntax = "proto3";

package tw.waterballsa.protobuf.operations;

// Fully-qualified path to 'commons.proto'
import "tw/waterballsa/protobuf/commons/commons.proto";

option java_multiple_files = true;

message PlayerEnterSceneOperation {
  // Fully-qualified path to `PlayerAppearance'
  tw.waterballsa.protobuf.commons.PlayerAppearance appearance = 1;
}

And then:
PROTO_PATH_1="${PWD}/protobuf"

protoc \
--proto_path=${PROTO_PATH_1} \
--java_out=. \
${PROTO_PATH_1}/tw/waterballsa/protobuf/operations/operations.proto \
${PROTO_PATH_1}/tw/waterballsa/protobuf/commons/commons.proto

NOTE Formally, every protobuf source (*.proto) should be prefixed by one of the proto_path path values. I'm using PROTO_PATH_1 here to make this clear.

There are two important paths.
The first is the package paths.
When you define proto_path, you specify the root (host) folder that represents the hierarchy of protobuf package references.
In this case, there's a single proto_path root folder ${PWD}/protobuf.
The second is the output|generated|host paths. These are often similar too but need not be identical to the protobuf package references.
The above protoc (which compiles commons.proto too) yields:
.
├── protobuf
│   └── tw
│       └── waterballsa
│           └── protobuf
│               ├── commons
│               │   └── commons.proto
│               └── operations
│                   └── operations.proto
├── README.md
└── tw
    └── waterballsa
        └── protobuf
            ├── commons
            │   └── Commons.java
            └── operations
                ├── Operations.java
                ├── PlayerEnterSceneOperation.java
                └── PlayerEnterSceneOperationOrBuilder.java

Comment: Thanks. You are right. A Fully-qualified path works.
use tw.waterballsa.protobuf.commons.PlayerAppearance, instead of PlayerAppearance


Python: nlst error. Empty directory

Question: I have a code which downloads zip files from a ftp server. When I try to catch files on an empty directory, the code fails.
It works fine when I have files in the directory.
These errors appears when the directory is empty.
File "/usr/lib/python2.5/ftplib.py", line 459, in nlst
    self.retrlines(cmd, files.append)
  File "/usr/lib/python2.5/ftplib.py", line 421, in retrlines
    return self.voidresp()
  File "/usr/lib/python2.5/ftplib.py", line 221, in voidresp
    resp = self.getresp()
  File "/usr/lib/python2.5/ftplib.py", line 216, in getresp
    raise error_perm, resp
ftplib.error_perm: 550 No files found.

I tried to fix this error with the next code, but it doesn't work. It keeps happening.
If somebody can help me with a solution, I'd appreciate it
CODE
try:
    fileList = s.nlst()
except ftplib.error_perm, resp:
    if str(resp) == '550 No files found':
        print 'Directory is empty.'
else:
    raise

which still results in
File "/root/folder/ftp.py", line 151, in download fileList = s.nlst()
File "/usr/lib/python2.5/ftplib.py", line 459, in nlst self.retrlines(cmd, files.append)
File "/usr/lib/python2.5/ftplib.py", line 421, in retrlines return self.voidresp()
File "/usr/lib/python2.5/ftplib.py", line 221, in voidresp resp = self.getresp()
File "/usr/lib/python2.5/ftplib.py", line 216, in getresp raise error_perm, resp
ftplib.error_perm: 550 No files found.

Comment: have a similar problem, looks like the behaviour is differently pn different ftp server implementations. See https://support.microsoft.com/en-us/kb/2383827 for example.
Comment: The fix looks reasonable (other than that the indentation here is wrong); can you show the *full* traceback when the error happens using your updated code?
Comment: the indentation was placed by stackoverflow. Nothing to do, or wouldn't let me post.
Comment: File "/root/folder/ftp.py", line 151, in download
    fileList = s.nlst()
File "/usr/lib/python2.5/ftplib.py", line 459, in nlst
    self.retrlines(cmd, files.append)
File "/usr/lib/python2.5/ftplib.py", line 421, in retrlines
    return self.voidresp()
File "/usr/lib/python2.5/ftplib.py", line 221, in voidresp
    resp = self.getresp()
File "/usr/lib/python2.5/ftplib.py", line 216, in getresp
    raise error_perm, resp
ftplib.error_perm: 550 No files found.
Comment: Have you tried with normal ftp on the command line? It may simply be an permission problem, that is, you don't have access to view that directory (in which case, the error message is somewhat deceiving).
Comment: I have access, it is not a permission problem :/
Answer: I know this is dead but I found this because I had the same problem. Here is the workaround I used:
def handle_folders(item):

    global fldrs
    temp = item.split()
    if item.startswith('d') and temp[4] != "512":
        fldrs.append(myFldr + item[54:] + "/")

ftp.cwd(myFldr)
ftp.retrlines('LIST', handle_folders)
setupDir = fldrs

where myFldr is the path and you filter out anything that isnt a folder and any empty ones. Elsewhere in my code I iterate through setupDir and use ftp.nlst() to get a list of files, though you could also use retrlines to get that list.

Python: nlst error. Empty directory


Sleep seems to run first in bash script

Question: I need to terminate a script if it exceeds a specific duration (10 mins)
examplescript.sh &
pid=$!
sleep 600
if ['pgrep $pid']
  then
    kill $pid
fi

When I tested it on my test environment, it seems working well. examplescript.sh runs first and if it runs for more than 10 mins, it will be terminated. However, when I tried in our production environment, it seems that sleep runs first. It waits 600s before running the examplescript.sh. Is there something wrong in the script?
Comment: There is a problem with the script you posted, but it has nothing to do with `sleep` running before `examplescript.sh` starts (which should be impossible). See shellcheck.net.
Answer: There is multiply thing you should correct in your code.
pgrep will make a regex search on process names not pids. You can use kill -0 pid to check if a process with pid is running.
[ (test) is a command[1] and should be treated as one. That means each argument should be separated by spaces. When using [ the last argument should also be ]:
[ arg1 arg2 ]

In your example you wont need [ since kill -0 will exit truly if the process is still running:
if kill -0 pid; then

And to wrap it up:
examplescript.sh &
pid=$!
sleep 600
if kill -0 "$pid" 2> /dev/null; then
    kill "$pid"
fi

kill -0 will write an error to stderr if the process is not running anymore. So we redirect that to /dev/null.
[1] It's usually a build-in these days.
Another thing to note is that your script will run for 600 seconds even though examplescript.sh will only take a few seconds to run.
Comment: Another thing to note is that your script will run for 600 seconds even though examplescript.sh will only take a few seconds to run.    -how can I run the kill only if it exceeds for 10 mins without using sleep?
Comment: @noobLadyTea *your script* as in the script that sleeps for 600 second.
Answer: Are your production machines significantly faster? I do not have example script to really run this on my machine, but I think your problem might be solved if you take the code you mention above
examplescript.sh &
pid=$!
sleep 600
if ['pgrep $pid']
   then
     kill $pid
fi

put it in a file called, say,  monitor.sh and run that file in the background. i.e.
monitor.sh &

Hope this helps.

Sleep seems to run first in bash script


How to I pass the data back to the main function for yielding?

Question: I am a beginner in python programming with the scrapy library. I want to yield the birth_date in the same output with the main output that have title, author, and etc. However, without a success, I couldn't get the result to be shown.
import scrapy

class QuotespiderSpider(scrapy.Spider):
    name = "quotespider"
    allowed_domains = ["quotes.toscrape.com"]
    start_urls = ["https://quotes.toscrape.com"]

    def parse(self, response):
        quotes = response.css(".quote")
        all_url_tags = quotes.css(".tags a.tag::attr(href)").getall()

        for quote in quotes:
            url_tags = []
            tags = (quote.css(".tags meta.keywords::attr(content)").get()).split(',')
            url_tags = [j for i in tags for j in all_url_tags if i in j] #append only the neccesary url_tags

            url_author = quote.css("span a::attr(href)").get()
            author_page = "https://quotes.toscrape.com/" + url_author

            items = {
                'title' : quote.css("span.text::text").get(),
                'author' : quote.css("span small.author::text").get(),
                'url_author' : quote.css("span a::attr(href)").get(),
                'tags' : tags,
                'url_tags' : url_tags
                }

            #Goes to the page to scrape the author's date of birth
            yield scrapy.Request(url=author_page, callback=self.parse_author_page, meta={'items':items})

            yield items

        next_page = response.css("li.next a::attr(href)").get()

        if next_page is not None:
            next_page_url = "https://quotes.toscrape.com/" + next_page
            yield response.follow(next_page_url, callback=self.parse)

    def parse_author_page(self, response):
        items = response.meta['items']

        birth_date = response.css(".author-details p span.author-born-date::text").get()
        items['birth_date'] = birth_date

        return items

These are some of the outputs:
{"title": ""The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking."", "author": "Albert Einstein", "url_author": "/author/Albert-Einstein", "tags": ["change", "deep-thoughts", "thinking", "world"], "url_tags": ["/tag/change/page/1/", "/tag/deep-thoughts/page/1/", "/tag/thinking/page/1/", "/tag/world/page/1/"]},

{"title": ""It is our choices, Harry, that show what we truly are, far more than our abilities."", "author": "J.K. Rowling", "url_author": "/author/J-K-Rowling", "tags": ["abilities", "choices"], "url_tags": ["/tag/abilities/page/1/", "/tag/choices/page/1/"]},

{"title": ""There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle."", "author": "Albert Einstein", "url_author": "/author/Albert-Einstein", "tags": ["inspirational", "life", "live", "miracle", "miracles"], "url_tags": ["/tag/inspirational/page/1/", "/tag/inspirational/page/1/", "/tag/inspirational/page/1/", "/tag/life/page/1/", "/tag/life/page/1/", "/tag/live/page/1/", "/tag/miracle/page/1/", "/tag/miracles/page/1/", "/tag/miracles/page/1/"]},

I want to yield the dict in the main function of parse however, I couldn't get the birth_date to be added to the items in the output.
Thank you in advance for your kindness.
Comment: I'm not expert in Scrapy but it seems that the *parse()* override is not meant to be a generator
Comment: Just yield the dict in `parse_author_page` instead of returning it.
Answer: You should just remove the yield items from the parse method. If you analyze the logs of your scraped items you are going to see duplicated items. You are yielding items without birth_date in the parse method and then returning the same item with birth_date in the parse_author_page. Removing the yield items from the parse method will make your spider behave the way you want.


Tkinter new windows won't close properly

Question: I want my GUI to have a 'new window' option that will be just the same as the first one.
The problem is that it also has an exit(quit) button that won't work as it should - whenever I open the new window and then press the button, in the first click nothing happens and in the second one it closes both windows (if 3 windows are open so it'll close everything in the third click and so on).
This the relevant code:
from Tkinter import *
from ttk import *

class Application(Tk):
    def __init__(self):
        self.root = Tk()
        self.root.geometry("250x150")
        self.app = Frame(self.root)
        self.app.grid()
        self.create_menu()
        self.create_widgets()
        self.root.mainloop()

    def create_menu(self):
        menu = Menu(self.root)
        self.root.config(menu=menu)
        sub_menu = Menu(menu)
        menu.add_cascade(label="File", menu=sub_menu)
        sub_menu.add_command(label="New", command=self.__init__)
        sub_menu.add_command(label="Run", command=self.enter)
        sub_menu.add_separator()
        sub_menu.add_command(label="Exit", command=self.app.quit)

I also tried to change:
sub_menu.add_command(label="New", command=self.__init__)

to:
sub_menu.add_command(label="New", command=self.new window)

Where:
def new_window(self):
    class App(Application):
        Application.__init__(self)

Both do the same thing.
How can I fix it?
Answer: In a Tkinter-Application there may only be one Tk-object. If the object is destroyed or destroyed by the garbage collector, Tkinter will be disabled. Use Toplevel for other other windows instead.
Try this instead:
from Tkinter import *
from ttk import *

class Application(object):
    def __init__(self, master):
        self.root = master
        self.root.geometry("250x150")
        self.app = Frame(self.root)
        self.app.grid()
        self.create_menu()
        self.create_widgets()

    def create_menu(self):
        menu = Menu(self.root)
        self.root.config(menu=menu)
        sub_menu = Menu(menu)
        menu.add_cascade(label="File", menu=sub_menu)
        sub_menu.add_command(label="New", command=self.new)
        sub_menu.add_command(label="Run", command=self.enter)
        sub_menu.add_separator()
        sub_menu.add_command(label="Exit", command=self.quit)

    def new(self):
        window = Toplevel(tk)
        return Application(window)

    def quit(self):
        tk.destroy()

tk = Tk()
Application(tk)
tk.mainloop()

Comment: _"If the object is dereferenced Tkinter will be disabled"_ - that is not an entirely true statement. You can dereference it, you just can't destroy it or let the garbage collector destroy it.  If the `Tk` instance lives in the global scope, it can be dereferenced without it being destroyed.


How to style the elements dynamic in iteration?

Question: How to style the elements dynamic in iteration
In test.phtml page
<?php foreach($tests => $test) { ?>
    <li class="<?php echo $test['class'] ?>">

        Test Instance

<?php } ?>

Style tags are coming in page.

        Test Instance

But, these style have no effect in webpage.
Please help me to solve this problem...
Answer: You should define internal styles in the head-section of the htmldocument. Visit http://www.w3schools.com/css/css_howto.asp.
You could use your loop to define variables both for the head-section and the later markup and echo them at the right position.
Comment: Though as a note to you, w3schools should -never- be used as a reference.  Although I myself have learned things from it, it propagates wrong actions and what-not.  Please see [w3fools.com](http://www.w3fools.com).
Comment: I am using zend framework, looping in head-section, not looks good one to me. Thanks for information. Any other suggestions ?
Answer: You can use inline style tag like this.
<li style="color:<?php echo $test['color']; ?>;background-color: <?php echo $test['bgColor'] ?>;">Test

I have modify your code check it.
 <?php foreach($tests => $test) { ?>

        <li class="<?php echo $test['class'] ?>">

            Test Instance

    <?php } ?>


php css/js minifier?

Question: I have a custom loader for my css and javascript functions.
as such.
when I am ready I have a list of css and another of javascript files.
I am looking for a way that I can then call a function and it will output a path to a compressed and combined css and js file.
so.
something like
<code>load::css('master');
load::css('links');
load::css('buttons');
load::css();
</code>
(calling load:css() without any params should generate the minified css link)
What classes do you suggest for doing this?
Answer: It doesn't work quite the way you want, but I've found it pretty useful to use minify (http://code.google.com/p/minify/), then have a separate class (I use Zend Framework's headStyle view helper) collect all the css files I need, then build a single css/JS link that I include.
Comment: Yeah, I was looking at that, however My issue comes as, almost every page on my site uses a different combination of css and javascript files, hence, normally averaging 7 files each. I am hoping to be able to just call a minify class, and it would generate me a css/js file name based on the files. it would use some sort of alogrithm to ensure that the filename is based off the file contents and, if the js/css file exists, return is, else, create it then return it.
Comment: I had something that was pretty similar. The way minify works is that you can include a url that's something like http://yoursite.com/minify/?foo.css,bar.css,foobar.css as your CSS, and it will generate a minified CSS file. I had around 15 files, and it got pretty slow, but it might do the trick.
Answer: I wrote a "build" shell script for javascript and css, which I the javascript from the server, and then compress it using YUICompressor.
This wouldn't be a run-time compression like you're looking for, it'd be more of a one-time build process you do when you publish your site. My javascript is mostly static, though, so I can get away with this.
<code>#!/bin/bash
cd /webroot/js
wget -nc -O filename.premin.js http://localhost/js/filename.src.js
java -jar yuicompressor.jar --line-break=200 -o filename.min.js filename.src.js
rm filename.premin.js
</code>
Answer: If I understood your aim correctly Php Speedy may help you. Check it out: http://aciddrop.com/php-speedy/ .
Answer: It sounds like the problem you're trying to solve is that you have "too many" JS/CSS files being served.
By looking for a way to merge them together, you're only compounding your problem by inventing new files that must be delivered to your clients.
Instead, learn about HTTP caching, and use it: http://www.mnot.net/cache_docs/

php css/js minifier?


How do quickly switch dagster from running with test data and the full data?

Question: I have a Dagster project where I like to test it with a small subset of data (eg. I run it daily with a list of 10,000 users). This is helpful at catching issues before kicking of a "big" job.
Currently I have a software defined asset called userIds which I modify between runs:
@asset
def userIds():
    userIds = get_user_ids_from_database()
    # return userIds
    return userIds[:10_000]

But this is probably not how it should be done.
What is the best way to switch the config of an asset in Dagster?
Answer: Have a look at the configuration docs. The gist is that you can provide a configuration schema which defines variables that you can enter values for when launching a run. In your case it might look something like this:
from dagster import Field, asset

@asset(config_schema={"number_of_users": Field(int, is_required=False)})
def userIds(context):
    userIds = get_user_ids_from_database()
    # return userIds
    number_of_users = context.op_config.get("number_of_users")
    if number_of_users:
        return userIds[:number_of_users]
    else:
        return userIds

(note: the context variable is injected for you by the Dagster framework if you define it as the first parameter to your op/asset)
The configuration can then be provided in any of the contexts in which you might run the asset (these execution docs have some examples of providing runtime configuration via config schemas). For instance, in this case you might execute the asset programmatically like this:
from dagster import materialize

asset_result = materialize(
    [userIds],
    run_config={
        "ops": {"userIds": {"config": {"number_of_users": 10000}}}
    },
)


How to add a UI to a WiX 3 installer?

Question: I've tried <UIRef Id="WixUI_Minimal" />, but I get "Unresolved reference to symbol WixUI:WixUIMinimal". What am I doing wrong?
Answer: The wixui extension is no longer wixui.wixlib. It was rolled into the WixUIExtension.
If you are on the command line, add -ext WixUIExtension to the call to light.exe.
If you have a WiX project in Visual Studio, add a reference to "WixUIExtension" by right clicking on "References" in the Solution Explorer.
See the WiXUI Dialog Sets page for WIX3.
Comment: If anybody's wondering where the dll is, it should be in `C:\Program Files (x64)\WiX Toolset [version]\bin\ `.
Comment: Why they've decided not to include any Visual Studio instruction on that documentation page is beyond me.
Comment: For your 2017 question, you are probably using NuGet to fetch the WixInstaller.  If so, the location of the DLL is your solution folder\packages\Wix\tools\WixUIExtension.dll.  I'm adding all this to my MSI project (not the EXE bundle).  It compiles.  LOL
Comment: FWIW you need to add the DLL reference to the Wix project in your solution.
Answer: If you use the .wixproj directly via MSBuild, without Visual Studio, the required modification is to add this:
<Project ...>
  ...
  <ItemGroup>
    <WixExtension Include="WixUIExtension">
      <HintPath>$(WixToolPath)WixUIExtension.dll</HintPath>
      <Name>WixUIExtension</Name>
    </WixExtension>
  </ItemGroup>
  ...
</Project>

Comment: You can insert this code snippet also with **Visual Studio**. ... **unload the project** in the project explorer with right-click to the project name. Then make **double click** to the project name. The `*.wixproj` file opens and you **can edit** it. After saving reload the project and you are done.
Answer: See Re: (WiX-users) How to get off the ground with WixUI_Minimal?
Answer: Below is a link to a good example on how to custimize the WixUIExtensions.
Customised UIs for Wix
Answer: You need to add reference of WixUIExtension in your WIX project to resolve this issue.

How to add a UI to a WiX 3 installer?


Keep attempting urlopen until a connection is established - Python 2

Question: I'm having a problem with my program freezing, I think it is due to no connection to the Poloniex server. How do I keep looping the urlopen request until a connection is established?
Here is what I have:
elif(command == "returnOrderBook"):
    try:
        ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'])))
        return json.loads(ret.read())
    except:
        print('no connection')
    else: return None

And in the main:
jsn = None

count = 0;
for pair in pairs:

    while(jsn == None):
        jsn = p.returnMarketTradeHistory (pair)
        if(jsn == None):
            print('jsn failed')
            sleep(0.3)

I have checked the timings and I don't seem to be breaking any excessive data request limits from Poloniex.
Comment: I'm having the same problem now, if I can come up with anything I'll post an answer here......
Answer: This seems to be working for me.  I increased the wait times so that it won't just bombard the site until the IP gets banned.
    wait = 60
    while True:
        try:
            html = urlopen('http://www.example.com')
            wait = 60
            break
        except:
            print('Failed to open page')
            time.sleep(random.sample(range(wait, wait * 2), 1)[0])
            wait = (wait + 300) * 2
            pass


Linked List HeadInsert

Question: template <class T>
void List<T>::insertAtHead(T item)
{
     ListItem<T> *node=new ListItem<T>(item);
     ListItem<T> *temp=head;
     if (temp==NULL)
     {
         head=node;
     }
     else if (temp!=NULL)
     {
         node->next=temp;
         temp->prev=node;
         head=node;
     }
 }

I am making a linked list using classes.ListItem is a struct which contains next and previous pointers and they are being pointed to NULL in the struct whenever a new node is made.ListItem has a value of datatype T which can be anything from int to string.I want to know if there are any loopholes in this code.It is basically an assignment of data structures and a test file has been given to us to test our code.But when I run that test file,it fails this piece of code.I just want a hint on whats wrong with this code.Thanks
Comment: What is it doing/not doing that you expect it to do?
Comment: "it fails" - How exactly does it fail? What problem are you dealing with? How did you try this piece of code?...
Comment: OT: Is your intention to have a *circular* linked list ?
Answer: Im assuming you have a head variable as a member variable in you List type
Also, from your next/prev references, I am assuming you have a doubly linked list:
ListItem<T> *temp = head;

if (temp != NULL) {
    temp->prev = node;
    head = node;
    node->prev = NULL;
    node->next = temp;
} else {
    head = node;
    node->prev = NULL;
    node->next = NULL;
}

Linked List HeadInsert