Is there a way to get the script who's blocking browser?

Question: We have a large old web application organized with iframes (many), every iframe is a html page (to be more specific asp.net webform, but the problem is on client side).
We have a problem with some javascript but we don't know which script and in which page.
When the user navigate to a specific section of the web application, the application freeze. Browsers  generally alert the user that there is a script with long execution, and suggest to quit the script.
We can't find where is the problem. Is there some feature in modern browser to step directly in developer tools of the browser, in debug mode on the script who has the problem (instead of simply quit the script) when we face the problem, or some other workaround to detect the script?
Comment: HI, you have to set the debugger to break on all exceptions. F12>Debug tab, select "Break on all exceptions" from the dropdown (looks like a stop sign). It defaults with "Never break on exceptions". !important Without closing the dev tool return to your web page and do your testing.... the debugger will now break when encounters any scripting error. Long running script errors CAN occur if you have alert or prompt statements in the  section of your documents. Only fire alert statements after the document has loaded.
Comment: @RobParsons I don't think any script errors are actually *long running* (they all crash your page almost immediately). The usual cause for freezing pages are infinite loops, which are very hard to detect automatically.
Comment: @Goto - alert statements in infinite loops in the head section... fake support scams.
Comment: @Goto - Page 'crashes' will result in an error log in the Windows Event viewer.... always caused by browser Addons.... Long running script errors are displayed as a user message in response to long running scripts that delay the dom ready state. Place this js in a script block in the head section... while(true){alert('you have been taken');} use IE11 or Edge, v Chrome or FX.
Comment: @RobParsons But `while(true){alert('something');}` is not an error and will not trigger a breakpoint in the debugger. Also, it will not crash your page (in fact, you'll have to kill your IE by yourself).
Answer: The comments on my answer helped for a very simple solution I didn't thinked before... Keeping the debugger running I noted on debugger toolbar (IE, but suppose every browsers work the same) the buttons "pause" (2 vertical red sticks) and "continue" (green triangle). Pressing pause the debugger stop on the exact line the script is running in that moment...
Comment: Yes, every browser dev tool works the same.... you must configure the dev tool to break on errors (handled or not) and to keep the dev tool opened while debugging.... all browsers will ignore errors while their dev tool is not opened.


Howto install php 5.2.17 on centos 6 x86_64

Question: Does anyone know how to install php 5.2.17 on a 64bit centos 6 install? I've got a old legacy system that requires php 5.2.17, but centos 6 only supports php 5.3.
I've installed repo's such as webtatic, but had no luck at all.
Should I rather revert back to centos 5 and install it there?  Any ideas, I am out?
Answer: If centos 6 does not support legacy PHP, you are better off running v5 because if you have to mod the OS to trick it into running it, it could open up a security hole. Recommend you use the latest PHP and OS. If that's not possible, then make sure you have very tight security when using old PHP. That's why they update their software. I'm looking for a way to get this to work right for you.
EDIT: I was beaten to it. Refer to the other poster's wget method.
EDIT2: removed useless text.
Comment: I'd recommend waiting to submit an answer until you have good content to offer. Doing so will gain you many more upvotes than you would if you post a half-baked answer.
Comment: Even though it can be edited? Okay, sounds like good advice.
Comment: Agree with the updated answer, and Centos 5 will still receive maintenance updates until Spring 14'.
Answer: Do the following:
wget http://www.atoomnet.net/php/php-5.2.17/php-5.2.17-1.x86_64.rpm

Then:
rpm -ivh php-5.2.17-1.x86_64.rpm

Then:
vi /etc/yum.conf

Add the following under [main]:
exclude=php*

If you do all that it should work fine.
But, I warn you, you should really run the latest version of PHP to insure that your server is secure.
Comment: Unfortunately I've tried this already, got too many dependency problems when I want to follow this method.
Comment: Okay, are you having problems with dependencies when installing the rpm package I provided? Or, after excluding php from updates?
Comment: That is correct, you see it's not just installing php, extra extensions is also required such as gd, curl, json ect. The best would be to have a yum repo where one can install these extra extensions as well.
Comment: This should contain all of the extensions: http://www.atoomnet.net/centos_updated_php.php
Answer: The atomicturtle repo contains php 5.2.17 x64 rpms for centos 6. Download the necessary packages and install it.
http://www6.atomicorp.com/channels/atomic/centos/6/x86_64/RPMS/
Updated link: http://www6.atomicorp.com/channels/atomic/centos/6/x86_64/drpms/


gcc showing errors from system library. -isystem doesnt work

Question: Here is a simple (Deliberately wrong) c++ hello world program(https://pastebin.com/Cehm9yLx)
#include <iostream>
using namespace std;
int main()
{
    int a;
    cout >>  "Hello World! Welcome!" << endl;
    cin << a;
}

but when i compile it with gcc it shows me 100s of errors instead of usual 1 or 2 in my code, rest all errors are from system libraries on which i have no control.
here is gcc output (https://pastebin.com/uTavsq43). I even tried adding -isystem but it still gives me errors. as the size of my code increases system errors increases too thus making me very difficult to find my problems. I tried ubuntu 17.10 and solus (both ship with gcc 7.2) and both have same problem. Any help will be appreciated. thanks.
Here is also simple makefile i use. (https://pastebin.com/v5Zk4M25)
Comment: The vast majority of standard header stuff in that error log is just candidates for `operator<<` and `operator>>` that it lists when none of them match (identified by them being notes instead of errors and the word "candidate" in the notes). The first thing in the error list points to the part of your code that is wrong, and the other big error in there points to the other part of your code that is wrong.
Comment: `cout <<` and `cin >>`
Comment: @chris do you have any script or any method to hide notes? it makes coding very cumbersome, especially for me because i am still a beginner.
Comment: @user9180468, The notes are part of an error or warning. If the whole thing is too long, it's probably better to fix one and compile again.
Answer: When gcc (or clang) emits errors it does so to stderr.
You will note that the error messages have the word "error:" in them and the lines with notes have the word "note:" in them.
If only there was some means of running a command and filtering its stderr...
$ gcc nod.cpp 2>&1 | grep "error:"

Result (in my case):
nod.cpp:6:10: error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const char *')

nod.cpp:7:9: error: invalid operands to binary expression ('istream' (aka 'basic_istream<char>') and 'int')```

In bash-ese, 2>&1 means "redirect stderr to stdout"
Comment: Thankyou. this gets most of the job done but it shows 'notes:' from the **system_error** library.
Comment: Thankyou, I solved the error by replacing 'error:' by './Sources' (that is where i store my source code).
Comment: @user9180468 great. glad to have helped.


Node with picture left and text right

Question: I have a content type with image and body fields. I am trying to edit the css so that the picture is on the left and the body/text is on the right with all the text staying in a column on the right rather than wrapping around the bottom of the picture. I attached a picture. I want what is show on the bottom. What is shown on the top is what I currently have. I don't want to use a module such as Panels or Display Suite.
Thanks for you input!
Comment: *"I don't want to use a module such as Panels or Display Suite."* I'm afraid that this question has nothing to do with Drupal then. :(
Comment: Maybe, maybe not. I could be hitting up against something in the theme which is Corolla or maybe I'm just confused about how things work. Either way, it is a Drupal site and I'm trying to alter the theme.
Answer: This appears to be about primarily about the CSS, and the right answer depends on how the html is structured.
Have you tried any resources like Learn CSS Positioning in Ten Steps?
If there are already some containers, you can float both the containers left and give them specific widths (probably).  Or you could use absolute positioning.  Do you have to account for the picture potentially NOT being there?
My best suggestion is to use Firebug or Inspector or similar to try out a couple things based on your DOM
Comment: It turned out to be CSS. I'm a long-time Windows developer learning Drupal/web since last Dec. CSS is a real weakness which I'll be addressing in the weeks/months including your suggested resource which I'll start on in the morning. Thank you.
Comment: The CSS tutorial was excellent and helped me get the rest of the items in the layout to stay put when the window sizes. Thanks again.
Answer: are you planning to integrate the wysiwyg editor? with that option you could even control the size of the pictures and you can adapt it with the insert module to make sure that they can only insert certain sizes of the pictures. In that way you can make your users have certain control.
The following link has a conference helped me a lot to integrate the editor, you can create your own classes and help control better how everything is displayed Best practice for wysiwyg editor
Comment: Yes, I am planning to integrate the wysiwyg editor and the functionality you are mentioning will be a real plus for site usability - thanks!
Answer: Use property inspector or firebug to get the class of id names of your picture and body.
In chrome I just right click the photo, and click Inspect Element.
You should find the dome elements where the photo and the body are siblings.
Then add a float: left; to the photo.
Let's say your photo is 300px wide. Add a margin-left: 310px; to your body.
I use this all the time. It would look something like this:
Comment: My selectors .article .field-name-field-article-pic-left-image {float: left; width:50%;} & .article .field-name-field-article-body {witdh:50%; margin-left: 300px} were working but I had a float:right; in the 2nd which was messing things up which I took out after reading you suggestion - thanks!

Node with picture left and text right


Exibir mensagem para validação de um formulário ao invés de alerta

Question: Estou fazendo um formulário que se o usuário deixar o campo nome em branco, exibir a mensagem no campo, ao invés de um alerta. O document.write não funciona com função através de um evento. Estou usando innerHTML e textContent. Entretanto não consigo exibir a mensagem. Fiz dois códigos, vejamos:

    <form name="formulario">
        Nome: <input type="text" name="nome">

        <input type="submit" value="Enviar" name="cadastro" onclick="validar()">
    </form>

Segundo código:

    <form name="formulario">
        Nome: <input type="text" name="nome"> <input type="submit"
            value="Enviar" name="cadastro" onclick="validar()">
    </form>

Comment: No seu primeiro exemplo você está fazendo um `innetHTML` em uma variável `aviso`. Em que local você usa essa variável?
Comment: @Pedro Camara Junior  Uso a variável em  Estou fazendo assim, sem aspas, porque vi um exemplo dum código para mostrar a hora na página no qual usava o  para exibir um bloco de informação pegada do innerHTML
Comment: Você precisa usar o `getElementById`, assim você não está fazendo referência alguma ao `span`. Da uma olhada na resposta que postei.
Comment: @Pedro Camara Junior por que você usa o símbolo de '$'?
Comment: É somente uma [boa prática](http://opensource.locaweb.com.br/locawebstyle-v2/manual/praticas-padroes/javascript/), para diferenciar as variáveis de elementos das demais. Funcionará da mesma maneira sem o cifrão.
Comment: @Pedro Camara Junior Eu execultei o seu código na própria resposta e funcionou. Copiei, colei na minha IDE, mas não funcionou. Mudei algumas coisas e não funcionou. Segue no jsfidle:  http://jsfiddle.net/hkoe6zm0/2/
Answer: Uma opção é criar uma div logo após o txt ou em um local de sua preferência, e nessa div você irá fazer o innerHTML da mensagem de validação, fiz um exemplo pra você ver como funciona:

document.getElementById("btnEnviar").addEventListener("click", validar, false);

function validar() {
  var $divMensagem = document.getElementById('divMensagem');
  var $txtNome = document.getElementById('txtNome');

  if ($txtNome.value.length == 0)
    $divMensagem.innerHTML = 'O nome deve ser informado';
  else
    $divMensagem.innerHTML = '';
}
Nome:
<input type="text" name="nome" id="txtNome">

<input type="submit" value="Enviar" id="btnEnviar" name="cadastro">


General solution of $y''+y = 4\cos x$

Question: So I know how to find the complementary function of this non-homogenous equation. The complementary function is $y = A \cos x + B \sin x$. But I don't understand how to find the particular solution. If we use $y_p = p \cos x + q \sin x$, where $p$ and $q$ are constants to be determined. This doesn't work out, as the result becomes zero. Please tell the particular integral to find the particular solution.
Comment: First you find the solution of the homogeneous equation.  In this case, $4\cos(x)$ is already a solution of the homogeneous equation.  So the method of undetermined coefficients (as explained in any ODE textbook) tells you what to do.  Please report what you found in your textbook, do not merely ask us to do it for you!
Comment: https://www.wolframalpha.com/input?i2d=true&i=y%22%2By%3D4cosx&key=129d2
Answer: Close! Observe that
$$y_p=2 x\sin(x)$$ satisfies the above, and assuming $y_0=A\cos x+B\sin x,$ the whole solution is known. Check:
$$(2x\sin x)''+2x\sin x=0+2(2x)'(\sin x)'-2x\sin x+2x\sin x=4\cos x$$ Thus $$y= 2x\sin x+C_1\cos x+C_2\sin x \ \diamond$$
Comment: Thanks a lot for your help! I realized this a little while ago.
Answer: The general way to solve this is by using method of undetermined coefficients.
First, find the complementary solution (the solution to $y''+y=0$). The characteristic polynomial is $$\lambda^2+1=0\Longleftrightarrow \lambda = \pm i$$
Hence, the complementary solution is $$y_c(x)=Ae^{ix}+Be^{-ix}$$
Using euler's identity of $\operatorname{cis}(x)=e^{ix}$ and regrouping terms, we can rewrite the complementary solution into  $$y_c(x) = A\cos(x)+B\sin(x)$$
The particular solution assumption for your case (ie $a\cos(x)$) is $y_p(x)=x(m\cos(x)+n\sin(x))$, for constants $m, n$, where we multiply by $x$ to account for the cosine already in the complementary solution.
Why does multiplying by $x$ account for cosine already in the complementary solution? That is because we need both solutions to contain only linearly independent terms.
Any scalar multiple of a term is linearly dependent on that term. Hence, our particular solution's cosine and sine are linearly dependent on the complementary solution's cosine and sine. To make them linearly dependent again, we multiply by a factor of $x$.
So we plug this into our diffeq and we find that  $$-mx\cos(x)-2m\sin(x)+2n\cos(x)-nx\sin(x)+mx\cos(x)+nx\sin(x)=4\cos(x)$$
Simplifying and solving this will result in $m=0, n=2$, so $$y_p(x)=2x\sin(x)$$
Adding these up, we find that the general solution is nothing but $$y(x)=y_c(x)+y_p(x)=A\cos(x)+B\sin(x)+2x\sin(x)$$ for some unknown constants $A, B$.

General solution of $y''+y = 4\cos x$


Definition of the Berkovich spectrum

Question: I am trying to read these notes:
http://www-personal.umich.edu/~takumim/Berkovich.pdf
Regarding the Berkovich spectrum. In definition [2.24] it says that the spectrum is the set of bounded (non-trivial) multiplicative semi-norms. But in the explicit definition, elements in the Berkovich spectrum are said to be bounded by the norm of the ring $A$, and it says that we can assume this because we can replace the norm with an equivalent norm.
Initially I did not see the importance of this fact and assumed one can simply discuss bounded semi-norms, and not just norms bounded by the ring norm. However this part of the definition becomes essential when discussing the Gelfand transform.
I do not fully understand the remark above, and how this equivalent norm should be taken. Right now this condition seems to me to make the Berkovich spectrum much less rich than simply bounded multiplicative semi-norms.
I would appreciate it if someone could point to what I'm missing.
Answer: I don't exactly recall what was meant by that remark, but here is an observation from [Berkovich, p. 12].
Let $(\mathscr{A},\lVert \cdot \rVert)$ be the Banach ring in question, and let $\lvert \cdot \rvert$ be a multiplicative seminorm on $\mathscr{A}$ such that there exists a constant $C > 0$ for which $\lvert f \rvert \le C \cdot \lVert f \rVert$ for all $f \in \mathscr{A}$.
Claim. $\lvert f \rvert \le \lVert f \rVert$ for all $f \in \mathscr{A}$.
Proof. For every integer $n \ge 1$, we have
$$\lvert f \rvert^n = \lvert f^n \rvert \le C \cdot \lVert f^n \rVert \le C \cdot \lVert f \rVert^n$$
since $\lvert \cdot \rvert$ is multiplicative and $\lVert \cdot \rVert$ is submultiplicative. Taking $n$th roots, we then have
$$\lvert f \rvert \le \sqrt[n]{C} \lVert f \rVert$$
for every integer $n \ge 1$, hence $\lvert f \rvert \le \lVert f \rVert$. $\blacksquare$
In other words, there is no replacement by an equivalent norm necessary.
EDIT. This observation has been incorporated into the newest version of the notes.

Definition of the Berkovich spectrum


scio type safe BigQuery classes - annotation issue

Question: I am trying to use type safe BigQuery classes. I have also installed intellij scio plugin. But i get the error,

Error:(37, 21) type arguments [RowElement] do not conform to method typedBigQuery's type parameter bounds [T <: com.spotify.scio.bigquery.types.BigQueryType.HasAnnotation]
      sc.typedBigQueryRowElement

Here is my scala code:
def main(args: Array[String]): Unit = {

  @BigQueryType.fromQuery("select id, org, env from TABLE")
  class RowElement

  val (sc: ScioContext, arg) = ContextAndArgs(args)
  sc.typedBigQuery[RowElement]("select id, org, env from TABLE")
    .saveAsTypedBigQuery("TABLE_DEST")
  sc.close()
}

Comment: Did you resolve the case yet? I have a similar issue.
Answer: All @BigQueryType annotations should be in the top level of an object to avoid any macro expansion issues. For example:
object MyPipeline {
  @BigQueryType.fromQuery("...") class MyRecord
}


Views exposed filters do not display in front end

Question: I created a view block. I can see the view block on my page (node/30) no problem. Edited the view by adding filter criteria. I also changed "use Ajax to Yes". I can see the exposed filter in views edit page but I dont see the views at all on my actual page when I add the filter criteria. After I remove the filter criteria, I see the views again on my page. When i added the filter criteria, I also checked "exposed to user option.." I am not sure what I did wrong.
Please help.
D
Comment: Try by adding nid in contextual filter.
Comment: Experiencing the same issue in D8 Did you ever resolve this issue, learn4ever?
Answer: Mb it's because there is no result. In that way you will see exposed form on edit page, but view will not be displayed on front because it's empty (so, there is no need to display exposed form for user and it's hidden).
Try to go on your view's edit page to No results behavior and make it display some text to see if view has no result
Answer: Please check if the 'Exposed form in Block' option under 'Exposed Form' section within the 'Advanced' accordion on the right, is set to 'Yes'.

If so, then your exposed filters will be under 'Disabled' in Structure > Blocks.
You will have to move that exposed form to the specified region.

Also check if the user who visits node/30 also has access to use the filter criteria used in the block view (That is, if you have any field permissions set).
Hope this helps.
Comment: I dont see block option under exposed form. i only see Exposed form
Exposed form style:Basic | Settings
Comment: @learn4ever This option you will get in D8.
Answer: Exposed filters require "Use Ajax" to be set to true for block displays which can also cause this issue. See this issue.
Answer: Get to the Exposed filter form section of the ADVANCED box to set Exposed form in block: to "Yes" and doing so will make the filter be displayed in the views page (if you had that in your setting).
In D8, this setting will make the form avialble in the block but not on the page. On D7 the filter will show up in both page and block but in both instance the user must have permission to use search else it will not show up at all. If after all these are done and still not showing up you need to clear cache and/or rebuild permissions!
And if the search is related to searching user information the logged in user must the "View user information" permission to see/use the search exposed filter.


Factoring a cube expression - (Step by step)

Question: How can I factor the following expression:
$$(a+3)^3$$
Please, step by step so I can learn.
Comment: It seems to already be factored. Can you elaborate about what you need?
Comment: It looks already factored - perhaps it's something else you want done?
Comment: I would like to backshift it, I mean, I looked it up on the internet and I found an expression like this: (a+4)(a²-4a+16)... I don't know the step-by-step to get to this form though
Answer: As noted in the comments $(a+3)^3=(a+3)(a+3)(a+3)$ is already factored.
The expression in your comment is the factorization of a different binomial expression:
$$
a^3+4^3=(a+4)(a^2-4a+4^2)
$$
You can verify this identity simply multiplying the factors.


What are the benefits of time-series over a well-setup linear regression for forecasting?

Question: EDIT: I just want to note that both David and Richard's answers (and comments) I think are needed to paint the full picture in response. To me I still haven't felt a real need to try out time-series frameworks from the given replies if all I can about is strong predictions and have a good sense of how to set up the regression formula, but I do take the points taken on interpretation of the coefficients and overall efficiency (and that, perhaps, I'm doing it the "hard" way).

I'm a bit naive to time-series related models like ARIMA as I can't seem to find a justification for them compared to a well-setup regression model for forecasting. Numerous responses online point to the vulnerability of linear regression due to thinks like autocorrelated errors, seasonality, and extrapolation, but it seems to me I can accommodate much of this with good data prep:

Seasonality - Model it. If there are periodic dips, I've had good luck catching them with various flag columns (month, quarter, even years, etc).
Autocorrelation - Include lagged values. Taking deltas, rolling means, and various statistics against prior values seems to help nicely.
Extrapolation - I don't see how time-series approaches navigate this any better since rare to no series is truly stationary into the future. I've found that keeping a running count from an initial reference point (i.e. months since start) seems to help general directional trends, and at some point you need to retrain anyways.

Adding on to that, regression models allow for a standard means of including  multiple other input features (for instance market data if predicting sales) that do help that extrapolation quandary, as well as the benefits of a typical "optimize it to heck" framework of machine learning... I've never found the justification for a true time-series route.
Can someone help explain what I'm missing in practical use case terms? Or is it perhaps just that regression models do require that careful data modelling before use?
Comment: https://stats.stackexchange.com/questions/35510 contains a discussion of the spatial version of this question.
Comment: Regarding your initial note (due to the edit): my answer tells explicitly that time series approaches will be superior in forecasting in a nontrivial subset of cases. Given that, I wonder if we are on the same page.
Comment: @RichardHardy Perhaps. My general take-home is that: 1) For less "work" (I might quibble on this due to needing to tune hyperparameters), I would expect better predictions via a time-series approach like ARIMA or ARIMAX if including other predictors, 2) If I want to look at causation, time-series is likely needed to get meaningful p-values and coefficients, 3) However, a carefully tuned/setup regression model like in the original post might catch up to time-series method's predictive power or (possibly) surpass it in some situations.
Comment: I am fine with 1 and 2. Regarding 3, surely there will be *some* situation where regression can catch up. But what you wrote in the edit seemed to be a bit more than that (and too strong in my opinion): *I still haven't felt a real need to try out time-series frameworks <...> if all I can about is strong predictions*.
Comment: @RichardHardy That's fair and likely more speaks to my personal motivation and time to learn to new things than anything else. For me, when I can get "pretty decent" results using a very flexible and familiar paradigm, it's hard to allocate time for a new paradigm of perhaps unclear superiority when busy. What I would be very interested in is some efficacy comparison research between the methods in fair comparison conditions (i.e. both getting retrained the same amount, same time steps, etc), but that's perhaps another deeper question.
Comment: Makes sense to me, thanks.
Comment: a counterpoint, why would you not use a time series model for working with time series data? As you stated you can replicate a lot of the functionality implicit in, say, SARIMAX with seasonal predictors and lags and such, but you could just as easily provide your un-transformed predictors into SARIMAX and it will create seasonality and generate a moving average term (lags) in a more mathematically sound way
Answer: It is somewhat of a false dichotomy that one has choose between using a time series framework OR a regression framework.
The main reason for wanting to use a time-series framework would be autocorrelated errors. With this in mind, one can incorporate autocorrelated errors into regression by using Regression with ARMA errors (The ARIMAX model muddle - Hyndman) and in a sense get the 'best of both worlds'.
Comment: @Josh the biggest advantage is interpretability. See the section ARMAX models in the Hyndman blog post I linked. Basically your $\beta$ values become hard to interpret if you also include lagged values of your response variable in your regression equation. However if you use Regression with ARMA errors your regression $\beta$'s 'make sense' in the same way as they would if there was no autocorrelation.
Comment: I may need some help understanding the autocorrelated errors bit. While I know what they are in theory, I have a hard time seeing how they bother me in regression in practice once set up with things like lags and control variables as framed in the question.
Comment: @Josh, see ["Correcting for autocorrelation in simple linear regressions in R"](https://stats.stackexchange.com/questions/181257) for an answer. [Here](https://stats.stackexchange.com/search?q=diebold+user%3A53690+clothes) are some other variations on the theme.
Comment: @David That makes sense I think, though I would need to study the implementation. Ignoring interpretability, would I expect more predictive power, or it ends up roughly (possibly) the same in my proposition?
Comment: @Josh it is hard to say exactly which method has more predictive power. What I would expect is using regression with ARMA errors you will probably end up with more accurate estimates of your $\beta$ coefficients which will help with prediction.
Comment: @DavidVeitch one more question -- if using regression with ARMA errors, does that make using lagged values of response (as features) redundant? Some reading elsewhere I've done seems to suggest the ARMA errors is aimed to take care of that (which would make sense to me since both aim to tackle autocorrelation)
Comment: @Josh what you are describing is something akin to a ARMAX model (described in the Hyndman post). I would say don't include lagged values as features if using regression with ARMA errors.
Comment: Josh, for a graphical representation of why autocorrellated errors are a bad problem, see my question [here](https://stats.stackexchange.com/questions/313119/how-to-prove-that-the-probability-of-spurious-correlation-increases-with-random).
Answer: Autocorrelation
Here is a counterexample. Suppose the data generating process is either exactly an invertible MA($1$) model or well approximated by one. If you wanted to approximate it by a time series regression about as well, you would need an AR($\infty$) model. This is not feasible, so you would end up with an AR($p$) with some large $p$. Estimating the $p+2$ parameters* of the AR($p$) model will make it have high variance and thus perform poorly in forecasting. Meanwhile, you could use an MA($1$) model instead. It has only 1+2 parameters* and thus much lower variance and better forecast accuracy.
Seasonality
Here is another counterexample. Consider a parsimonious SARIMA model as a data generating process or its close approximation. The seasonality generated by a SARIMA model cannot be modelled by dummy variables (flags as you called them). Moreover, approximating it with a time series regression might take a lot of variables and bring in a lot of unnecessary estimation variance.
Even in the very simplest instance of SARIMA(1,0,0)(1,0,0), the SARIMA model will have 2+2 parameters* to be estimated while an equivalent autoregression (which you can consider as a time series regression) will have 3+2 parameters. This way you would be estimating one superfluous parameter and thereby increasing the variance of the model. If we were to add some moving average terms, this would get significantly worse.
Extrapolation
If by that you mean forecasting into the future (beyond the available data), then the above two points apply. Otherwise I agree that there are challenges to both approaches.
Regarding including additional variables, regression with ARMA errors (as already suggested by David Veitch) is always an option. But these additional variables typically also need to be forecast, which brings us to vector autoregressions (VAR) and VARMA models.
In conclusion, it is good to know both time series regression and ARIMA-type time series models. There will be situations where the former is more natural or more effective, and there will be situations where the opposite is the case. You can then only benefit from having both tools under your belt and being able to use whichever one works better at the given task.
*+2 comes from the intercept and the error variance.
Comment: this is a bit hard to parse being written mostly from the "very familiar with ARIMA" perspective which unfortunately I noted I wasn't. It seems though the general motif of your points is that, to accomplish the same feats as time-series frameworks using multivariate regression, you 1) will generally end up with a more complicated model because after all you had to 2) try and puzzle put those variables/lags/seasonality regressors yourself. Then you get the typical problems that come with more complicated models. Is that a fair take?
Comment: @Josh, hm, sort of. I think I am mostly appealing to the no free lunch theorem of statistical learning / machine learning. It says that there is no single model/method/algorithm that works best for all problems. ARIMA and other classical time series models may be best suited for some data generating processes while regression for other. The model needs to be tailored to the problem, and ARIMA and co are well suited for some problems. Trying to conquer these problems with regression may be possible but less efficient (and less natural when it comes to interpretation).
Comment: @josh: I don't have a general answer, but, for certain specific problems, it can be clear cut that time series approaches will be better. For example, suppose you had a problem where the response was  dependent on what happened ( say the error )  in the immediately previous period or previous 2 or previous n periods. A standard regression model can't handle that case. So  there are definitely cases where a regression framework is inferior. For specific examples of what I'm referring to, google for dynamic models in econometrics or lagged dependent models or ARDL models.


How does CCA find a low-dimensional common subspace?

Question: According to Wikipedia, canonical correlation analysis (CCA) finds pairs of canonical variables. CCA has also been used in many cases as dimensionality reduction tool to find low-dimensional subspaces. I am wondering how the subspace is found? and how the subspace is related to the pairs of canonical variables?
Comment: Related or even possible duplicate: http://stats.stackexchange.com/q/65692/3277
Comment: Are you asking to explain mathematically how CCA works? Or are you asking about intuition behind CCA? Or are you asking specifically about the connection between canonical variables and the subspace? This last connection is like the connection between principal components and principal axes (eigenvectors of the covariance matrix) in PCA.
Comment: If this is of interest: I've done a demonstration how the canonical correlations are computed from correlations  resp. from the factor-loadings matrix, and have even added a short discussion when the varimax-rotation might even be superior over the usual principal axes-solution. It is a small (old) "living letter" to a friend using my 1996 Dos-program "Inside-R" without deeper introduction. One downloads the zip-file, unzips it in a directory where a Dos-process can work on, opens a Dos-Box and starts the demo. See http://go.helms-net.de/stat/ir/cc.zip If you have questions, ask here
Comment: @amoeba, I am asking for the connection between canonical variables and the subspace, is it simply the canonical variables spans the subspace? If I have n pairs of variables, no orthogonality within the pair, but orthogonal between the pairs, the spanned subspace is still dimension n?
Comment: Say you have two datasets with $n$ points each, $X$ with $p$ dimensions and $Y$ with $q$ dimensions. CCA will find you $m=\min(p,q)$ canonical pairs; this means it will find $m$ **canonical axes** in the $p$-dimensional $X$ space and $m$ canonical axes in the $q$-dimensional $Y$ space such that projections of the data onto each pair of these axes (called a pair of **canonical variables**) are maximally correlated. If you take e.g. first 2 pairs only, then first two axes span a 2d subspace in space $X$ and a 2d subspace in space $Y$. Does this make sense?
Comment: @amoeba, yes, it make sense, but are those two subspace the same?  where is the COMMON subspace?
Comment: They cannot be the same, because they live in two different spaces! You have to imagine two spaces, $\mathbb R^p$ where data points from $X$ live and $\mathbb R^q$ where data points from $Y$ live. Continuing example from my previous comment, CCA finds 1d (or 2d) subspace in one of them and a 1d (or 2d) subspace in another of them, such that projections onto these subspaces are highly correlated. It is always **a pair** of subspaces, there is no "common" subspace.
Comment: @amoeba, The common subspace was my confusion. I read multiple claims that "CCA finds common subspace for two different dataset". for example: http://www.cvc.uab.es/~almazan/wp-content/uploads/2012/07/iccv13_poster.pdf , If there is no common subspace, how CCA helps to compare two dataset? by project on one dataset entirely to one of the newly found subspace? Thank you
Comment: Yes, I think talking about "common subspace" is a bit sloppy and should be avoided. But I can see why people do it. Imagine that you find 1d subspace in $X$ and 1d subspace in $Y$ such that projections on these subspaces have correlation $r=0.99$. This means that these projections are pretty much the same (up to a scaling), and one is tempted to talk about the "common projection". By the way, this can be made more precise in a framework called "probabilistic CCA", but this is beyond the scope of classic CCA. I am not sure I understand your last question.
Comment: @amoeba, my last question is, in practice, CCA is used to find what is common between two dataset. but how? do we project the two original dataset to one of the subspace and compare them within the subspace?
Comment: As I said, you cannot project both datasets to the same subspace! Let's talk about 1d subspaces, i.e. first pair of canonical axes. You project one dataset onto its first canonical axis (first axis in a pair) and another dataset onto its first canonical axis (second axis in a pair). Now you have two 1d projections, $x$ and $y$. Their correlation is maximal. You can plot them one against each other, or "compare" in any other way. The rest I guess depends on the application...
Comment: @amoeba, thank you very much for your patient explanation, I am now more comfortable with CCA and what it does. Do you mind to write a short answer so I can label it as the right answer?
Comment: All right, will do.
Comment: fast tooth: `I read multiple claims that "CCA finds common subspace for two different dataset"`. In a sense, this is true: if we initially embed both datasets in a common superspace then of course canonical variates lie in a common subspace. But this idea is of little heuristic value. Even in usual regression both Y and the Xs share some space (in which the error variable lies, by the way). And so what? What's really interesting is another point: CCA creates a pair of variables - one in set1 space and the other in set2 space - which correlate maximally. Then goes the 2nd pair.... etc
Answer: This question was based on a false premise that CCA finds one "common subspace". It does not.
CCA deals with two datasets $X$ and $Y$ of $n$ points each: points from dataset $X$ are $p$-dimensional and live in $\mathbb R^p$ and points from dataset $Y$ are $q$-dimensional and live in $\mathbb R^q$. Let $\mathbf X$ and $\mathbf Y$ be two centered data matrices of $n\times p$ and $n\times q$ size respectively.
CCA finds $m=\min(p,q)$ pairs of canonical axes. The first pair $(\mathbf w_1, \mathbf v_1)$ consists of one canonical axis $\mathbf w_1 \in \mathbb R^p$ and one canonical axis $\mathbf v_1 \in \mathbb R^p$. Projections of the data onto these axes (called "canonical components", "canonical variates", or "canonical variables") are given by $\mathbf X \mathbf w_1$ and $\mathbf Y \mathbf v_1$, and they have highest possible correlation  between each other. Projections of the data on the next pair, $\mathbf w_2$ and $\mathbf v_2$ have second highest correlation, etc.
So the first pair of canonical axes defines a 1-dimensional subspace in each space, but these are two different subspaces in two different spaces. Two first pairs define a 2-dimensional subspace, but these are again two different subspaces. There is never a "common subspace", because the spaces $X$ and $Y$ are different to begin with.


keepalived shutdown - does not run "notify" hook on daemon shutdown

Question: I'm running keepalived under Debian (Lenny, Squeeze) in a fairly
simple setup, I'm just (ab)using it as a VRRP daemon to decide the
mastership
between two equal machines for some virtual IPs.
All the magic happens in the notify-script.
When I completely stop the daemon (using debian's init-script)
keepalived does
not run the notify-script for backup or at least fault mode, which is
what I would suspect and need.
I could "fix" the rc-script with some unwanted effects - the
notify-script would be hard-coded into the rc-script introducing an
unwanted coupling of these two and the mess of porting the patch to the
next debian versions so this is not the way I really want to go...
Any hints for a cleaner solution to this problem?
vrrp_instance FOORRP {
  virtual_router_id 42
  interface eth0
  state BACKUP
  priority 200
  nopreempt
  authentication {
    auth_type AH
    auth_pass foobar42
  }
  notify "/usr/local/bin/vrrp-state"
  virtual_ipaddress {
    127.0.0.2
  }
}

PS: the use of the "three notify_"-scripts does not change anything
PPS: in the changelog (Release 1.1.16) there is something
mentioned, that somehow fits my problem (though I am not using anything
lvs-related in keepalived), but I am using a newer version (1.1.20):
"notify_down isn't executed for working real servers on keepalived
shutdown."
Answer: Dug through more documentation and finally found it:
notify_stop "/usr/local/bin/vrrp-state fault"

Works as expected.... X-}
Answer: I faced such an issue recently and I found it is logical to not execute these scripts. These scripts get executed in case of specific events like becoming a master or slave. Keepalived process should not be shutdown unless it is done manually and there is a good reason to do so. If you are worried about failure in keepalived process (not the case of manually shutting it down), you can use monit. It is a great tool to monitor your running processes and restart them if anyone fails.
As you mentioned, you can simply modify the startup script of keepalived to execute the desired script (like stopping some other service). I think this will be cleaner than patching keepalived code, maintaining it yourself, and doing the necessary patch again each time you want to re-install/upgrade it.
Comment: I have a good reason to shutdown keepalived - maintainance! (I haven't seen keepalived crashing for years now, though I've seen it messing up. But thats not my point here.) And - as I wrote - editing the rc script is a technical solution but with unwanted administrative overhead.
Finally: "not running these script" is no solution at all, since this script does all my failover stuff! (which is more than keepalived can do)
Comment: @Michuelnik: So, this will be part of your maintenance anyway. You can include this in keepalived startup script or run it manually.
Answer: You can use notify to get notified about these 5 state transitions:

MASTER
BACKUP
FAULT
STOP
DELETED

You can have a script to catch anyone of these:
#!/bin/bash

ENDSTATE=$3
NAME=$2
TYPE=$1

case $ENDSTATE in
    "BACKUP") # Perform action for transition to BACKUP state
              exit 0
              ;;
    "FAULT")  # Perform action for transition to FAULT state
              exit 0
              ;;
    "STOP")  # Perform action for transition to STOP state
              exit 0
              ;;
    "MASTER") # Perform action for transition to MASTER state
              exit 0
              ;;
    *)        echo "Unknown state ${ENDSTATE} for VRRP ${TYPE} ${NAME}"
              exit 1
              ;;
esac


Canvas Rectangle position

Question: I'm new with the canvas on Android. I'm trying to draw a square at the center of the screen, I want to increase or decrease the size of the square when I click the button. The problem is I don't understand the position of the square.
When I add a code like this it's positioning correctly (5 left and 5 top): canvas.drawRect(5, 5, sideLength, sideLength, mPaint);
But I want to draw this square at the center of the screen as I've mentioned before.
I've tried this but the square doesn't appear on the screen: canvas.drawRect(getWidth()/2, getHeight()/2, sideLength, sideLength, mPaint);
It would be great if you could help me to find a solution for this.
activity_main.xml
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<FrameLayout
    android:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toTopOf="@id/button"
    app:layout_constraintTop_toTopOf="parent"/>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

</android.support.constraint.ConstraintLayout>

MainActivity.java
public class MainActivity extends AppCompatActivity {

FrameLayout frameLayout;

MyView myView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    frameLayout = findViewById(R.id.frameLayout);

    myView = new MyView(this,200);

    frameLayout.addView(myView);

    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            frameLayout.removeView(myView);
            myView = new MyView(MainActivity.this,600);

            frameLayout.addView(myView);
        }
    });
}
}

MyView.java
public class MyView extends View {

Paint mPaint;
int sideLength;

public MyView(Context context){
    super(context);
}

public MyView(Context context,int sideLength) {
    super(context);

    this.sideLength = sideLength;

    mPaint = new Paint();
    mPaint.setAntiAlias(true);

    mPaint.setStyle(Paint.Style.FILL);
    mPaint.setColor(Color.BLUE);

}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.drawRect(getWidth()/2, getHeight()/2, sideLength, sideLength, mPaint);
}

}

Answer: getWidth()/2 and getheight()/2 will give you the center coordinates of your container.
Assuming your container is a perfect square with dimensions (2000, 2000) in pixels, your center coordinates will be (1000, 1000). With this in mind, you are attempting to draw the left side of your square at coordinate 1000 and the top part at coordinate 1000.
Now the next part is where the problem arises. You are attempting to draw the right side at coordinate 600 and the bottom at coordinate 600
When drawing rectangles and squares, the following should be noted:

The right coordinate should be greater than the left
The bottom coordinate should be greater than the top.

Below is a working code which draws a square in the center of a FrameLayout
MyView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.view.View;

public class MyView extends View {

    Paint mPaint;
    int sideLength;
    PointF center;

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, int sideLength) {
        super(context);

        this.sideLength = sideLength;

        mPaint = new Paint();
        mPaint.setAntiAlias(true);

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.BLUE);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(center.x - sideLength, center.y - sideLength, center.x + sideLength, center.y + sideLength, mPaint);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        int y = getHeight() / 2;
        int x = getWidth() / 2;

        center = new PointF(x, y);
    }
}

activity_main.xml
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#dedede"
        app:layout_constraintBottom_toTopOf="@id/button"
        app:layout_constraintTop_toTopOf="parent"/>

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Canvas Rectangle position


Relationship between a "standard fact" about limits, Cauchy and d'Alambert

Question: In the material I'm going over there's a "standard fact" about sequences:
$$a_n>0, \lim\limits_{n \to \infty}{a_{n+1} \over a_n} = q \implies \sqrt[n]{a_n}=q$$
Now, once we consider series, the d'Alambert ratio test states:
$a_n>0, {a_{n+1} \over a_n} \to q < 1 \implies \sum a_n$ converges.
The Cauchy criterion postulates: $\sqrt[n]{a_n} \to q \implies \sum a_n$ converges.
Now, I've come across a statement that the satisfaction of the Cauchy criterion Cauchy is stronger than d'Alambert. The statement I've seen about Cauchy being stronger that d'Alambert was
$$\sqrt[n]{a_n}\to q \implies {a_{n+1} \over a_n} \to q \qquad (1)$$
Two questions here:

Is the original "standard fact" not only an implication but actually an equivalence?
Is $(1)$ plain wrong? If we assume $(1)$ is correct and take $\sqrt[n]{a_n} \to 2$, the series converges by Cauchy but diverges by the ratio test. How do we reconcile this?

I've seen several expositions comparing the root and ratio test so far. None of them has clarified the matter.
Comment: The relation between these limits is described e.g. here: http://math.stackexchange.com/a/1164162/259493
Comment: @NickPeterson It seems the notes I'm reading are lacking vital information. Just to check if I got this right, even with the knowledge that the root test implies convergence if $q<1$, we only can write ${a_{n+1} \over a_n} \to q \implies \sqrt[n]{a_n}$ and this means that if the ratio test is satisfied, then the root test is as well but there are cases when the root test is satisfied but the ratio test is not (so the root test is stronger in identifying convergence)? EDIT: Your answer posted in the interim replies to my question :)
Answer: The statement (1) is not correct.
For instance, consider
$$
a_n=\frac{1}{2^{n+(-1)^n}}.
$$
The ratios are
$$
\frac{a_{n+1}}{a_n}=\frac{2^{n+(-1)^n}}{2^{(n+1)+(-1)^{n+1}}}=\begin{cases}2 & \text{$n$ even}\\\frac{1}{8} & \text{$n$ odd}\end{cases}
$$
while the roots satisfy $\sqrt[n]{a_n}\to\frac{1}{2}$ as $n\to\infty$.
In fact, the opposite of (1) is the truth: if $\lvert\frac{a_{n+1}}{a_n}\rvert\to q$ as $n\to\infty$, then $\sqrt[n]{\lvert a_n\rvert}\to q$ as $n\to\infty$ as well.
As for your claims about convergence: remember that convergence of the ratios/roots is not sufficient to show convergence in either case; what's required is that the limit be less than 1.


What is the role of the person escorting and recording the driver during the interview?

Question: In the formula 1 after the race finish and they interviewing the driver, they are escorted by a person recording the interview.
What is that role position? And why they need it?
Are they afraid of what driver say? Or they need a copy of the interview in case the press put something different?
Shouldn't be easy just let the driver use the same microphone wear during the race
Comment: @JuanCarlosOropeza person escorting them are PR minder and would make it easy to search for answer but answer still would be opiniated.
Comment: The title and question don't match at all, and both seem based on a false premise. Your personal comment on the appearance and stature of the person holding the recorder are irrelevant and sexist. Cars have drivers, not pilots.
Comment: Why do you think, in the first place, that this is either a limit on the driver or that the recording is evidence for anything? Drivers and teams have their own websites and articles and sponsors to think about, of course they want their own copies of any interview.
Comment: @Nij I remove the comment, Sorry english isnt my first lenguaje. my question is why they need someone to record the interview, looks like they try to keep them in a leash? So they arent really free to express during interviews.
Comment: @nij, because they could just use a wireless microphone, you know like they use to talk during the race. No need to have someone behind.
Comment: Please downvoters would you mind comment on why you think this is a bad question?
Comment: Thanks @RamchandraGiri , Google for `F1 PR minder` give me some answers.
Answer: As @Ram chandra point it out. The person is a PR minder. So doesnt only record the interview, also help them to navigate between all the reporter and sponsors. And also act like an assistant so driver only have to worry about racing.
I google F1 PR Minder and find this post in Reddit
One interesting comment here:

Ted Kravitz did a piece on this with Vettel's minder.
Their jobs are far more than just simply recording stuff the driver's say, they're basically like a personal assistant.
Drivers (top ones anyway) have a lot of obligations, especially with media and sponsors, if they're not out on the track racing, they're most likely doing an interview or making an appearance with sponsors. The PAs arrange their schedules, from daily activities down to the very minute (eg, 15 minutes spent doing signings before needing to go to A, B and C), they try to fit as many activities in as possible and their trips are planned down to the minutes.
Apart from that, the paperwork involved in getting an F1 driver around the world is insane, the coordination and scheduling is a huge task and one of the most important jobs these "minders" have.
As an example, to satisfy anti-doping laws the drivers must submit a schedule of where they'll be a year in advance so the WADA (world anti-doping agency) knows exactly where they are at any given time, this allows them to do random spot-checks with no warning. The penalty for them not finding you can be a ban/loss of super license. Example of how stringent the WADA are at doing spot checks You can imagine just doing that one specific time tabling task would be a huge headache.

Also they show one example of why is important record the interview:

They make their own recording of all the interviews, so that when some journalist misquotes a driver for a story, they can play their copy of the tape to prove what was actually said.
Happened just a few weeks ago, someone reported that Hamilton said he "blew away" Nico ... every other "journalist" lazily copied and pasted this story without checking ... Mercedes issued their recording with Hamilton saying he "pulled away".
Answer: I've wondered the same thing but I think it might be in order to verify press later. That is to say, have a way of confirming or denying what a driver may have said during a post-race interview. It seems similar to what some politicians have used in past.


ARKit: Tracking VisonCoreML detected object

Question: I'm new to iOS and I am currently refactoring a code I got from a tutorial on VisionCoreML and ARKit that adds a node to the detected object.
currently, if the I move the object the node does not move and follow the object. I can see from Apple's sample code for Recognizing Objects in Live Capture they use layers and repositions this each time Vision detects the object at a new position which is what I was hoping to replicate with an ARObject.
Is there a way I can achieve this with ARKit?
Any help around this would be greatly appreciated.
Thanks.
EDIT: Working code with solution
@IBOutlet var sceneView: ARSCNView!
private var viewportSize: CGSize!
private var previousAnchor: ARAnchor?
private var trackingNode: SCNNode!
lazy var objectDetectionRequest: VNCoreMLRequest = {
    do {
        let model = try VNCoreMLModel(for: yolov5s(configuration: MLModelConfiguration()).model)
        let request = VNCoreMLRequest(model: model) { [weak self] request, error in
            self?.processDetections(for: request, error: error)
        }
        return request
    } catch {
        fatalError("Failed to load Vision ML model.")
    }
}()

func renderer(_ renderer: SCNSceneRenderer, willRenderScene scene: SCNScene, atTime time: TimeInterval) {
    guard let capturedImage = sceneView.session.currentFrame?.capturedImage
    else { return }

    let imageRequestHandler = VNImageRequestHandler(cvPixelBuffer: capturedImage, orientation: .leftMirrored, options: [:])

    do {
        try imageRequestHandler.perform([objectDetectionRequest])
    } catch {
        print("Failed to perform image request.")
    }
}

func processDetections(for request: VNRequest, error: Error?) {
    guard error == nil else {
        print("Object detection error: \(error!.localizedDescription)")
        return
    }

    guard let results = request.results else { return }

    for observation in results where observation is VNRecognizedObjectObservation {

        let objectObservation = observation as! VNRecognizedObjectObservation
        let topLabelObservation = objectObservation.labels.first
        print(topLabelObservation!.identifier + " " + "\(Int(topLabelObservation!.confidence * 100))%")
        guard recognisedObject(topLabelObservation!.identifier) && topLabelObservation!.confidence > 0.9
            else { continue }

        let rect = VNImageRectForNormalizedRect(
            objectObservation.boundingBox,
            Int(self.sceneView.bounds.width),
            Int(self.sceneView.bounds.height))

        let midPoint = CGPoint(x: rect.midX, y: rect.midY)

        let raycastQuery = self.sceneView.raycastQuery(from: midPoint,
                                                  allowing: .estimatedPlane,
                                                  alignment: .any)
        let raycastArray = self.sceneView.session.raycast(raycastQuery!)
        guard let raycastResult = raycastArray.first else { return }

        let position = SCNVector3(raycastResult.worldTransform.columns.3.x,
                                raycastResult.worldTransform.columns.3.y,
                                raycastResult.worldTransform.columns.3.z)

        if let _ = trackingNode {
            trackingNode!.worldPosition = position
        } else {
            trackingNode = createNode()
            trackingNode!.worldPosition = position
            self.sceneView.scene.rootNode.addChildNode(trackingNode!)
        }
    }
}

private func recognisedObject(_ identifier: String) -> Bool {
    return identifier == "remote" || identifier == "mouse"
}

private func createNode() -> SCNNode {
    let sphereNode = SCNNode(geometry: SCNSphere(radius: 0.01))
    sphereNode.geometry?.firstMaterial?.diffuse.contents = UIColor.purple

    return sphereNode
}

private func loadSession() {
    let configuration = ARWorldTrackingConfiguration()
    configuration.planeDetection = []
    sceneView.session.run(configuration)
}

override func viewDidLoad() {
    super.viewDidLoad()
    sceneView.delegate = self
    viewportSize = sceneView.frame.size
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    loadSession()
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    sceneView.session.pause()
}

Answer: To be honest, the technologies you're using here cannot do that out of the box. YOLO (and any other object detection model you swapped out for it) have no built in concept of tracking the same object in a video. They look for objects in a 2D bitmap, and return 2D bounding boxes for them. As either the camera or object moves, and you pass in the next capturedImage buffer, it will give you a new bounding box in the correct position, but it has no way of knowing whether or not it's the same instance of the object detected in a previous frame.
To make this work, you'll need to do some post processing of those Vision results to determine whether or not it's the same object, and if so, manually move the anchor/mesh to match the new position.  If you're confident there should only be one object in view at any given time, then it's pretty straightforward. If there will be multiple objects, you're venturing into complex (but still achievable) territory.
You could try to incorporate Vision Tracking, which might work though would depend on the nature and behavior of the tracked object.
Also, sceneView.hitTest() is deprecated. You should probably port that over to use ARSession.raycast()
Comment: Thanks @Chris

I have replaced the use of sceneView.hitTest() with raycast() which has helped with the node's positioning.

Re: your point on tracking and moving the Anchor, that is pretty much what I thought, and in hindsight, I really should have made my intentions clear Sorry for not reviewing my question properly. And yes, initially I just want to track the 1 object.

The method ```resetScene()``` tries to remove any existing node and anchor and replace it with a new one based on the object's position but this does not work very well. Is there anything changes you can suggest?
Comment: I'd recommend starting off with an approach where your store a reference to the current `sphereNode`, the first one you place.  Then when you get a new rectangle from your YOLO detection, you cast a new ray to that center position, and then move the existing `sphereNode` by changing `node.simdPosition` to the newly detected 3D point. There is no need to reset the scene between detections, in fact that seems counterproductive!


How to bulk add information to the profiles of users?

Question: I have hundreds user profiles where I want to add a one or two fields like the adress of the company they work for. For some group of users this adress will be the same and for others it will be different. How do I mass bulk add these kind of informations? Through the database? (I'm on phpmyadmin)
Answer: Step 1
Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to Set a data value, for each of those fields you want to be updated.
Step 2
Create a view of the group of users for which those fields should be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.
Tutorial
To get the idea, have a look at the video about Using Rules components with VBO" which uses a Rules Component with (only) 1 parameter. If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Attention: to process like 100.000 entities at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
PS: this answer is for D7 ...


issues with adding anchor tag around the image tag

Question: I have my Flex Gallery working well, only issue is when I add an  tag to the around  tag and it all messes up.
When I wrap the  tag around with an  tag so I can open the full size images, it ends up messing the whole design, I am sure something in my CSS is messing it up, how can fix it

html,
body,
h1,
h2,
section,
div {
  margin: 0;
  padding: 0;
}

body {
  max-width: 76.5rem;
  padding: clamp(0.5rem, 2vw, 2rem);
  margin: auto;
}

.gallery {
  margin-top: 2rem;
}

.gallery>div {
  columns: 16em;
  gap: 1.25rem;
  padding-top: 1.25rem;
}

.gallery img {
  display: block;
  width: 100%;
  margin-bottom: 1.25rem;
}

Gallery Title Here

Comment: Could you share the "messed up" code snippets and possibly a jsfiddle?
By the sounds of things it's because you have the css applied to .gallery img, and when you're using the anchor tag around the image the styling isn't applied to the anchor, so you should pretty much just rename ".gallery img" to ".gallery a"
Comment: So you want to turn your images into clickable links. am I right?
Comment: yes, right, and i wrapped around it with a tag but it messed up the whole gallery
Comment: I agree with Seann I also think that you can replace  image html codes by only  tags with different classes Like ,.. and then set their background images in CSS
Comment: i think i tried already said by @seann and it really messesup the design
Comment: See this fiddle: [link](https://jsfiddle.net/vxnw32ez/) it seems to be fine with the anchor tags, the design appears the exact same as without them
Comment: for me, when i add the anchor, instead of displaying 3 in a row, it just ends showing two in a row
Comment: @moorad when I resize it shows 3.. It looks perfect to me
Comment: Agree with the other posters above, but a functioning example of the broken state will be helpful here, for future readers if nothing else.
Comment: @Jake I don't think he means broken. When I open the picture from link, the image is scaled up too much in the destination link. so we need styling in the destination link which will need some Javascript or he can make separate styled image html pages and then link them to the main html
Answer: Works fine for me. The anchor tags make zero difference.

html,
body,
h1,
h2,
section,
div {
  margin: 0;
  padding: 0;
}

body {
  max-width: 76.5rem;
  padding: clamp(0.5rem, 2vw, 2rem);
  margin: auto;
}

.gallery {
  margin-top: 2rem;
}

.gallery>div {
  columns: 16em;
  gap: 1.25rem;
  padding-top: 1.25rem;
}

.gallery img {
  display: block;
  width: 100%;
  margin-bottom: 1.25rem;
}

Gallery With Links

Gallery Without Links


Make nginx to pass hostname of the upstream when reverseproxying

Question: I run several docker containers with hostnames:
web1.local
web2.local
web3.local
Routing to these done based on hostname by nginx. I have a proxy in front of this setup (on different machine connected to internet) where I define upstream as:
    upstream main {
      server web1.local:80;
      server web2.local:80;
      server web3.local:80;
    }

And actual virtual host description:
    server {
      listen 80;
      server_name example.com;
      location / {
        proxy_pass http://main;
      }
    }

Now, because containers receive hostname "main" instead of "web1.local", they do not respond properly to the request.
Question: how I can tell nginx to pass name of the upstream server instead of name of upstream group of servers in Host: header when proxying request?
Comment: @MichaelHampton That is not possible in some cases, eg if using `proxy_ssl_server_name` for TLS SNI, it needs the right server name.
Comment: I don't think you can. Why don't you set your backend servers to respond to main or example.com? It isn't as if the backend doesn't know who *it* is. The reverse is readily possible: proxy_set_header Host $host; will replace any Host variable coming back from the upstream with the hostname from the original request.
Comment: IMHO this is a bug in Nginx. The name "main" of upstream is just a local reference in the .conf file that does not need to reflect an actual hostname resolvable by DNS or known to the backend. Basically unless your backends know this reference or respond to Host: * you can't use Nginx's `upstream` directive.
Comment: The proper thing to do is to fix the application.
Answer: Actually you can do that via proxy_set_header.
For more details look here: http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header or see an example use-case here: https://stackoverflow.com/questions/12847771/configure-nginx-with-proxy-pass
I have included the dynamic approach into your above posted configuration:
server {
  listen 80;
  server_name example.com;
  location / {
    proxy_pass       http://main;
    proxy_set_header Host            $host;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

Here is an example with a static host name:
server {
  listen 80;
  server_name example.com;
  location / {
    proxy_pass       http://main;
    proxy_set_header Host            www.example.com;
    proxy_set_header X-Forwarded-For $remote_addr;
  }
}

Comment: proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; seems better
Comment: This answer implies that `$host` variable gets set to the value of the server name from the `upstream` block `server` directive but that doesn't seem to match the documentation. If nginx chooses e.g. `web1.local:80` as the destination, does `$host` get set to `web1.local:80` or to `example.com` (the first value in `server_name`)? The latter might work but it's not what was originally asked.
Comment: @pavel: got it. Actually I did also some research and some tests.  It seems that there is no straight approach to fulfill your requirement. So even a "bastardized" solution is a solution. I don't like to ask why you'd like to do this. I'm pretty sure you have your reasons. :-)
Comment: This answer reflects [advice of the official blog](https://www.nginx.com/resources/admin-guide/reverse-proxy/).
Comment: This answer is incorrect  - passing the incoming `$host` variable to your backend will only work if your NGINX is called on the SAME host as your backend responds to - an unlikely scenario.
Comment: @ncenerar You can do that but this will bring you to a single point of failure: the load balancer. If this is for load balancing (not redundancy) you can also use DNS based load balancing in combination with DNS failover.
Comment: This doesn't work in 2022. `$host` is not set to server name(like facebook.com), but instead for me at least, its giving `localhost`. So this answer is deprecated.
Comment: @JensBradler You seem more expert than me so, could you tell me what you think of my solution? I want to do the same because I run two copies of my website from two accounts on my ISP: `site1.myisp.com` and `site2.myisp.com` and they only respond to their respective name. I, now, own my domain name and I'd like to use my ISP website to load balance my servers. Isn't that a good reason? Thank you very much ;)
Comment: Also passing theese options can be saviour for your dev team because the application will continue to work during development.
Comment: To complement Marc's comment: From the [docs](http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header): "`$host`'s value equals the server name in the "Host" request header field or the primary server name if this field is not present." I.e. usually the `Host:` as defined by the client is passed on.
Comment: Since nginx 1.7.0 you may also need to [set](https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ssl_server_name) `proxy_ssl_server_name on;` in your load balancer if your upstreams have multiple SSL certs and depend on SNI.  nginx by default does NOT enable SNI for upstream connections....so the upstream may not know which cert to return.
Answer: I had the same problem and I finally solved it by using two levels of proxy. Here is how you could do for your situation (I think):
server {
  listen      8001 default_server;
  server_name web1.example.com;
  location / {
    proxy_pass       http://web1.local:80;
    proxy_set_header Host web1.local:80;
  }
}

server {
  listen      8002 default_server;
  server_name web2.example.com;
  location / {
    proxy_pass       http://web2.local:80;
    proxy_set_header Host web2.local:80;
  }
}

server {
  listen      8003 default_server;
  server_name web3.example.com;
  location / {
    proxy_pass       http://web3.local:80;
    proxy_set_header Host web3.local:80;
  }
}

upstream main {
  server 127.0.0.1:8001;
  server 127.0.0.1:8002;
  server 127.0.0.1:8003;
}

server {
  listen      80;
  server_name example.com;
  location / {
    proxy_pass http://main;
  }
}

As you can see, the trick is to create a local server responding to a particular port that will proxy the server by rewriting the right Host for each servers. Then, you can use this local servers in your upstream and finally use that upstream in the real proxy.
Comment: I originally used Lua approach, but now switched completely to HAProxy which allows to do just what I wanted with standard configuration.
Comment: I wonder how this affects performance (adding an extra `server { .. proxy_pass ... }` layer)
Comment: This is useful if you want to use a resolver with more than 1 server in upstream, because the free tier of nginx doesn't allow to resolve in the upstream (using a variable as the proxy name is not enough, because there's more than 1 endpoint, in the case in which nginx acts as a load balancer).
Comment: 7 years after creating this answer it saved my hide.  In my case each upstream also needs unique headers to each upstream so this worked perfectly.
Answer: While the goal seems logical, nginx isn't going to change the Host: header to match the upstream. Instead, it treats upstream domain names like a CNAME in DNS - as a way to get to an IP address.
The request headers (and body) are fixed before the upstream is selected. The upstream may change mid-request if it's a particular upstream is found to be non-responsive, but the request doesn't change.
Answer: We pass in the upstream addr as a separate header like this
server {
  listen 80;
  server_name example.com;
  location / {
    proxy_pass       http://main;
    proxy_set_header Host            $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    add_header       X-Upstream      $upstream_addr;
  }
}

What if you tried?
server {
  listen 80;
  server_name example.com;
  location / {
    proxy_pass       http://main;
    proxy_set_header Host            $upstream_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    add_header       X-Host          $host;
  }
}

Comment: No. At the time "proxy_set_header" is evaluated the $upstream_addr is still null, it get's choosed later.
Answer: So from reading all documentation for nginx (I could not really parse code for upstream module =( ) I came up with this bastardized solution. Unfortunately this solution does not keep track of failed hosts, but simply select random one and redirect request to it. So I have to setup some kind of monitoring to make sure all backends are running.
server {
        listen 80;
        server_name example.com;
        resolver 127.0.0.1;

        location / {
                set $upstream "";
                rewrite_by_lua '
                        local upstreams = {
                                "http://web1.dokku.localdomain",
                                "http://web2.dokku.localdomain",
                                "http://web3.dokku.localdomain",
                                "http://web4.dokku.localdomain"
                        }
                        ngx.var.upstream = upstreams[ math.random( #upstreams ) ]
                ';
                proxy_pass $upstream;
        }
}

Comment: What happens if an upstream host is down with this method ?
Answer: Hmm. I have a similar setup, in which I've simply done
location / {
    ...
    proxy_set_header X-Forwarded-Host $http_host;
    proxy_pass ...;
}

The use of $http_host (the HTTP Host header from the incoming request) here rather than $host (the server hostname configuration) causes the same Host header passed by the client to be passed up to the upstream, in my testing.
See also https://stackoverflow.com/questions/14352690/change-host-header-in-nginx-reverse-proxy.
Comment: According to the docs https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_set_header `the $host variable - its value equals the server name in the "Host" request header field or the primary server name if this field is not present` - so probably `$host` is better
Answer: As other people already posted using script variable (like $upstream), you can set it however way you like, and that will fix the issue, without additional header hacking.
Proxy Pass handler threat script variables in a different way, if a value is not conditional (does not have $ in the name) is backed to the upstream on configuration phase and use later.
A simple way to omit this issue, and have the most advantages of (free version) upstream would be using something like Split_Clients:
split_clients $request_uri $my_upstream {
              33%          server1.domainX.com;
              33%          server2.domainX.com;
# Always use DOT at end entry if you wonder why, read the SC code.
              *            server3.domainX.com;
}
location / {
    ...
    proxy_pass http://$my_upstream;
}

The above example looks almost the same as upstream. There exists other modules do the mapping, i.e. chash_map_module, but as they are out of the tree you will need to build them by your own, which is not possible for some use-cases/
Comment: While simpler than lua, wouldn't solve the problem of one of the upstreams being down.


Simulating post hoc power for multiple regression

Question: I have a null result for a negative binomial regression model and I would like to give evidence that my sample is large enough to detect even small effects.
I've found a few online calculators for power analysis, but I'd prefer to use simulation. I haven't been able to find many resources about how to do this.
Comment: Your sample size was not enough to detect your effect, so your power is zero. See Lenth (https://pdfs.semanticscholar.org/fbfb/cab4b59e54c6a3ed39ba3656f35ef86c5ee3.pdf) for a "grand unified formula" for posthoc power. For an alternative, you can try "design analysis" https://andrewgelman.com/2017/03/03/yes-makes-sense-design-analysis-power-calculations-data-collected/
Answer: For your given sample size and the observed effect size your power was <50%, no need for simulation. If that's a meaningful effect size,  the study was under-powered.
If that is not the case and the confidence intervals exclude a meaningful effect size,  then you have a pretty good argument that the study had provided a pretty clear answer.
What's the particular problem with simulating? Simulate your drop out/ censoring process, condition on the simulated drop out times,  then either simulate straight from a negative binomial, or simulate as a Gamma-Poisson mixture (useful if you also have a baseline period and need to capture the within subject correlation for that). Then apply your analysis model to each simulated dataset.
Comment: For your second statement, the pretty clear answer is that there is no effect?


How to get damaged images while displaying it in gridview

Question: I'm using a grid view for showing my gallery images, but few of them aren't displaying anything. When i open facebook app and go for image posting, its also showing those blank images, but when i'm trying to select it showing messages "can't read file , it might be damaged."
How would i do this??
            final String[] columns = { MediaStore.Images.Media.DATA,
                MediaStore.Images.Media._ID };
        final String orderBy = MediaStore.Images.Media._ID;
        Cursor imagecursor = managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                null, null, orderBy);
        int image_column_index = imagecursor
                .getColumnIndex(MediaStore.Images.Media._ID);
        count = imagecursor.getCount();
        thumbnails = new Bitmap[count];
        arrPath = new String[count];
        thumbnailsselection = new boolean[count];
        for (int i = 0; i < count; i++) {
            try {
                imagecursor.moveToPosition(i);
                int id = imagecursor.getInt(image_column_index);
                int dataColumnIndex = imagecursor
                        .getColumnIndex(MediaStore.Images.Media.DATA);
                thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail(
                        getApplicationContext().getContentResolver(), id,
                        MediaStore.Images.Thumbnails.MICRO_KIND, null);

                arrPath[i] = imagecursor.getString(dataColumnIndex);

                onProgressUpdate(String.valueOf(id));

            } catch (Exception e) {

            }
        }

here's the code which i'm using in doInBackground();
Thank you for help.
Comment: Just refresh your gallery items.
Comment: @ Harshit Rathi I did that, but that's not worked, neither in facebook.
Comment: is your gallery display that items correctly.
Answer: this line for refreshing gallery item pragmatically
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(filePath))));

it will happening while some files u just delete from sdcard and gallery of android is not updated i.e that time device is not able to fetch that image so u can try with this
 For images
private void getallimages(File dir)
    {

    String[] STAR = { "*" };
    controller.images.clear();

    final String orderBy = MediaStore.Images.Media.DEFAULT_SORT_ORDER;
    Cursor imagecursor = cntx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STAR, null, null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
    int count = imagecursor.getCount();
    for (int i = 0; i < count; i++) {
        imagecursor.moveToPosition(i);
        int id = imagecursor.getInt(image_column_index);
        ImageItem imageItem = new ImageItem();//this is my wrapper class
        if(new File(imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA))).length()<=10485760)
        {
            imageItem.filePath = imagecursor.getString(imagecursor.getColumnIndex(MediaStore.Images.Media.DATA));

        imageItem.id = id;
        imageItem.selection = false; //newly added item will be selected by default this it do for check box unselect u dont need to fill this
        controller.images.add(imageItem);//this i just add all info in wrapper class

        }
} }

And if it will not come from this also then just print something for user :)
when u try to fetch or open that image then just give one condition like i try to open that image and if it is not present then toast for it that this image might be corrupt or not present in sdcard

Comment: I've update my code, when i used your filtering method none of image is showing in grid.
Comment: like u dint got even all valid image also
Comment: whenever u call that method then u have to pass file dir = Environment.getExternalStorageDirectory();.... have u pass this path dude
Comment: yes, i've got just blank square and check box.(no imge)
Comment: Environment.getExternalStorageDirectory(); have u pass this
Comment: No, i'm not using that yet. can you show me how would i do that.
Comment: then how can u call my method getallimages() dude
Comment: the method i've mentioned above is returning all images..i haven't use your all method
Comment: have  u just add my first line only sendBroadcast ??
Comment: No, yours if condition
Comment: see u can check from your path like whenever u will get any image path from your method then check it like if(Filepath.exists()) then only add in your gridview images wrapper class or anywhere add in which u use to store all file to show in grid


Jquery : Hide first row of all the tables except first table

Question: I have many tables like

i may have more than 10 such tables
i need to hide the first row (class name first_tr) of all the tables except first table
Comment: The title says "hide second row" and the body says "hide the first row"?
Answer: Try this:
$('td:nth-child(2):not(:first)').hide();

Demo here
More info about what I used:

:nth-child()
:not()
:first
Answer: You can exclude the first element using .not() method:
$('table.mytable').not(':first').find('.first_tr').hide();

Answer: You can use .not() selector
$('.mytable').not(":eq(0)").find(".first_tr").hide()

Or, You can use .gt() selector
$('.mytable:gt(0)').find(".first_tr").hide()

If you want to hide second row use second_tr instead of first_tr
Answer: You can achieve this as simple as that:
$('.first_tr', '.mytable').not(':first').hide();

Demo 1
Or, within the same selector:
$('.first_tr', '.mytable:not(:first)').hide();

Demo 2


What is a "win in last at-bat"?

Question: On a baseball broadcast tonight, the team statistic "wins in last at-bat" came up.  What's the definition of this term?
The announcer was careful to point out that such a win "doesn't have to be a walk-off", and gave as an example San Francisco at Milwaukee, June 8, 2017.  This was an extra-innings game in which the visiting Giants scored four runs in the top of the 10th, then held the Brewers scoreless in the bottom of the 10th to win.  But the Giants' last at-bat in the top of the 10th didn't score a run at all (it was a ground ball into a double play) so it's not clear to me in what sense they won on their last at-bat.
If it helps, there was a graphic showing the National League leaders for most wins in last at-bat in the 2017 season up to June 9:
<code>Giants            9
Phillies          9
Diamondbacks      7
Braves            7
</code>
I tried searching and found a few mentions of games won on the last at-bat, but couldn't find a precise definition.
Answer: I don't hear it much outside this specific context, but would generally assume that an at-bat for a team (instead of an individual) covers the portion of a single inning that a team is on offense.
This ESPN story confirms that usage for this statistic.

The definition of a last at-bat win is when the winning run is scored by a team in their final inning at the plate
Answer: It means your team took the lead during their last turn at bat.
Let's say a home team took the lead in the 1st at bat of the bottom of the 8th inning, then committed 3 outs, and the visiting team failed to score in the top of the 9th.
It would be a last at bat win for the home team.

What is a "win in last at-bat"?


PHP: Calculate with decimals

Question: I am creating an app which calculates nutrients of food based on a specific amount. The user fills in the amount of food they have consumed and the app calculates the nutrient values.
My source data has values with decimals, for example: 100g of strawberries have 6,5 carbs.
When I fill in 100g of strawberries (which is the same amount of grams as the source data) the app will output 6 instead of 6,5. So it seems like my calculations ignore everything that's behind the comma (",").
My code:
$con = mysqli_connect('localhost','root','','food');
if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con, "food");
$sql = "SELECT * FROM products WHERE id = '".$q."'";
$result = mysqli_query($con, $sql);

if ($result->num_rows > 0) {
    while($row = mysqli_fetch_array($result)) {
        $GLOBALS['name'] = $row['product'];
        $GLOBALS['kcal'] = $row['kcal'] / 100 * $GLOBALS['amount'];
        $GLOBALS['protein'] = $row['protein'] / 100 * $GLOBALS['amount'];
        $GLOBALS['fat'] = $row['fat'] / 100 * $GLOBALS['amount'];
        $GLOBALS['carbs'] = $row['carbs'] / 100 * $GLOBALS['amount'];
    }
} else {
    echo "Geen gegevens";
}

If I use number_format around the equation, the results will still be wrong (output will be 6).
What am I doing wrong?
Demo
Fill in the top two inputs:

Strawberries (Aardbeien)
100
Click "Voeg toe"
Answer: Maybe, you need use str_replace function?
For example:
$GLOBALS['kcal'] = str_replace(',','.',$row['kcal']) / 100 * $GLOBALS['amount'];

PHP: Calculate with decimals


Connecting Scarlett Solo output to mixer in live setting

Question: I would like to play virtual instruments in Ableton Live in rehearsal setting. At my disposal are:

Scarlett Solo interface (with stereo RCA outputs)
laptop with Ableton Live
Mackie Fx Pro 12 mixer

Mixer offers 1/4 inch line ins per each channel and few RCA labeled "unbalanced" - I am not sure what this means in this situtation.

Question: How do I connect interface to mixer, in order to hear interface output in the monitors?
Thank you for your consideration.
Comment: Here (in Poland) word "kolumna" _singular_ / "kolumny" _plural_ is used loosely to mention various specialized and/or high end speakers of considerable power. And most likely it stems from popularization of the standard mentioned by you.
Comment: I can't figure out what you mean by "columns", by the way. That's not a term normally used to describe a part of an audio mixer.
Comment: "Columns" would be local word for "monitor speakers". Apologies for the confusion.
Comment: Interesting. Old people like me would be likely to call monitor speakers "wedges", since they used to be almost always wedge-shaped speaker cabinets on the floor. I guess a lot of people now use the new style of column speakers that Bose invented.
Answer: Those red and white outputs on the back of the Scarlett Solo are called RCA jacks. In the case of the Scarlett, those jacks are outputs. You can connect them to any RCA inputs using an RCA cable.
This is what an RCA cable looks like:

Get an RCA cable and connect it to the outputs of the Scalett, matching the red plug to the red jack and the white plug to the white jack. Plug the other end of the cable (white to white and red to red) into the left side of the group of four RCA jacks on the Mackie. That's the side the says "Tape In" to the left of the jacks.
Now look at the main fader, which is the one farthest to the right. Right above the main fader is a knob labelled "Tape Level". Play sound from your computer and turn the "Tape Level" knob slowly to the right until you hear the volume you want.
Image source: https://pisces.bbystatic.com/image2/BestBuy_US/images/products/4408/4408065_sa.jpg;maxHeight=640;maxWidth=550


COMO FAZER UM GetAsync em uma API ASP.NET passando um objeto como parâmetro?

Question: Gostaria de saber como faço para enviar um objeto como parâmetro para uma API feita em ASP.NET e retornar dados pela mesma?
Entendo que o método simples de um Get é:
HttpClient cliente = new HttpClient();

string url = "http://localhost:50501/api/values/ListaContatos";
var response = await cliente.GetStringAsync(url);
var contatos = JsonConvert.DeserializeObject<List<Contato>>(response);

return contatos;

... Como eu faria para enviar um objeto e retornar dados?
Answer: Tente algo assim:
using (var http = new HttpClient())
{
    var url = new Uri("http://localhost:50501/api/values/ListaContatos?id=1&nome=teste");
    var result = http.GetAsync(url).GetAwaiter().GetResult();
    var resultContent = result.Content.ReadAsStringAsync().GetAwaiter().GetResult();

    if (result.StatusCode != HttpStatusCode.OK)                {

        return null;
    }
    return JsonConvert.DeserializeObject<MyClass>(resultContent);
}


c# Mover imagem sem rastro

Question: Estou movendo uma picturebox por cima de outra com mouse. Porém ela fica deixando um rastro por trás quando mexo o mouse, o rastro some logo em seguida, mas, existe um jeito de remover isso?
Tentei tirar o refresh() quando a imagem move, tira o rastro mas ela trava demais, mexe muito lenta, fica dando trancos.
Aqui o código:
private void picImage_MouseMove(object sender, MouseEventArgs e)
    {

        if (picImage.Image == null)
            return;

        if(act)
        UpdateZoomedImage(e);

       picZoom.Location = new Point(e.X+40, e.Y+40);
       picZoom.Refresh();
    }

codigo do Zoom:
private void UpdateZoomedImage(MouseEventArgs e)
    {
        // Calculate the width and height of the portion of the image we want
        // to show in the picZoom picturebox. This value changes when the zoom
        // factor is changed.
        int zoomWidth = picZoom.Width / _ZoomFactor;
        int zoomHeight = picZoom.Height / _ZoomFactor;

        // Calculate the horizontal and vertical midpoints for the crosshair
        // cursor and correct centering of the new image
        int halfWidth = zoomWidth / 2;
        int halfHeight = zoomHeight / 2;

        // Create a new temporary bitmap to fit inside the picZoom picturebox
        Bitmap tempBitmap = new Bitmap(zoomWidth, zoomHeight, PixelFormat.Format24bppRgb);

        // Create a temporary Graphics object to work on the bitmap
        Graphics bmGraphics = Graphics.FromImage(tempBitmap);

        // Clear the bitmap with the selected backcolor
        bmGraphics.Clear(_BackColor);

        // Set the interpolation mode
        bmGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

        // Draw the portion of the main image onto the bitmap
        // The target rectangle is already known now.
        // Here the mouse position of the cursor on the main image is used to
        // cut out a portion of the main image.
        bmGraphics.DrawImage(picImage.Image,
                             new Rectangle(0, 0, zoomWidth, zoomHeight),
                             new Rectangle(e.X - halfWidth, e.Y - halfHeight, zoomWidth, zoomHeight),
                             GraphicsUnit.Pixel);

        // Draw the bitmap on the picZoom picturebox
        picZoom.Image = tempBitmap;

        // Draw a crosshair on the bitmap to simulate the cursor position
        bmGraphics.DrawLine(Pens.Black, halfWidth + 1, halfHeight - 4, halfWidth + 1, halfHeight - 1);
        bmGraphics.DrawLine(Pens.Black, halfWidth + 1, halfHeight + 6, halfWidth + 1, halfHeight + 3);
        bmGraphics.DrawLine(Pens.Black, halfWidth - 4, halfHeight + 1, halfWidth - 1, halfHeight + 1);
        bmGraphics.DrawLine(Pens.Black, halfWidth + 6, halfHeight + 1, halfWidth + 3, halfHeight + 1);

        // Dispose of the Graphics object
        bmGraphics.Dispose();

        // Refresh the picZoom picturebox to reflect the changes
        picZoom.Refresh();
    }

Comment: acredito que o problema seja, que a cada ponto movido do mouse, você redesenha a imagem completamente, não sei se funciona, mas tenta chamar o método `this.SuspendLayout();` do form, antes de desenhar, e depois que estiver pronto, o `this.ResumeLayout();`. Se não funcionar, colocaria um timer pra atrasar o processo de desenho, só executando-o uma vez, ao final do movimento.
Comment: qual o código do seu UpdateZoomedImage ?
Comment: Editei o post com o código.
Comment: Obrigado amigo, com timer funcionou perfeitamente.
Comment: que beleza! coloquei como resposta, se quiser marcar e fechar a questão =]
Answer: Acredito que o problema seja, que a cada ponto movido do mouse, você redesenha a imagem completamente, eu colocaria um Timer pra atrasar o processo de desenho, só executando-o uma vez, ao final do movimento.

c# Mover imagem sem rastro


Finding the parameterization of a circle given a tangent vector at a point

Question:
Find the curve whose curvature is 2, passes through the point (1,0) and whose tangent vector at (1,0) is $\begin{bmatrix} 1/2\\ \sqrt{3}/2 \end{bmatrix}$. Hint: Use the proof of the fundamental theorem of plane curves.

So this is a differential geometry problem, but it feels like it can be done with tricks from trigonometry and calculus. Since the curvature is constant, and we are in $\mathbb{R}^2$, we know that the curve is a circle of radius 1/2. so say we have a parameterization like $\alpha(t) = \frac{1}{2}(-\cos(t),\sin(t)) + \vec{p} ~~~~~~ t \in [0,2\pi]$. Where $\vec{p}$ is our center point. We could get $T(t) = \alpha'(t) = \frac{1}{2}(\sin(t),\cos(t))$ but from here is where I am stuck. We could set this equal to our given tangent vector but what would this tell us about $t\in[0,2\pi]$? is this approach even any good? is $\vec{p}$ the only thing I need to define this curve?
EDIT: I have solved it using the hint, but I would still like to know if it is doable using elementary techniques.
Answer: To solve the problem elementarily, note that if the tangent vector is rotated 90° counterclockwise around $(1,0)$, so that it becomes $(-\frac{\sqrt3}2,\frac12)$, it points towards the circle's centre. This vector conveniently has length 1, so halving it produces a vector that points from $(1,0)$ to the circle centre. This centre is therefore $(1,0)+\frac12(-\frac{\sqrt3}2,\frac12)=(1-\frac{\sqrt3}4,\frac14)$.
The parametrisation of the required curve is thus
$$\alpha(t)=\left(1-\frac{\sqrt3}4,\frac14\right)+\frac12(\cos t,\sin t),\ t\in[0,2\pi]$$
Answer: If the tangent vector is $t=\begin{bmatrix} 1/2\\ \sqrt{3}/2 \end{bmatrix}$ then the normal (outward) vector is $n=\begin{bmatrix} \sqrt{3}/2\\ -1/2 \end{bmatrix}$.
So $\begin{bmatrix} 1\\ 0 \end{bmatrix} -1/2 n$ gives you the center.


"drush rr" error

Question: I am trying to perform a simple drush rr in my drupal directory. I have been able to do this before, but all of a sudden this no longer works. I have made changes to my drupal site, but I have no idea what might be causing it.
The error is as follows:
chlong@chlong-Vostro-460:/var/www/drupal7$ drush rr
PHP Fatal error:  Call to undefined function lock_acquire() in /var/www/drupal7/includes/bootstrap.inc on line 3106
Drush command terminated abnormally due to an unrecoverable error.     [error]
Error: Call to undefined function lock_acquire() in
/var/www/drupal7/includes/bootstrap.inc, line 3106

Does anyone have any ideas on how to resolve this issue?
Comment: What is `rr` command for? I can't find it in docs.
Comment: @kalabro, the "rr" is "rebuild registry"
Answer: Newer versions of Drupal 7.x (7.13+), have added locking to the registry rebuild process. This means that the locking system now needs to be available to call that function.
drush rr specifically tries to include as less as possible, to be able to rebuild the registry before something can break.
For you, this simply means that you need to update your version of registry rebuild, as this has been fixed already.
That said, I am very much looking forward to Drupal 8, for which we are currently working hard to be able remove the registry in favor of a PSR-0 class loader that finds classes based on conventions and does not need to scan files to build up a mapping of class names to files.
Answer: It looks like your includes/lock.inc file has gone missing. If that's the case, you should download Drupal again.
Comment: I just checked, my 'includes/lock.inc' file is there.

"drush rr" error