Is $\dim \mathcal{L}(V,W)\ge |F|$ for infinite dimensional vector spaces $V$ and $W$?

Question: In Lemma 2 of this answer, it was shown that if $\dim V$ was infinite, then $\dim V^*\ge |F|$. As $V^*=\mathcal{L}(V,F)$, this led me to wonder if the same held for the general space of linear transformations $\mathcal{L}(V,W)$.
More concretely, if either $\dim V$ or $\dim W$ is infinite, does $\dim \mathcal{L}(V,W)\ge |F|$?
As far as I can see, my conjecture holds at least for the case when $\dim V$ is infinite, if we modify the proof for $\dim V^*\ge |F|$ slightly, as follows $-$
Consider an arbitrary non-zero vector $v\in W$. If we re-define $\mathbf{f}_c$ as $\mathbf{f}_c\colon V\to W$, $\mathbf{f}_c(\epsilon_n) = c^n v$ if $n\in\omega$, and $\mathbf{f}_c(\epsilon_i)=0$ if $i\geq\omega$. Then as $\alpha_1\mathbf{f}_{c_1} + \cdots + \alpha_m\mathbf{f}_{c_m} = \mathbf{0}$ implies
\begin{align}
(\alpha_1 c_1^i + \cdots + \alpha_m c_m^i)v &= 0 \\
\implies \alpha_1 c_1^i + \cdots + \alpha_m c_m^i &= 0,
\end{align}
the rest of the proof should proceed just as it did for $\dim V^*\ge |F|$. However, I have not been able to see if my conjecture is valid when $\dim W$ is infinite.
Answer: If $\dim V$ is infinite and $W$ is not $0$, then by choosing a non-zero vector $x\in W$, you get an inclusion :
$$\mathcal L(V,F) \hookrightarrow \mathcal L(V,W)$$
Therefore, $\dim\mathcal L(V,W) \geq |F|$ by the lemma you cite.
If $\dim V= n$ is finite and $\dim W = \kappa$ is infinite, then :
$$\mathcal L(V,W) \simeq W^n$$
Therefore $\dim \mathcal L(V,W) = \kappa^n = \kappa$, which can be $<|F|$.  (For example if $F = \mathbb R$ and $\kappa = \aleph_0$)
Comment: How do you show that $\mathcal L(V,W) \simeq W^n$?
Comment: Choose a basis $(e_i)$ of $V$. A linear map $f\in\mathcal L(V,W)$ is uniquely defined by the $f(e_i)$.


Constructing one-ninth fraction of the $3^{5}$ design

Question: I want to construct a $3^{5-2}$ design with $I=ABC$ and $I=CDE$ as generators. The complete defining relation for this design is: $I=ABC=CDE=ABC^{2}DE=ABD^{2}E^{2}$. This is a resolution III design with $x_4=2x_1+2x_2+x_3$ and $x_5=x_1+x_2+2x_4\:({\rm mod}\:3)$.
Question
I wonder how to get $x_4=2x_1+2x_2+x_3$ and $x5=x_1+x_2+2x_4\:({\rm mod}\:3)$ in this specific problem.
Edited

This is a question from Design and Analysis of Experiments by Douglas C. Montgomery.
Answer: Allow me to begin with the qualification that algebra is not my strong suit and in my area (industrial statistics) we use fractionated three-level factorials almost never.  Is it possible there's an error in your question?  I've generated the design given the $x_k$'s and it appears that the words you give are not actually words.  I also worked out the columns given $I=ABC=CDE$ and got a different design.

Words Given the Design Construction
I went ahead and constructed your design from the $x_k$'s you give using R:
<code>X<-as.data.frame(expand.grid(c(0:2),c(0:2),c(0:2)))
colnames(X)<-c("A","B","C")
X[,"D"] <- (2*X[,"A"] + 2*X[,"B"] + X[,"C"]) %% 3
X[,"E"] <- (X[,"A"] + X[,"B"] + 2*X[,"D"]) %% 3
</code>
When I did both
<code>(X[,"A"]+X[,"B"]+X[,"C"]) %% 3
</code>
and
<code>(X[,"C"]+X[,"D"]+X[,"E"]) %% 3
</code>
I get
<code>[1] 0 1 2 1 2 0 2 0 1 1 2 0 2 0 1 0 1 2 2 0 1 0 1 2 1 2 0
</code>
which suggests neither $ABC$ nor $CDE$ are words.  Let $A=x_1$,...,$E=x_5$ and assume addition on $\mathbb{F}_3$.  Then given
\begin{align}
D&=2A+2B+C,\\
E&=A+B+2D,
\end{align}
we have
\begin{align}
2D &= A + B + 2C\\
E &= 2A + 2B + 2C\\
A+B+C+E &= 0\\
\end{align}
so $I=ABCE$ should be a word.  Indeed, in R
<code>(X[,"A"]+X[,"B"]+X[,"C"]+X[,"E"]) %% 3
</code>
yields
<code> [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>
Similarly,
\begin{align}
A+B+D&=C \\
A+B+2C+D &= 0
\end{align}
so I'd expect $I=ABC^2D$ to be a word, and in R we find
<code>(X[,"A"]+X[,"B"]+2*X[,"C"]+X[,"D"]) %% 3
</code>
yields
<code>[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>
It appears that the words are
\begin{align}
I=ABCE=ABC^2D=A^2B^2C^2E^2=A^2B^2CD^2=A^2B^2DE=ABD^2E^2=CDE^2=C^2D^2E.
\end{align}

Design Construction Given the Words
Going the other way, let $A+B+C=0$ and $C+D+E=0$ then
\begin{align}
C&=2A+2B\\
2C&=A+B\\
E&=2C+2D = A+B+2D.
\end{align}
It is more convenient (for me, at least) to treat $A$,$B$, and $D$ as coming from the $3^3$ and solve for $C$ and $E$.  We can express $D$ as
\begin{align}
D &= 2C + 2E \\
&= A+B+2E \\
&= 2A+ 2B+C+2E
\end{align}
but since no word contains something that's not a multiple of $DE$ (or $D+E$ in my notation) it's not possible to solve for both independently of each other.
Comment: (+1): Thanks @neverknowsbest for your answer. Please my edits too. Thanks
Comment: He's my PhD advisor.  Was the formula for D and E in the student solutions manual or the book? I can follow up with him if so.
Comment: Formula for D and E are given in the student solution manual. I believe these formulas are not correct. Might be typo in question too.
Comment: I guess they'll look at it after the end of the semester.
Comment: That would be very late.
Comment: I'm stilling looking the answer.


Runing Total sum minus different condition

Question: I looked at some SQL Server running total examples, but I can't manage thing like this.
I have a table where I have columns id, name, type of operation, date, value.
I want to calculate balance for each record. Balance should be calculated like this:
Starting balance must be 0 and then if operation type is IN there will be plus, if operation is OUT there will be minus. Each next record should see previous record balance and then +value or -value depending on operation Type.
This operation should be ordered by date (not Id).
For example, if the table looks like this:
ID Name  Op_Type Date       Value
1  box   Out     2017-05-13 15
2  table In      2017-04-31 65
3  box2  In      2017-05-31 65

then result should look like this
ID Name  Op_Type Date       Value Balance
2  table In      2017-04-31 65     65
1  box   Out     2017-05-13 15     50
3  box2  In      2017-05-31 65     115

result of this code :
select *,
       sum(case when Op_Type = 'Out' then -Value else Value end)Over(Order by [Date]) as Balance
From Yourtable

is:
ID  Date        Type        Value       Balance
143 2016-12-31  In          980         664.75
89  2016-12-31  Out         300         664.75
90  2016-12-31  Out         80          664.75

But I expect the following result:
ID  Date        Type        Value       Balance
143 2016-12-31  In          980         980
89  2016-12-31  Out         300         680
90  2016-12-31  Out         80          600

Comment: Please use punctuation, this question is one long sentence, which is difficult to read. Have you tried anything? There are many tutorials online on how to calculate running totals and conditional aggregation. Also, which version of sql-server do you use?
Comment: what platform is this for? is it for an RDBMS?
Comment: yah i have tried somthing  but in most case i am getting wrong numbers in some rows or somthing like that :/ and it's not calculating with prev rows
Comment: @Wuhu - All the dates are same. What is the result you are expecting /
Comment: 0+980-300-80 this iwhat i want
Comment: How you are getting that order ? All the dates are same right
Comment: it is example there will be datee changed like 2017-05-03 this it is just ordering by date 3 record change with 2017-05-03 it is just first 3 records for example
Comment: The solution suggested by @Prdp only works if the `order by` attribute (combination) is *unique*. Your `Date` column is not unique, so the result is unpredictable. It's important here to remember that data stored in a table in inherently unsorted, so the order you see doesn't mean anything if you haven't specified an `order by`
Comment: @Wuhu - In database you can never say *just first 3 records*. To identify first 3 records there should be some order.
Comment: you don't get i don't meaning first 3 recored it is just examplee mann just example .... the result of query there is tones of recoreds and just i give you 3 for examplee
Answer: The problem with answer by Prdp is that SUM(...) OVER (ORDER BY ...) by default uses RANGE option instead of ROW.
This is why you see unexpected results when dates are not unique. This is how the default RANGE option works.
To get results that you expect spell it our explicitly:
SELECT
    *
    ,SUM(CASE WHEN Op_Type = 'Out'
        THEN -Value ELSE Value END)
    OVER(ORDER BY [Date], Op_Type, ID
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Balance
FROM YourTable
ORDER BY [Date], Op_Type, ID;

I also added Op_Type into the ORDER BY to add positive values first in cases when there are several rows with the same date.
I added ID into the ORDER BY to make results stable in cases when there are several rows with the same date.
Comment: 1 question it is work fine but 1 question i have when i am pointing time period like SELECT
    *
    ,SUM(CASE WHEN Op_Type = 'Out'
        THEN -Value ELSE Value END)
    OVER(ORDER BY [Date], Op_Type, ID
    ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS Balance
FROM YourTable
ORDER BY [Date], Op_Type, ID where date>=2017-01-05 AND date<=2017-01-17 it is not starting calculating balance from bigining of the time it is starting from 2017-01-05 i want to display this period but calc from begining
Comment: @Wuhu, essentially you need to run two queries. First will be a simple `SUM` (not running total) from beginning of time till `2017-01-05`. Remember the calculated sum and then add it to each row in the main query with the running total.


Arrastar div para outra div e redimensionar ao soltar!

Question: Boa noite, galera! basicamente o que estou querendo fazer é arrastar uma div (#mainmsg) para dentro de uma outra div (#msgprivhere), porém preciso que, ao soltar, ela seja redimensionada. Apenas gostaria de saber se isso é possível. Estou iniciando na área de web desenvolvimento, e sou muito leigo.
desde já agradeço!
não tenho preferencia por linguagem não. Se existir uma possibilidade, eu gostaria de tentar.
Agradeço a quem puder responder!

                                 Oliver Motokh
                                 12:34 pm
                                 heeooooyuuuo

                                    Oliver Motokh
                                     12:34 pm
                                     heeeeyyyyyyooooooooooooy

Answer: Olá.
Você pode utilizar a função onDrop do Javascript:

Na função você redimensiona utilizando jQuery, manipulando o css da div.
Espero ter ajudado.
** Atualização
Conforme solicitado, estou colocando um exemplo mais completo de como fazer isso, usando jQuery:
No HTML:

No JavaScript:
function mover() {
   $("#movimento").css({"width":"500px","height":"400px"});
}


Quantile Regression: follow up methods to have a more fine-grained understanding of what the results really mean?

Question: I recently employed multiple quantile regression in my area of research and found some interesting quantile differences across the distribution of Y, but I don't quite understand what they all really mean.  Unlike the traditional methods such as dividing the sample into multiple groups where I have access to the groups' data on various variables which then allows me to make sense of, for example, why the correlation between X and Y is 0 for group 1 and .7 for group 2, I feel like I have no idea where those quantile regression estimates come from, especially when there are more than 2 predictors in the QR model. Another way of putting this is I don't know which specific data points contribute heavily to a given quantile regression estimate and so this makes it very difficult for me to understand what the quantile differences really mean.
Based on my understanding of QR, it uses all the data points in the full sample but weights the data points that are farther from a quantile of interest less heavily than the data points that are closer to that same quantile of interest, is this correct? If so, as a follow up, can I divide my full sample into 10 groups, e.g., 10th quantile, 20th quantile, 30th quantile group, and then examine how the 10 groups differ on various variables of interest in order to make sense of the 10 quantile regression estimates that I got? I know the subgroups approach is not ideal, which is why I used QR, but if you think this is a terrible idea, please let me know why. And if you know of any other methods  that allow me to have a more fine-grained understanding of my results, please help.  I conducted QR using the quantreg package in R.
Answer: You have alot of questions here, I will attempt to answer some of them to the best of my understanding. In my opinion the best way to understand what quantile regression is doing is to consider what regular linear regression does and compare it to quantile regression on the median (special case). Regular linear regression asks how does X affect Y on average (mean), while median quantile regression asks how does X affect median of Y. This is initially how quantile regression was developed, and it was later extended to any quantile of interest. So lets say im interested in the 10th percentile and the 90th percentile, quantile regression allows to me ask, how does the variable X affect the position (or estimate or value) of the 10th percentile of Y and the 90th percentile of Y.
So quantile regression is not weighting your samples, it is simply estimating the effect of X on Y, but rather than the effect operating on the mean of Y (as in regular linear regression) it is estimating the effect of X on the quantile (eg 10th or 90th) of Y.
The main problem with subgroup analysis is the dramatic reduction in power, you are basically reducing sample size by considering smaller and smaller groups. If you have extremely large sample sizes and/or large effect sizes, then subgroup analysis is not so bad, but if not you will not have to the power to detect effects in the subgroups.
Answer: QR does not weigh in the data points differently. Here is how I would think about QR:
In the QR, quantiles are defined on the response variable (y).
What QR tells you is the effect of your predictor variable (X) at different quantiles of your response (Y) variable.
Consider the following regression (Don't worry too much about other things that might come into play in this regression):
Wage = b0 +b1*age+……
In a linear regression setup the coefficient on age tells you the effect of age on salary. Whereas, in the QR setup you will get to see the effect of age on different quantiles of the response variable.
Ex: QR will tell you whether age has a different effect on the top 10% of the wage earners than the bottom 10% of the wage earners


Em PHP existe suporte à Bluetooth?

Question: Se não, em geral (web) existe suporte à bluetooth? Existe algum meio de fazer a comunicação entre PORT COM (Bluetooth) para web?
Comment: seria mais fácil alguém te dar uma resposta para seu problema se souber o que você pretende fazer. Mas em termos gerais você consegue ler as portas COM através com PHP basicamente como um middleware, como por exemplo: http://www.phpclasses.org/browse/file/17926.html
Comment: Sendo mais especifico, diretamente desejo usar/instanciar um controlador Bluetooth via WEB, uma pagina web que o usuário faça controle do dispositivo bluetooth. Por exemplo em C# faço esse controle referenciando a bibliote 32feet
Answer: O controle do Bluetooth só vai funcionar no servidor (no lado do servidor), ou seja se o usuário acessar do computador dele ele só vai conseguir enviar "comandos", mas a máquina que vai estar executando isto é o servidor.
Note que se um usuário acessar o Bluetooh, este mesmo ficará ocupado e outros usuários não poderão acessar até que o primeiro termine o processo.
Provavelmente a classe https://github.com/Xowap/PHP-Serial usada nesta pergunta deve ter o mesmo objetivo.
Windows:

Abra o executar ou cmd
Digite %SystemRoot%\system32\control.exe ou abra o painel de controle
Vá até "gerenciador de dispositivos"
Procure por "Bluetooth radios" (algo semelhante)
Selecione o dispositivo Bluetooth desejado com o botão direito do mouse e vá até propriedades
Clique na aba Detalhes, deve aparecer o nome e em seguida a porta, por exemplo Bluetooh (COM 17)

Linux
No linux o dispositivo deve está como /dev/rfcomm0
Usando
O script php deve ficar assim:
<?php
include 'PhpSerial.php';

$serial = new PhpSerial;
$serial->deviceSet('/dev/rfcomm0'); # No windows deve ser deviceSet('COM17')

Agora se você quiser enviar do bluetooth do computador do visitante, será necessário uma tecnologia como java

Em PHP existe suporte à Bluetooth?


How to create a flyout menu with Views?

Question: I am trying to achieve the following output- id like a view with two images- each displaying a corresponding menu on hover- I've looked at using rewrite result for an image field in views for this- but I don't think I am using it properly. I would be tremendously grateful if anybody could take the time to give me some tips or tutorials on how to do this?
Note: I am a drupal-newbie.
Comment: are you need to do something or have problem to achieve with drupal?
Please write more details about what you need/have? we could help better in that case
Comment: Your question is not clear enough. Can you please provide more detail on what you wanna achieve and what have you did yet?
Comment: For a expandable menu, I believe superfish module should be used instead of views.
Answer: Views maybe isn't the best solution to your problem. Drupal has a built in way to create menus. When you created your two menus and maybe placed them on your site with Menu Block, you then may apply the flyout functionality with CSS or jQuery or have a look at Superfish maybe.

How to create a flyout menu with Views?


Robust handling of the pager in an Ajax controlled View, when URI is shared with another user?

Question: I have a gallery content type, it references a number of images. When viewing gallery content, a View renders a gallery image, and a pager set to display a single item at a time allows the user to go back and forth with a link that will change the url.
As a user, I can now copy the URL and send it to someone else, who will see exactly the same image.
Problems show up however, when we decide to load only the new image, instead of the whole page, with JS. Since we no longer change the url, the JS-using user will remain at page=0 all the time, and can no longer share this URL as intended.
I have two suggestions of my own, but I haven't implemented either yet, and would love to hear either comments on those, different answers, or just votes on whichever answer you think is the best.
Answer: With Javascript, I could manipulate the # value of the URL without triggering a page reload. Using this, a custom Javascript pager could be implemented, that will override the ?page value with any #page value instead. Unfortunately that would mean loading two images. This way, paging with JS will update the #page value, and this url can then shared and get the intended behavior.
Comment: I haven't implemented a custom pager for views before, but does it work on the client side? The `#` part of a URL isn't sent to the server so there would have to be some client-side manipulation/loading of the view whenever the `#` portion of the url changes, or whenever a page is visited directly
Comment: Your right, I didn't consider that. A custom pager doesn't make sense at all then. Unless you'll do it, I'll post a different suggestion then.
Comment: I think it's still valid, just not the `#` part...for HTML5 browsers it is possible to [modify the url without refreshing the page](http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page); it seems you might be able to use that technique in place of the `#` if that makes sense?
Comment: Yeah, but the custom "paging" would need to be implemented client side instead, so that a link to ?page=Y#page=X will start at Y, but then move to X. I've updated the answer to remove the Views reference.
Answer: When using Javascript, the next/previous button could manipulate the # part of the URL with a page=X variable, and then if this is sent somewhere using a service like facebook or twitter, we just parse the #page=X into ?page=Y instead. If the url is copied directly, then we manipulate the copied text with JS to remove the # and move it's value into ?.
I believe I've seen such JS url-mangling practices before, but I also though that browsers protected the clipboard from manipulation with JS.


How to fix Google Play Services 2 Library install to Eclipse

Question: I've tried to follow https://developer.android.com/google/play-services/setup.html instructions in Eclipse for Mobile Developers (Juno), but am getting multiple errors with the library package after importing the library project into my workspace.  I fixed the AndroidManifest.xml error it reported, but now I can't open the project in Eclipse saying the .project  description file contains invalid information.  So much for a simple install.  I've tried uninstalling it, redownloading it, and I still get the multiple errors.  Any suggesions how to get it working?
Answer: There is a misleading step in step 3 of http://developer.android.com/google/play-services/setup.html:

Copy the
  /extras/google/google_play_services/libproject/google-play-services_lib
  library project into the source tree where you maintain your Android
  app projects.
If you are using Eclipse, import the library project into your
  workspace. Click File > Import, select Android > Existing Android Code
  into Workspace, and browse to the copy of the library project to
  import it.

Don't do the first copy.  Instead just do the second part and check the box that says "Copy projects into workspace".  I found that if I did the first part I would end up with empty xml files.
Comment: +1 because, You mentioned: Instead just do the second part and check the box that says "Copy projects into workspace"
Comment: So after copying project to workspace, what happens when there is an update?
Answer: Try the following :
<code>https://developers.google.com/maps/documentation/android/intro#sample_code
</code>
You would get errors while opening an activity mentioned in the sample code. That is because android.support.v4.app.FragmentActivity is not added to your build path. Hover over the error and click on "Fix Project Setup". It would ask you to add the lib to the build path. Say Yes and enjoy :)
Answer: If your google_pay_services/libproject is empty (mine was empty) and looks like installed in sdk manager, first delete google play services from sdk manager, install it again and follow the steps in the first answer.
Answer: Try Window > Android SDK Manager > Extras > Google play service > Delete package.
And then re-install that package again:
File > Import, select Android > Existing Android Code into Workspace
Answer: I had the same problem.  I went to Properties->Java Build Path and clicked on the Projects tab.  Then I added google-play-services_lib using the Add button.  This got me this run-time exception:
E/AndroidRuntime(9469): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
So then I changed the main.xml file entry from this:
<code>      android:name="com.google.android.gms.maps.MapFragment"
</code>
to this:
<code>    android:name="com.google.android.gms.maps.SupportMapFragment"
</code>
And FINALLY, it runs, but NOW no map due to authorization failure.  So I am off on another search.
thanks Google for making it so complicated and for posting incorrect instructions!


Panel data estimation for country-fixed, time-varying share of y

Question: I want to estimate the following equation using a panel data set with countries $i$ and years $t$, preferably in R:
$$
y_{it} = \beta_1 \cdot x_{1,it} + \beta_2 \cdot x_{2,it} + \epsilon_{it}
$$
However, I cannot observe $y_{it}$ directly. Instead, I can only observe $\tilde y_{it} = s_i \cdot y_{it}$, where $s_i$ is a share of $y_{it}$ that varies across countries, but not over time. $s_i$ is not observable. If it were observable, I could probably just substitute and estimate
$$
\tilde y_{it} = \beta_1 \cdot x_{1,it} \cdot s_i + \beta_2 \cdot x_{2,it} \cdot s_i + \epsilon_{it}
$$
directly.
Is there a way to estimate the above relationship given my data constraints? It somehow feels like a problem that can be addressed using country dummies (i.e. a fixed-effects model) or a random-effects model, but I cannot seem to figure it out.
Comment: Unfortunately, I have negative independent variables, but I might be willing to drop one (the only) negative variable if this turns out to be the only way to estimate the model. How would I do this exactly, though? If I take the log of the right-hand side, I end up with $log(... + ...)$, don't I? That wouldn't be a linear term anymore. (EDIT: This comment is the answer to another comment that was deleted in the meantime: "If all your variables are positive, you can take logs and estimate a fixed-effects model.")
Comment: If the first model is true, then multiplying both sides by $s_i$  we get that either $\tilde{y}_{it}=\beta_1\tilde{x}_{1,it}+...$ or $\tilde{y}_{it}=\beta_{i1}x_{1,it}+...$, where  $\beta_{i1}=s_i\beta_1$. Since $s_i$ is not observable, it is only possible to estimate the second model. But this model has different coefficients for different $i$, so it is not a panel data model. If you have sufficient data you can simply estimated individual regression for each $i$. Adding individual country dummies  and their interactions would result in the same model.
Comment: @mpiktas: Thanks! Estimating individual regressions would be an option. I just wonder whether it isn't possible to somehow use the information that all $\beta$s contain the same $s_i$, to either estimate or at least pull out the $s_i$ somhow.
Comment: $s_i$ comes into model non-linearly, via multiplication, while the usual panel data techniques are designed to deal with linear effects.
Answer: Since you have enough of the data to estimate individual regressions, you can at least get a sense of $s_i$ in the following way.

Estimate individual regressions, get the estimates $\beta_{i1},\beta_{i2}$
Choose base country $k$
Calculate the ratios: $\beta_{k1}/\beta_{i2}$, $\beta_{k2}/\beta_{i2}$, for all $i$.
If the original hypothesis holds, these ratios should be equal to $s_k/s_i$.
If the equality is feasible, multiply all countries $i$ by estimated ratios $s_k/s_i$. You get the equation:

$$y_{it}s_k = \beta_1 x_{1,it}s_k + \beta_2 x_{2,it}s_k + \varepsilon_{it}s_k$$
All of the variables are observed, so you can estimate this using panel data.

Given $\beta_1$ and $\beta_2$ you can calculate $s_i$ as $\beta_{i1}/\beta_{1}$ and $\beta_{i2}/\beta_2$.

This is not a strict statistical procedure, but you at least will get a feeling whether your original hypothesis holds.


If a user has been deleted, delete also the user's files

Question: I want to know how to delete the files uploaded by the user after he/she has been deleted.
Whenever I delete a user, it only deletes the data on the database. But I want is to also delete the files in the file system.

NOTE: I'm using Wordpress. rmdir() and unlink() isn't working.

Please help! I tried Googling it, but there's nothing.
UPDATE: Thanks to pr1nc3 for the function.
But it's not yet done.
add_action( 'delete_user', 'delete_user_dir' );
function delete_user_dir( $user_id ) {
 global $wpdb;

 $files = 'wp-content/uploads/user/';
 $deluser = $wpdb->get_results( "SELECT user_login FROM " .$wpdb->user ." WHERE ID=".$user_id );
}

wp-content/uploads/user/Array <- OUTPUT
For the rmdir() and unlink it works. But it can't find the path I want to delete because of this.
I found on my research I need to move the global $wpdb before the function is fired. But it returns an error...
Call to a member function get_results() on a non-object.
Comment: ` rmdir() and unlink() isn't working.`, but why?
Comment: Check the file and folder permission..
Comment: Are any of the user's files left in the media library? http://en.support.wordpress.com/media/deleting-files/
Comment: @Raj Mohan CHMOD doesn't have to do with it because the parent directory is already 777. I just need is whenever an administrator deletes a member of the site, it also automatically delete the user's folder. But thanks for that suggestion.
Comment: @DavidEugenePeterson the files are inside a subdirectory in the wp-content directory. The files are uploaded straight to the database and file system.
Comment: I think you need to hot code the folder and file delete in the action of delete user....
Comment: @xdazz I don't know. But maybe, I just put it in the wrong function. If that's it, I can't find the wp_delete_user function inside wp-includes/user.php
Comment: @RajMohan I'm using 3.7.1. 3.8 has that kind of function but I'm not permitted to upgrade it to 3.8.
Answer: This Function Would run everytime when user is deleted
$user_id is id of that deleted user
 function my_delete_user( $user_id ) {
    --> Get All posts created by $user_id
    --> Loop All posts to get attachments for each posts
    --> Finally delete each attachment using wp_delete_attachment

    }

add_action( 'delete_user', 'my_delete_user' );

Refer here
Delete Attachment
Answer: I got it! Thanks for the help guys. :)
function delete_user_dir( $user_id ) {

 global $wpdb;
 $url = home_url('/');
 $folder = 'wp-content/uploads/user/';
 $deluser = get_userdata( $user_id );

 $files = glob($url. $folder . $deluser->user_login .'/*');

 if(is_array($files)){
    foreach($files as $file){
      if(is_file($file))
        unlink($file);
    };

    rmdir($url. $folder . $deluser->user_login .'/');

 }else{
    rmdir($url. $folder . $deluser->user_login .'/*');
 }
}

add_action( 'delete_user', 'delete_user_dir' );


GAE - Java - Best way to do a query filter "LIKE"

Question:
In my GAE Datastore I have "Person" Entity with name, surname and country
I need to do a query like
"SELECT * FROM Country WHERE name LIKE '%spa%'"
This answer offers a solution like this:
Query query = new Query("Person");
query.addFilter("name", FilterOperator.GREATER_THAN_OR_EQUAL, "pe");
query.addFilter("name", FilterOperator.LESS_THAN, "pe"+ "\uFFFD");

But I don't have any success, always return 0 results... I'm missing something?
It seems that another alternative is useing the "Search API", but... How I migrate all my data of "Persons" in my Datastore to a new Document to do the search?
Any solutions?
Thanks
Answer: That answer is not the same as your question. The query they provide is a prefix query: ie all names that start with "pe". You seem to want a query for all names which contain "pe" anywhere, which is not possible for the reasons explained in the accepted answer to that question.
The Search API is indeed the answer to doing this, and the details of how to create documents to represent your datastore objects are contained in the link you posted. (Note this isn't a migration: your data should stay in the datastore, the Search API is a separate system used only for full-text search.)


Sort a 2-D matrix elements from largest to smallest, tracking ij indices too

Question: Given an upper triangular matrix (or lower triangular)
A = np.array([[1, 2, 3],
              [0, 4, 5],
              [0, 0, 6]]
             )

I would like to sort its values from largest to smallest, keeping track of the ij indices, so for instance in this matrix I would want something like
6, (2,2)
5, (1,2)
4, (1,1)
3, (0,2)
2, (0,1)
1, (0,0)

This simple example uses a matrix with integers, but it should handle floats as well as arbitrarily large matrices, generally between 10x10 and 40x40. Speed is not very important, it is a one time operation. Also, it need not be upper or lower, the matrix is symmetrical, so I can simply fill in the opposite triangle if that is easier.
I have tried np.argsort() but that just gives
array([[0, 1, 2],
       [0, 1, 2],
       [0, 1, 2]], dtype=int64)

which is to say, it sorts each row independently. This doesn't help much since I don't want a list of the largest elements in each row, it could be that one row has all of the largest values.
Comment: `np.dstack(np.unravel_index(np.argsort(-A.ravel()), (3, 3)))` ? source : https://stackoverflow.com/a/30577520/12502959
Comment: I just edited it to order in the way you want
Comment: @python_user So you don't want to "claim credit" by making it your answer, which is very honest of you; still, comments tend to disappear, and this answers the question. If anyone with a similar question finds this page in the future because of a search engine, and it is neither marked as a duplicate nor answered, they'll be disappointed. Note that you can tick the "community answer" box when writing an answer if you really don't want credit.
Comment: @python_user I think that works, it orders it in reverse, but that isn't a big deal
Comment: @python_user I guess you might as well post this one-liner as an answer.
Comment: @Stef other than the making the array negative, I did not really change anything from the source, if anything, this can be a dupe of that, but my numpy skills are not good enough to confidently mark it a dupe
Answer: You can use the code shown in this answer, (provided you negate your array) to perform a "2d argsort".
>>> A = np.array([[1, 2, 3], [0, 4, 5], [0, 0, 6]])

>>> A
array([[1, 2, 3],
       [0, 4, 5],
       [0, 0, 6]])

>>> np.dstack(np.unravel_index(np.argsort(-A.ravel()), (3, 3)))
array([[[2, 2],
        [1, 2],
        [1, 1],
        [0, 2],
        [0, 1],
        [0, 0],
        [1, 0],
        [2, 0],
        [2, 1]]], dtype=int64)

PS : If any user who is confident of their numpy skills feel this should be a dupe do mark it, in the mean time this will be a "Community Wiki" as suggested by Stef in the comments.


Redirect comment permalink to their corresponding node paths

Question: Is there any way in drupal to  redirect comment permalink to their corresponding node paths or url alias?
I want to redirect all comment/x paths to their corresponding node-path. And it should handle pagers as well. If your comment is in the second page (when you have set a comments-per-page value in node type settings), it should be like
http://example.com/comment/111 to http://example.com/node/123?page=1#comment-111
http://example.com/comment/111 to http://example.com/node/123#comment-111
http://example.com/comment/112 to http://example.com/node/123#comment-112

Thanks in Advance!
Comment: It can be done programmatically I think. By using `hook_preprocess_page`.
Comment: @SumitMadan Thanks for ur comment. But I somehow managed to acheive it through hook_menu_alter
Answer: I managed to acheive it through hook_menu_alter. It just works great for me
<?php
/**
* Implements hook_menu_alter.
* @author Md Eqbal Ahmad <*****@******.com>
*/
function MODULE_menu_alter(&$items) {
  $items['comment/%']['page callback'] = 'MODULE_commentpermalink';
}

/**
 * Redirect comment permalink to their corresponding node paths
 * @author Md Eqbal Ahmad <*****@*****.com>
*/
function MODULE_commentpermalink($cid) {
  if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
    // Find the current display page for this comment.
    $page = comment_get_display_page($comment->cid, $node->type);
    // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
    if ($page > 0) {
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
    }
    else{
      drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
    }
  }
  drupal_not_found();
}

?>

Comment: I thinks, this is not a right way to do. `hook_page_process` is more better way than this. `hook_menu_alter` means you are altering the page content.
Comment: @SumitMadan I will be highly obliged, if possible, if u provide a code snippet  using hook_page_process to redirect comment permalink to their corresponding node paths as ur Answer to the question
Comment: checkout my answer.
Comment: @SumitMadan Thanks for ur answers! I have a question that dont u think redirection at hook_page_process has a slow page loading issue. The bulk content array is generated and then u are opting for redirection to load the same page content.
Comment: I dont think so. I never found any issue with this option.
Comment: @SumitMadan Conceptually I find `hook_menu_alter` a better stage to redirect rather than at `hook_process_page` or a similar approach could be at `hook_init`. But I really appreciate ur valuable comment . Its really nice intracting with u.
Answer: Try it using hook_preprocess_page :
function MODULE_preprocess_page(&$vars) {
      if (arg(0) == 'comment') {
        $cid = arg(1);
        if (($comment = comment_load($cid)) && ($node = node_load($comment->nid))) {
          // Find the current display page for this comment.
          $page = comment_get_display_page($comment->cid, $node->type);
          // Now, rather than setting menu_executive_active_handler and changin $_GET valies, we redirect them to the actual node URL with fragments and pager set.
          if ($page > 0) {
            drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid",'query'=>array('page'=>$page)), 301);
          }
          else{
            drupal_goto("node/$comment->nid", array('fragment'=>"comment-$comment->cid"), 301);
          }
        }
        drupal_not_found();
      }
    }


Does milvus2.0 support restful API?

Question: Milvus1.x can support restful API. I can find some docs from here.
But I don't find restful API docs for Milvus2.0.
Comment: Off-site resource requests are off-topic
Comment: Please reqd [ask] and take a [tour]
Answer: I found out from this page that restful API is under development.

Does milvus2.0 support restful API?


How to ignore Make output at quickfix in vim?

Question: What is the desired behaviour of vim's quickfix feature?
Should the quickfix window (:copen) only contain compiler errors/warnings or should the whole output be displayed?
I want the former, since the output of make can be very long, but I get the latter, even with compiler set to gcc and g:compiler_gcc_ignore_unmatched_lines set.
However, lines inside the quickfix window with warnings/errors are highlighted and :cnext correctly jumps to the next issue.
Furthermore, Lines without issues have a double pipe symbol prefixed, so it seems that vim properly parses the make output.
Are these lines displayed in addition to the warnings/errors and can be hidden or does the errorformat string not exactly match the make output?
I used the avrdude 5.11.1 sources as an example, but I get the same result with many other projects.
Does setting the compiler automatically adapt the errorformat string or do I have to set that string always manually?
Thanks
Answer: It's really however you want it to work. I often filter out some of the build output that I'm not interested in by adding grep to my makeprg, but I also want some of the build output even if it's not an error.
I don't think vim will remove non-error lines from the quickfix. If you don't want them there, you need to filter them yourself (or modify efm to include them in an error).


Is this fair or foul?

Question: If a ball is batted in foul territory and is fielded in foul territory but the ball bounces off the fielders glove and lands in fair territory, is it fair or Foul?
Answer: The ball is foul and the play is dead.
The rulebook reference defines a fair ball (Definitions section, page 142 in linked version):

A FAIR BALL is a batted ball that settles on fair ground between home
and first base, or between home and third base, or that is on or over
fair territory when bounding to the outfield past first or third base,
or that touches first, second or third base, or that first falls on
fair territory on or beyond first base or third base, or that, while
on or over fair territory touches the person of an umpire or player,
or that, while over fair territory, passes out of the playing field in
flight.
A fair fly shall be judged according to the relative position
of the ball and the foul line, including the foul pole, and not as to
whether the fielder is on fair or foul territory at the time he
touches the ball

The ball in the scenario touched a person not over fair territory, but over foul territory.  The place it eventually struck the ground after such a contact is not relevant.

Is this fair or foul?


Getting redundant records

Question:
$result = $query->entityCondition('entity_type', 'node')

->entityCondition('bundle', 'mypage')
    ->fieldCondition('field_mymodule_module','tid', 123,'=')
     ->execute();

$nids = array_keys($result['node']);
$or = db_or();
foreach($nids as $nid)

$or->condition('m.entity_id', $nid, '=');

$query2 = db_select('metatag', 'm')

->fields('m', array('entity_id', 'revision_id', 'language', 'data'))
    ->condition('m.entity_type', 'node')
    ->condition($or)
    ->orderBy('entity_id')
    ->orderby('revision_id')
    ->execute();

while ($record = $query2->fetchAssoc()) {

<code>dpm($record);
</code>
}

As you can see in above code, I'm trying to get metadata information of each node. Getting nids of them turns out to be easy. However, when I use those nids to retrieve metadata, I get so many identical ones. That problem persists even after I removed "or" statement from the db_select and hard-coded entity_id, it returns like 10 identical records. Can anyone shed a light on the problem and where I am doing wrong here?
Comment: $or->condition('m.entity_id', $nids, '='); you are using $nids in this.use $nid in place of $nids
Comment: You are right but as I said in my post, I have dropped the whole "or" statement together and hardcoded the nid but it still returns redundant records. I just tested with db_query and constructed my own SQL statement just to make sure I'm not using db_select wrong, but the problem persists.
Comment: You got all all nodes id in $nids. have you checked that $nids contains unique nodes id
Comment: I did (with devel's dpm), there's only 11 of them and they are all unique.
Comment: This happens because in foreach you are using while loop. and it runs 11 times
Comment: checkout below code.hope it works for you
Comment: I found out why that's happening! It's because each node has multiple revisions so they have different revision_id. That's why I'm getting multiple results for the same node and I can filter that out with DISTINCT. Silly me. Thanks TBI!
Comment: thats good user30646 !
Answer: $result = $query->entityCondition('entity_type', 'node')
<code>        ->entityCondition('bundle', 'mypage')
        ->fieldCondition('field_mymodule_module','tid', 123,'=')
        ->execute();

    $nids = array_keys($result['node']);
    $array=array();

    foreach($nids as $nid)

{
    $query2 = db_select('metatag', 'm')

    ->fields('m', array('entity_id', 'revision_id', 'language', 'data')) ->condition('m.entity_type', 'node')
</code>
->condition('m.entity_id', $nid, '=')
->orderBy('entity_id')
->execute()->fetchAssoc();
<code>$array[]=$query2

        }

$array contains all fields value.traverese this array.
Hope this will give you result.
</code>

Getting redundant records


Check if a point is inside a rectangle (not knowing the coordinates, but knowing distances to vertices)

Question: I have to solve  the following problem:
I have 4 points (A, B, C, D) which form a rectangle, but I do not know their coordinates. I have another point (X), I do not know its coordinates either, but I know the distances between point X and all other 4 points (XA, XB, XC, XD). I need to be able to tell if X lies within a rectangle formed by A, B, C, D.
Any help appreciated.
Comment: Do you at least know the side lengths of the rectangle?
Comment: No, just the distances.
Comment: Is it true that the rectangle _must_ be ABCD (not any order, right)?  I think this plays a role in determining the answer.
Comment: @Jared The order might matter if you asked *'does there exist a rectangle for given set/sequence of distances?'* However OP assumes the rectangle exists, and then the problem is undecidable: there exist both a rectangle containing X and a rectangle with X outside (except when X is the center of a rectangle)
Answer: It seems it is impossible to know whether X is inside for sure. For example, if we had a rectangle ABCD and a point X inside of it, WLOG so that the vertical distance from X to CD is less than the vertical distance from X to AB, creating a new rectangle ABEF with EF parallel to AB and CD, but EF underneath X with the same vertical distance creates a new rectangle with exactly the same distances to the vertices, but with X outside.
(Low picture quality, which is why I hesitate to put a picture. But I also thought that my above explanation was sort of unclear, so I posted this too.)
Comment: Thanks, the picture is very helpful. Would it help add another check to eliminate ABEF - the angles (AXB, BXC, CXD, ...) must be less than 180 degrees?
Comment: Yes, if we knew the angles were all less than 180 degrees then we could conclude that X is inside the rectangle. This can be confirmed because you'd know the angles AXB, BXC, etc. have X as the interior angle of triangles AXB, BXC, etc. so that you could conclude that they were inside the rectangle. However, if an angle was greater than 180 degrees (such as EXF) then X is the exterior angle of EXF and that therefore X is not inside ABEF.
Answer: It's not possible in general:
<code>A . . . . . D . . A'
.           .     .
.           .     .
B . . . . . C . . B'
</code>
Let $X$ be the centre of $ABA'B'$.  Then $XA=XA'$ and $XB=XB'$, and of course $XC=XC$ and $XD=XD$.  But for suitable choice of $C$ and $D$, $X$ is inside $ABCD$ but not $A'B'CD$.
Answer: For any point $X$ inside the rectangle, except the rectangle's center, there exists another rectangle, which has the same vertices-to-X distances, but does not contain $X$. You can construct it by mirroring one of the rectangle's edges by an axis parallel to the edge and passing through $X$.
The opposite is also true: you can make a reverse construction for the $X$ outside a rectangle to find an appropriate rectangle containing $X$. If $X$ lies 'opposite to some edge', not to a corner, that is, when $X$ lies between two parallel lines containing two opposite sides of a rectangle, one side mirroring will suffice. If $X$ is 'opposite to a corner', that is it lies in the angle vertical to the rectangle's corner (see https://commons.wikimedia.org/wiki/File:Vertical_angles.svg), one needs two such mirrorings for two adjacent sides of the rectangle.
As a result,

if three of the four $AX$, $BX$, $CX$, $DX$ distances are equal, then $X$ is a center of the $ABCD$ rectangle (and the fourth distance must be equal to those three, too), so you know it is inside.
In any other case you can't tell whether $X$ is inside or outsde the rectangle, because there exist two rectangles $ABCD$, $A'B'C'D'$ with the same distances of their respective vertices to the given point: $AX=A'X$, $BX=B'X$, $CX=C'X$, $DX=D'X$, one rectangle containing $X$ and the other one missing it.
Answer: I assume that the four given points are as given as four trees in a landscape forming a nondegenerate rectangle. If your question could not be decided this would mean that we have four different circles intersecting in at least two different points $P$, $Q$. But this would imply that the four circles all have their center on the median $m$ of $P$ and $Q$, contrary to assumption.
Comment: The point is the trees are not given, just distances to them. Imagine you are a bat wih one ear only (no stereo hearing allowing the bearing measurement, just distances). Are you between the trees or outside?


Probability distribution vs. probability function

Question: Is there a difference between the expressions "probability distribution" and "probability function" or are they just synonyms?
Comment: 'Probability function' is a bit vague. What does it mean?
Comment: Well, as I suggest in my question, I suspect that it means the same as "probability distribution". I have found this expression in some material on probability theory, with no further specifications, and I was wondering whether some of you guys knows its exact meaning.
Answer: In my opinion there has been a general pedagogical failing with regard to defining the term "probability distribution". So I like this question every time it is asked. The term "probability distribution" is often used loosely in a way that causes genuine confusion, including for myself.
The term "probability function" is not so common, but I have seen it used as a synonym for "probability measure", which is a totally unambiguous term.
The distribution of a random variable $X$ is the probability measure $\mu$ on $\mathbb R$ defined by $\mu(A) = P(X \in A)$ (for any Borel measurable subset $A$ of $\mathbb R$). This definition of "the distribution of a random variable $X$" is very standard; for example it is used in Folland, and probably every other rigorous textbook that covers probability.
Unfortunately, the PMF of a discrete random variable $X$ is sometimes also called a probability distribution or "the distribution of $X$". Same goes for the PDF of a continuous random variable $X$. This seems to be common in machine learning, for example. If someone asks you, "what's the distribution of $X$?" they expect you to tell them either the PMF or PDF of $X$, whichever one it has (assuming $X$ is either continuous or discrete).
Sometimes the term "distribution of $X$" is used as a synonym for "cumulative distribution function" of $X$ (for example by Sheldon Ross).
Sometimes a probability measure is called a "probability distribution" (by Knuth in Concrete Mathematics, for example).
So I say again, there has been a genuine pedagogical failing with this term.
Answer: "Probability distribution" denotes the law governing some random process. As noted in the comments, "probability function" is vague. Proper terminology would be "probability mass function" (PMF), "probability distribution function" (PDF) or "cumulative distribution function" (CDF).
The numerous misnomers for "probability distribution" may relate to the fact that the distribution of a random variable is characterized by the PMF, PDF, CDF, characteristic function, etc.


Deep, Machine Learning e IA. Qual suas diferenças?

Question: A respeito de Deep Learning, Machine Learning e Artificial Intelligence, quais são suas principais diferenças?

Quais são seus princípios?
São todos que conseguem aprender e resolver problemas de natureza própria?
Como se distingue uma da outra?
Comment: Não entendi exatamente o que você quis dizer com "resolver problemas de natureza própria"
Comment: As técnicas de ML podem resolver problemas sem serem explicitamente programadas para tal. Só não entendi exatamente o que seria identificar problemas.
Comment: @ArthurFerraz quis dizer sobre a máquina identificar problemas e resolver eles sem uma programação totalmente explícita ali.
Comment: @ArthurFerraz máquinas que identificam situações que elas mesmas podem lidar.
Comment: DL é um modelo de ML específico, e ML é feito como uma das técnicas possíveis para se aumentar a função de fitness de um agente inteligente, voltado para obter uma boa IA fraca
Comment: Se está em código é Machine Learning, se está em PowerPoint é Inteligência Artificial :P :D
Answer: A diferença básica entre as áreas citadas está na granularidade. Deep Learning é uma subárea de Machine Learning, que por sua vez é uma subárea Inteligência Artificial.
Ou seja, toda técnica de Deep Learning também é de Machine Learning e, por conseguinte, de Inteligência Artificial. Já nem todo algoritmo de IA é de ML, e nem todo algoritmo de ML é de Deep Learning.
Inteligência Artificial
Definir Inteligência Artificial é bastante complicado pelo fato de que o termo inteligência não é bem definido. Mas resumidamente seria a área que estuda algoritmos que buscam imitar o comportamento inteligente humano. Então qualquer algoritmo que pretenda ser inteligente em algum aspecto, seria considerado de Inteligência Artificial.
Posso citar algoritmos de otimização, como 'Encontrar a melhor rota possível passando por N pontos', como um problema de IA que é resolvido sem utilizar Machine Learning.
Machine Learning
A confusão entre IA e Machine Learning (ML) hoje em dia é bastante comum porque boa parte dos sucessos e avanços de IA estão ligados a técnicas de ML, entretanto essa área é corresponde apenas a uma parte dos algoritmos.
ML é comumente definido como conjunto de algoritmos de IA que são capazes de realizar um procedimento sem serem explicitamente programados para isso.
Podemos citar como técnicas de ML Árvores de Decisão, Redes Bayesianas e até mesmo o famigerado Page Rank (algoritmo de rankeamento do Google). Entretanto, todas essas citadas não são técnicas de Deep Learning (DL).
Deep Learning
Umas das técnicas mais bem sucedidas de ML tem sido as Redes Neurais. Devido ao aumento da capacidade de processamento foi possível construir redes cada vez mais profundas, dando origem ao termo Deep Learning.
Deep Learning então seria a área dentro de Machine Learning que estuda especificamente Redes Neurais profundas.
As técnicas mais populares da DL que posso citar são as Redes Neurais Convolucionais (muito úteis para resolver problemas com imagens) e LSTM (úteis para resolver problemas em que existe dependência de ordem, como geração de texto).

Referência: https://propus.science/diferenciacoes-entre-inteligencia-artificial-machine-learning-e-deep-learning/)
Essa Thread tem uma ótima explicação sobre o tema: Qual é a definição de Aprendizado de Máquina (Machine Learning)?
Qualquer dúvida pode perguntar que enriqueço a resposta.
Comment: Boa a clareza e explicação dos três itens, mas não compreendi relação. Por mais que na explicação, tenha sido esclarecido onde cada uma atua na outra, não torna claro o que difere uma da outra, nem seus princípios.
Comment: Dei uma editada na resposta para ver se fica mais claro. Mas de forma geral o importante é entender que Deep Learning é uma subárea de Machine Learning que, por sua vez, é uma subárea de Inteligência Artificial.


$\lim_{n\to\infty} \left(1+\frac{2}{n}\right)^{n^2} e^{-2n}$

Question:
$$\lim_{n\to\infty} (1+\frac{2}{n})^{n^2} e^{-2n} = ? $$

$e$
$e^2$
$e^{-1}$
$e^{-2}$

My answer is 1. Since $$\lim_{n \to \infty} \left(1+\frac{2}{n}\right)^{n} =e^{+2}.$$
Therefore $$\lim_{n\to\infty} \left(1+\frac{2}{n}\right)^{n^2} =e^{2n}.$$
Where am I wrong?
Comment: I think the latest edit (version 4) misrepresents the OP's intent.  I interpreted the OP as saying the limit is the actual *value* $1$, not *option* !. (The options were originally labeled a), b), c), and d), not 1, 2, 3, and 4.)
Comment: You're overlooking the square in $()^{n^2}$ and the $n$ in $e^{-2n}$
Comment: @DRPR it is meaningless write that $\lim_{n\to\infty} (1+\frac{2}{n})^{n^2} =e^{2n}$ what it is true is that  $(1+\frac{2}{n})^{n^2} \sim e^{2n-2}$.
Answer: The fact that $(1+\frac{2}{n})^n\to e^2$ as $n\to\infty$ does not mean that $(1+\frac{2}{n})^{n^2}$ acts like $e^{2n}$ for large $n$, although it is easy to see why you might think so!
Exponents have huge effects on behavior; they can take even the smallest deltas and make them explode.
So, instead, let's consider logarithms:
$$
\ln\left[\left(1+\frac{2}{n}\right)^{n^2}e^{-2n}\right]=n^2\ln\left(1+\frac{2}{n}\right)-2n.
$$
There are a few ways to go from here.  One way: Taylor series. You can show that $\ln\left(1+\frac{2}{n}\right)=\frac{2}{n}-\frac{2}{n^2}+O(\frac{1}{n^3})$ for $n$ large, which implies that
$$
n^2\ln\left(1+\frac{2}{n}\right)-2n=2n-2-2n+O\left(\frac{1}{n}\right)=-2+O(\frac{1}{n}),
$$
so that the logarithm of your value approaches $-2$.  Thus, the answer should be $e^{-2}$.
If you aren't comfortable with Taylor series, you could also rewrite this as
$$
\frac{\ln\left(1+\frac{2}{n}\right)-\frac{2}{n}}{\frac{1}{n^2}}
$$
which is a $\frac{0}{0}$ indeterminate form, and use L'Hopital's rule.
Comment: (+1) for a very nice explanation that is far more enlightening than just putting up some standard computations.
Comment: Thank you . got it
Comment: Nice approach. (+1)
Answer: Note that
$$\left(1+\frac{2}{n}\right)^{n^2}=e^{n^2\log (1+\frac{2}{n} )}=e^{n^2\left(\frac{2}{n}-\frac{2}{n^2}+o(1/n^2)\right)}=e^{2n-2+o(1)}$$
then
$$\left(1+\frac{2}{n}\right)^{n^2} e^{-2n}=e^{-2+o(1)}\to e^{-2}$$
Comment: Beautifully explained. (+1) for this solution. It helped me too.
Comment: downvoting a correct and very clear answer is very regrettable behaviour
Comment: @thevbm Thanks so much for your kind appreciation! Bye


Como enviar dados para web service usando AFNetworking?

Question: Eu tenho um formulario que deve ser preenchido no aplicativo e enviado ao web service para cadastrar um novo usuário.
Como poderia enviar estes dados para o web service usando AFNetworking 2.0?
Tentei usar o código abaixo, mas retornou um erro:
NSDictionary *params =      @{@"id" : idCadastro.text,
                             @"nome" : nomeCadastro.text,
                             @"email" : emailCadastro.text,
                             @"cidade" : localidadeCadastro.text,
                             @"passe" : senhaCadastro.text
                                                         };
    NSString* HOST_URL = @"http://10.1.1.6/advphp/cad_adv_0.php?";

    AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
    [operationManager POST: HOST_URL parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){

        // Enter what happens here if successsful.
        NSLog(@"Cadastrado");

    }failure:^(AFHTTPRequestOperation *operation, NSError *error){

        // Enter what happens here if failure happens

        NSLog(@"Não Cadastrado. Erro:\n%@",error);
    }
     ];

E abaixo a mensagem de erro que aparece:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be
  completed. (Cocoa error 3840.)" (JSON text did not start with array or
  object and option to allow fragments not set.) UserInfo=0x7969de10
  {NSDebugDescription=JSON text did not start with array or object and
  option to allow fragments not set.}
Answer: ok consegui fazer isso sem usar o parameters ou ter que converter o conteúdo para JSON.
Fiz o seguinte, criei uma URL completa, e passei para URLString: diretamente!
NSMutableString* urlStrin = [[NSMutableString alloc]initWithFormat:@"http://10.1.1.6/advphp/cadastrar.php?id=%@&nome=%@&email=...%@",idCadastro.text, nomeCadastro.text, emailCadastro.text, localidadeCadastro.text, senhaCadastro.text];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager GET:urlStrin parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
// do whatever you'd like here; for example, if you want to convert
// it to a string and log it, you might do something like:

NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"%@", string);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];

Answer: O erro indica que o json enviado pelo servidor contém fragmentos, que não são suportados pelo parser por default. Para solucionar o problema, inclua este código após a inicialização da instância de AFHTTPRequestOperationManager:
AFJSONResponseSerializer *serializer = [AFJSONResponseSerializer serializer];
[serializer setReadingOptions:NSJSONReadingAllowFragments];
[operationManager setResponseSerializer:serializer];

Comment: Bom Rafael recebi o seguinte erro:

`Error Domain=NSCo coaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7babefa0 {NSDebugDescription=Invalid value around character 0.}`
Comment: Acredito que possa ser o servidor, pois no arquivo PHP chamado, eu estou usando $var = $_GET("id")... para receber os dados. Será que pode ser isso?
Comment: Engraçado, o app da esse erro mas cadastra os dados corretamente no banco! Mas preciso resolver este problema, pois preciso do recurso de SUCCESS ou FAILURE para chamar a próxima tela ou voltar para a anterior :/


Aplicar propriedades a um elemento somente se pertencer a uma classe

Question: Quero aplicar css a esses elementos
ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #555;
    color: white;
}

li {
    display: inline;
}

Mas, somente se pertencerem a uma classe x, como poderia fazer isto?
Answer: Sim é possível de duas formas.
Uma caso vc quera colocar os elementos dentro de uma div pai por exemplo, ai a div que tera a .classex e tudo dentro dela poderá ser customizado com seu css

.classex ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

.classex li a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

.classex li a:hover {
    background-color: #555;
    color: white;
}

.classex li {
    display: inline;
}

classe x

A outra forma é colocar a .classex no próprio elemento, dessa forma

ul.classex {
    list-style-type: none;
    margin: 0;
    padding: 0;
    width: 200px;
    background-color: #f1f1f1;
}

li.classex a {
    display: block;
    color: #000;
    padding: 8px 16px;
    text-decoration: none;
}

li.classex a:hover {
    background-color: #555;
    color: white;
}

li.classex {
    display: inline;
}

classe x

Answer: Informe o elemento juntamente com a classe que tu quer que ele pertença.
Exemplo:

li.teste {
color: blue;
}

a.teste {
color: red;
}

Teste

Teste

Teste

Teste

Caso eu tenha entendido errado sua pergunta, me fala que eu altero minha resposta.


How to deal with multiple entities using NSFetchedResultsController in swift

Question: I have 3 similar tables that I would like to store in core data. I would like to view and edit the tables from a common view controller using NSFetchedResultsController. How can I generalize the setup or use sub-classing to achieve this? Foe example in my code show below

Recommendation

is one of the entities. I have another entity named

Results

which I would like to use (by changing the cell description in the table) and making the appropriate other changes.For example how can I represent Recommendation with a variable.
var moc:NSManagedObjectContext!
var fetchedResultsController: NSFetchedResultsController<Recommendation>!
var recommendations: [Recommendation] = []

and a method:
    func setupFetchedResultsController() {
    let dataRequest:NSFetchRequest<Recommendation> = Recommendation.fetchRequest()
    let sortDescriptor = NSSortDescriptor(key:"recordNumber", ascending: true)
    dataRequest.sortDescriptors = [sortDescriptor]

    fetchedResultsController = NSFetchedResultsController(fetchRequest: dataRequest, managedObjectContext: moc, sectionNameKeyPath: #keyPath(Recommendation.recordNumber), cacheName: nil)
    fetchedResultsController.delegate = self
    do {
        try fetchedResultsController.performFetch()
    } catch {
        print(error.localizedDescription)
    }
}

Answer: You could create a base table view controller with properties to be overridden. I recommend to initialize the fetch controller lazily like suggested in the Core Data template.
class BaseTableViewController: UITableViewController {

    var managedObjectContext : NSManagedObjectContext!

    // MARK: - Variables to be overridden

    var entity : String { fatalError("entity must be overridden") }
    var sortDescriptors : [NSSortDescriptor]? { return nil }
    var cacheName : String? { return nil }
    var sectionNameKeyPath : String? { return nil }
    var fetchPredicate : NSPredicate? {
        didSet {
            fetchedResultsController.fetchRequest.predicate = fetchPredicate
        }
    }

   ...

    lazy var fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult> = {

        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: self.entity)
        fetchRequest.predicate = self.fetchPredicate

        fetchRequest.sortDescriptors = self.sortDescriptors
        let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest,
                                                               managedObjectContext: self.managedObjectContext!,
                                                               sectionNameKeyPath: self.sectionNameKeyPath,
                                                               cacheName: self.cacheName)
        aFetchedResultsController.delegate = self

        do {
            try aFetchedResultsController.performFetch()
        } catch let error as NSError {
            self.present(error:error)
        }

        return aFetchedResultsController
    }()

   ...

}

Now you can subclass the controller
class RecommendationViewController: BaseTableViewController {

  // MARK: - Variables to overide

  override var entity : String { return "Recommendation" }
  override var sectionNameKeyPath : String? { return #keyPath(Recommendation.recordNumber) }
  override var sortDescriptors : [NSSortDescriptor]? { return [NSSortDescriptor(key:"recordNumber", ascending: true)] }

Comment: Thank you for a great answer. I need to fill the cell from the subclass so I created a function in the base class which I override. In the base class in cellForRowAt I have code as:

let dataObject = fetchedResultsController.object(at: indexPath);
        fillCell(cell: cell1, dataObject: dataObject);

When I override fillCell, what do I need to do cast dataObject to the entity so I can access the attributes? I need to mimic:
cell1.categorylabel.text = dataObject.category
Comment: I did figure it out. I cast it to my entity as
let d = dataObject as! Recommendation
Then d exposes all the attributes.

Thank you for your help.


Spring: como o Jackson pode formatar uma resposta Json composta em objetos

Question: Bom, estou fazendo um projeto Spring juntamente com Spring-cloud-openFeign para integração com uma api da Fipe para acessar valores de carros. Veja a classe:
@Service
@FeignClient(name = "FipeService", url = "https://parallelum.com.br/fipe/api/v1")
public interface FipeService {

    @GetMapping("/{type}/marcas")
    public List<FipeResponse> getBrands(@PathVariable String type);

    @GetMapping("/{type}/marcas/{brandCode}/modelos")
    public List<FipeResponse> getModels(@PathVariable String type, @PathVariable String brandCode);

    @GetMapping("/{type}/marcas/{brandCode}/modelos/{modelCode}/anos")
    public List<FipeResponse> getYears(@PathVariable String type, @PathVariable String brandCode, @PathVariable String modelCode);

    @GetMapping("/{type}/marcas/{brandCode}/modelos/{modelCode}/anos/{year}")
    public FipeResponse getPrice(@PathVariable String type, @PathVariable String brandCode, @PathVariable String modelCode, @PathVariable String year);
}

O FipeResponse é uma classe minha usada para o Jackson inserir o retorno da api nela, o que ele faz no método getBrands() pois a resposta Json é simples, um array somente com nome e código. Veja a classe:
public class FipeResponse {

private String nome;
private String codigo;
private String valor;

public FipeResponse(String nome, String codigo, String valor) {
    this.nome = nome;
    this.codigo = codigo;
    this.valor = valor;
}

public FipeResponse(){

}

getters e setters

}
Porém, no segundo endpoint tenho um problema, o getModels retorna um array com modelos e anos (teste o link: https://parallelum.com.br/fipe/api/v1/carros/marcas/59/modelos) e o Jackson não consegue inserir no FipeResponse obviamente, mas, já tentei dentro do FipeResponse adicionar outras duas classes como composição, uma para modelos e outra para anos, ambos com nome e codigo de atributos somente, e inseri no FipeResponse assim:
public class FipeResponse {

private String nome;
private String codigo;
private String valor;
private List<FipeAnos> anos;
private List<FipeModelos> modelos;

public FipeResponse(String nome, String codigo, String valor, List<FipeAnos> anos, List<FipeModelos> modelos) {
    this.nome = nome;
    this.codigo = codigo;
    this.valor = valor;
    this.anos = anos;
    this.modelos = modelos;
}

public FipeResponse(){

}

getters e setters

}
E mesmo assim o Jackson continua não conseguindo inserir os dados usando o endpoint getModels(), mas funciona normalmente usando getBrands(), consigo acessar os atributos e tudo. O que fiz de errado?
Comment: Não entendi o downvote na pergunta... Se for necessário maiores detalhes é só perguntar, agora dar -1 e não falar nada não resolve em absolutamente nada.
Answer: GetBrands : A requisição a esse endpoint retorna de fato uma lista:
[
  {
    "nome": "Acura",
    "codigo": "1"
  },
  {
    "nome": "Agrale",
    "codigo": "2"
  }...
]

o endpoint getModels retorna um objeto, e esse objeto contém uma lista de modelos :
{
  "modelos": [
    {
      "nome": "AMAROK CD2.0 16V/S CD2.0 16V TDI 4x2 Die",
      "codigo": 5585
    },
    {
      "nome": "AMAROK CD2.0 16V/S CD2.0 16V TDI 4x4 Die",
      "codigo": 5586
    },
    ....
}

Para obter a resposta desse endpoint você deve modelar um objeto que represente esse json, como por exemplo:
public class FipeModelo {
   public String modelo;
   public Integer codigo;
}

Public class FipeModelos {
   public List<FipeModelo> modelos;
}

presta atenção que o FipeModelos recebe uma Lista de FipeModelo e a variável se chama modelos, conforme a resposta que vem no endpoint que você passou.
E na classe de serviço do feign ficaria:
@GetMapping("/{type}/marcas/{brandCode}/modelos")
public FipeModelos getModels(@PathVariable String type, @PathVariable String brandCode);


Alinhar listas de tamanhos diferentes na div em Bootstrap

Question: Tenho algumas listas que são alimentados através de uma consulta ao banco de dados, ou seja, a quantidade que irá mostrar é incerta, porém eu limito mostrar até 5 registros por categoria.
Como está:

Uma lista está ocupando o "espaço" da outra e entao quero quebrar em "rows", basicamente assim:

Meu código:

Categoria

Lorem Ipsum

            Ver Todos

Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

            Ver Todos

Categoria

Lorem Ipsum

            Ver Todos

Categoria

Lorem Ipsum

Lorem Ipsum

            Ver Todos

Categoria

Lorem Ipsum

            Ver Todos

Como posso fazer isso?
Answer: Vc pode tratar o .row que as listas estão dentro com display:flex e flex-wrap assim vc evita que as listas fiquem "encavaladas" e joga o conteúdo que não couber para a "linha" de baixo
Para entender melhor como fica veja o snippet abaixo (exiba também em "Página toda" para ver o resultado)

.listas {
    display: flex;
    flex-wrap: wrap
}
<link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

Categoria

Lorem Ipsum

                            Ver Todos

Categoria

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

                            Ver Todos

Categoria

Lorem Ipsum

                            Ver Todos

Categoria

Lorem Ipsum

Lorem Ipsum

                            Ver Todos

Categoria

Lorem Ipsum

                            Ver Todos

Comment: @Piupz Tranquilo jovem estamos aqui pra isso! E se quiser as 5 listas na mesma fileira basta tirar o flex-wrap: wrap
Comment: @LucasCoelho valeu jovem! Pode fazer dessa maneira sim, mas ai TODAS as .row vão ficar como essa classe, e pode atrapalhar o seu grid em outro lugar, pois isso preferi criar uma classe só com essas propriedades, ai vc pode usar apenas na .row que quiser! Lembrando que aqui o Boostrap é v3 não tem as classes de flexbox da v4
Comment: Funcionou, acabei esquecendo dessa possibilidade, obrigado!
Comment: Obrigado! Otima solução. Pode ser configurado também diretamente na classe row no arquivo de estilização onde foi implementada.


How do I write this PHP query the Drupal way (database abstraction)?

Question: I am using the code below to evaluate if a panel pane should display. I've read the docs on database abstraction, but I just don't really understand how to apply it. Of course, the dpm values are for debugging.
(Just to be clear, this code is currently functioning exactly how I need it to, and I am not having any problems with panels itself. I just don't understand how to sanitize this the Drupal way to avoid injection.)
Any help would be appreciated. Here's the code:
// Gets NID of viewed node as well as the parent (passed by entity reference field)
$nid = $contexts['argument_entity_id:node_1']->data->nid;
$parent = $contexts['argument_entity_id:node_1']->data->field_webisode_series_reference['und'][0]['target_id'];

// Returns the 3 newest nodes with same parent as the view node
$recentNIDs = db_query("
    SELECT entity_id
    FROM field_data_field_webisode_series_reference
    WHERE field_webisode_series_reference_target_id = $parent
    ORDER BY entity_id
    DESC LIMIT 3
    ");
$result = $recentNIDs->fetchAll();

// Checks NID of the viewed node against NIDs of the 3 nodes above.
// If true, and NIDs match, then the block is displayed.
foreach ($result as $k => $v) {
    $nid2 = $v->entity_id;

    if ($nid2 == $nid) {
        $top3 = 1;
    }
}

// If $top3 is set, display. Else, do not.
if (isset($top3)) {
    dpm('TRUE', 'top 3?')
}

elseif (!isset($top3) {
    dpm('FALSE', 'top 3?')
}

Comment: You might want to check out [EntityFieldQuery](https://www.drupal.org/node/1343708). As far as displaying the panel I am not sure because I use blocks, maybe [this](https://groups.drupal.org/node/37104) may help.
Comment: I'll take a look at EntityFieldQuery. Actually displaying it is not a problem. There's a "visibility" option within each panel where PHP code can be used to evaluate whether or not it will display. I'm just plugging this code into that spot.
Answer: I think that you can review this answer:

If you use db_query() all the time without directly inserting
  variables, but using the arguments.

I hope information be useful.
Comment: That answer explained why to do it, but not as much on how to do it. That being said, it did help me out on my way to figuring it out, so I'll mark this as the answer. That being said, a comment in that answer said to consider using db_escape_table (https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_escape_table/7). Do you know why/when this should be done, or how I would implement it?


How do I finger these descending treble fifths?

Question: From BWV 914, Toccata in E minor, Fuga:
My Henle edition marks 5-1 for the first four pairs of fifths starting from F#, E, D, C#, but doesn't give fingerings for the next 6 pairs of fifths.
What would you recommend? I'm inexperienced and wonder if using 5 for the top note in each fifth is really efficient. Thanks in advance! I included screenshots of two public domain versions:
(Version 1: bars 4 & 5):

(Version 2: equivalently, bars 2 & 3):
Answer: I can't find the passage in question, but in general, I play parallel 5ths moving up or down a scale by alternating between 5-2 and 4-1.  If you can't reach that stretch, then playing 5-1 and 4-1 is another option (in this case, keep the top line legato, and it will be okay if the bottom line is disconnected a little bit).
Either way, it's a little tricky because you need to be able to make that 5-4 crossover smoothly. If you're having trouble, you can practice that by playing scales using only those two fingers.
EDIT
As it turns out, I was assuming that the 5ths were chords; I wasn't expecting them to be broken.  In this case, playing 1-5 and walking your hand down the keyboard would be possible, but I would consider playing 5-2 when the lower note is on a black key.  In this case, a rigid alternation between 5-2 and 4-1 would be fairly awkward.
I did neglect to add this disclaimer: since I have no idea how large your hands are, I'm assuming that they're about an average size for a guy who's about 5 feet 6 inches tall (coincidentally, that's how large my hands are).  If your hands are smaller, you'll probably favor using 5-1 for all the intervals, and if they're larger, you'll feel more comfortable using 5-2.  In the end, it's all about what feels best for you; these are just suggestions to try.  In this situation, the fingering isn't all that critical, so feel free to experiment!
Answer: I play those with 5 on most of the upper notes, and a 4 here and there on a black key... thumb on the lower note except when it's a black key then usually 2. Practice them blocked (i.e., as an interval sounded together) then open to play as written.


How to specify address location in axis2-java2wsdl-maven-plugin?

Question: I use to generate wsdl from java calss axis2-java2wsdl-maven-plugin. Below I cited a passage pom.xml:
<plugin>
                <groupId>org.apache.axis2</groupId>
                <artifactId>axis2-java2wsdl-maven-plugin</artifactId>
                <version>1.6.2</version>
                <configuration>
                    <className>Path_to_ws_class</className>
                <outputFileName>src/main/webapp/webservice.wsdl</outputFileName>
        <schemaTargetNamespace>http://test.test/xsd</schemaTargetNamespace>
                    <wsdlVersion>${project.version}</wsdlVersion>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>java2wsdl</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

But it generates in the bottom of wsdl file:
<wsdl:port name="WebServiceHttpSoap11Endpoint" binding="axis2:WebServiceSoap11Binding">
<soap:address location="http://localhost:8080/axis2/services/MerchantWebService"/>
</wsdl:port>

I don't need following part, because my web service is not available by this link:
<soap:address location="http://localhost:8080/axis2/services/MerchantWebService"/>

Is it possible to specify location as parameter in plugin configuration?
locationUri doesn't work :(
Answer: Add
<locationUri>http://localhost:8080/AppRootContext/services/MerchantWebService</locationUri>

to your
<configuration>


Integrate this abstract integral

Question: I want to integrate(in this case: find an antiderivatie) $\int f(\sqrt{c^2+x^2})x\, dx$, where $f \in C$ and $F'=f$ for some $F' \in C^1$ and $c \in \mathbb{R}$.
It seems to me as if I'm missing the trick for this integral. Does anybody here have an idea?
Answer: If you know a primitive (an antiderivative) $G$ of $F$, it is relatively easy by substituting $u = \sqrt{c^2+x^2}$. Then
$$\begin{align}
\int f(\sqrt{c^2+x^2})x\,dx &= \int\sqrt{c^2+x^2}\cdot f(\sqrt{c^2+x^2}) \frac{x}{\sqrt{c^2+x^2}}\,dx\\
&= \int u\cdot f(u)\,du\\
&= u\cdot F(u) - \int F(u)\,du\\
&= u\cdot F(u) - G(u)\\
&= \sqrt{c^2+x^2}\cdot F(\sqrt{c^2+x^2}) - G(\sqrt{c^2+x^2}).
\end{align}$$
Comment: Any two primitives of the integrand differ by a constant. So in general, it is not possible to express the result without $G$, unless $\int F(u)\,du$ counts, as far as I can see. If $F$ has a particular form, it can be possible of course.
Comment: Mhmm, actually the excercise was supposed to be solved by only referring to this $F$. You think it is impossible to give an antiderivative that does not use this $G$?
Comment: Take $f(x) = 2xe^{x^2}$. Then $F(x) = e^{x^2}$ but this function in turn has no [normal] primitive and $G(u)$ and the final expression will not be expressible in terms of analytic functions. You need some extra conditions at least.
Comment: I'll see whether I can offer some extra conditions on F...thanks to you all of you.
Answer: Let  $F(x)$  is   the antiderivative   for $f(\sqrt{x}).$  Change  the  variable $t=x^2+c^2,  dt=2 x dx.$ Then
$$
\int f(\sqrt{x^2+c^2})x dx=\int f(\sqrt{t})  \frac 12 dt= \frac 12 F(t)= \frac{1}{2}F(\sqrt{x^2+c^2})+C.
$$

Integrate this abstract integral


Restrict edge set to certain nodes only

Question: Given a graph $G=(V,E \subseteq V \times V)$, an edge set $D \subseteq E$ and a subset of nodes $W \subseteq V$, is there such thing as an established operator for the "restricted" set of $D$:
$$
\{ (u,v) | u \in W \vee v \in W\} \subseteq D
$$
I did not find anything at wikipedia, but that does not necessarily mean something.
In case there is no such established operator, is $D | W$ acceptable/readable (i.e. has it some other obvious meaning in graph theory that I am not aware of?)
Comment: $D|W$ is sometimes used as shorthand for $W$ having a decomposition into subgraphs isomorphic to $D$; akin to "$D$ divides $W$".
Answer: I'm not aware of any established notation for this, however, the notion of incidence is usually understood in a more general sense, that is, not only with regard to vertices/edges, but whole sets. Therefore, you could say that
$$\{(u,v) \in E \mid u∈W \lor v∈W\} \text{ is the subset of edges incident to }W.$$
Also, there is another similar notion, namely, the induced subgraph, i.e.
$$\{(u,v) \in E\mid u∈W \land v∈W\} \text{ is the set of edges induced by }W.$$
Given the two above, you can add that you intersect it with $D$. With some stretch, you can use function restriction notation $f|_\Omega$ (I have seen it used for induced subgraphs), but in any case, I would simply define the necessary operators, just to be clear (notation in graph theory varies a lot).
I hope this helps $\ddot\smile$

Restrict edge set to certain nodes only


How to stop an "setInterval" from HTML

Question: This Code shows an growing up Intervaltimer. I'm using setInterval for it,  but i don't know how to stop ist.
There is a funktion called ende(). Can i stop the Intervaltimer with this funktion?
The Reason to stop it is that when i hit the button(at the bottom) again then a second Timer starts. I don't know how to say it, test it out.

```
<!DOCTYPE html>

  <title>Interval Timer</title>

WORK

00:00:45

REST

00:00:15

Pause

00:00:25

   <button class="button1" type="button" id="work">Work</button>
   <button class="button1" type="button" id="rest">Rest</button>
   <button class="button1" type="button" id="pause">Pause</button>

        Interval Timer

WORK

00:00:45

REST

00:00:15

Pause

00:00:25

        <button class="button1" type="button" id="work">Work</button>
        <button class="button1" type="button" id="rest">Rest</button>
        <button class="button1" type="button" id="pause">Pause</button>

Comment: Welcome to SO. Two suggestions before asking. 1) Read the setInterval documentation which will introduce you to `clearInterval` and 2) Try searching terms like "stop setInterval" . See [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users)
Answer: Store the interval in a variable, then use that variable to stop the interval. However, since you are starting the interval inside a function and stopping it inside another function, you need to use a global variable. First declare a global variable x:
var x;

Then, replace:
setInterval(...

by:
x = setInterval(...

To stop the interval, just call
clearInterval(x);

Comment: Poor practice declaring global variables this way. Also it does not necessarily need to be a *global*...so long as it is in scope where needed
Comment: @charlietfl why poor way?
Comment: At least use `var` or `let`
Comment: I already stated it in the post: declare a global variable x.
Comment: OK... suggest showing the declaration then  since OP is clearly a beginner
Comment: Sure. Will edit accordingly.

How to stop an "setInterval" from HTML


Cutting a can from a metal sheet to maximize volume

Question: Question:
Consider the following square sheet of metal (grey) with the side s = 10 cm. From it, we want to cut the parts of a cylindrical can with a lid and a bottom (bblack). Determine the radius and height of the can when the volume is maximal.

The rectangle and circles have to be cut in entire, singular pieces, so no trickery to minimize waste and no diagonal placement of the rectangle.
Solution has to use optimization / differentiation.
Attempted solution:
In order for this to work out the circumference of the circles and one side of the rectangle has to be identical. Otherwise they will not fit together in a cylindrical can.
This leads us to two cases that needs to be treated separately.
Case 1: The rectangle is standing upright.
Case 2: The rectangle is lying on its longest side.
There are two cases that needs to be considered separately.
Case 1:
The right-hand side of the above image must be the circumference of a circle, so
$$s_1 = 2r\pi$$
The bottom-side must be the height of the cylinder plus two radii of the circles:
$$s_1 = h + 2r$$
Putting these together becomes:
$$2r\pi = h + 2r = 10$$
Solving for h:
$$h = 10 - 2r$$
The volume of the can:
$$V = r^2\pi h$$
Adding in the earlier formula to get rid of h:
$$V = r^2\pi h = r^2\pi (10 - 2r) = 10r^2\pi - 2r^3\pi$$
Taking the derivative:
$$V' = 20\pi r - 6\pi r^2$$
Setting derivative equal to zero:
$$V' = 0 \Rightarrow r = \frac{10}{3}$$
(neglecting trivial r = 0 solution)
Height is then:
$$h = 10 - 2r = 10 - \frac{20}{3} = \frac{10}{3}$$
But this is not really possible given the side of the metal sheet cannot be more than 10 cm and $$2r\pi > 10$$.
Case 2:
The bottom becomes:
$$2r + 2r\pi = 10 \Rightarrow r= \frac{5}{1+\pi}$$
The right side becomes:
$$h = 10$$
However, none of these answers match the solution:
$$r = \frac{5}{\pi}$$
$$h = 10(1-\frac{1}{\pi})$$
Did I get the starting point for the possible cases right? Where did I go wrong? How come it appears that no calculus is needed in the second step?
Comment: No need to consider the "two cases" (The rectangle is standing upright vs  lying on its longest side) because the sheet is square.
Comment: @leonbloy are there are more than one potential case to consider?
Comment: @leonbloy: mathinferno is distinguishing the two cases where the vertical edge of the black rectangle is the height of the cylinder or its corcumference.
Answer: Yes, there are two cases. In your case 1 the side of the square equals the circumference of the lid; in case 2 the side of the square equals the height of the can.
In case 2 the volume of the can is a function of $r^2$ alone, so volume is maximized when $r$ is as large as possible. This is the reason why no calculus is required. The value of $r$ in this case is constrained by $2r + 2\pi r\le 10$, as you've shown.
The other answers have addressed case 1. It remains to check that the max volume under case 2 is less than the max volume under case 1.
Answer: Since the rectangle must be cut parallel to the sides of the square, the circumference of the circle is limited to the side of the square. So $2\pi r \leq 10$ or $r \leq 5/\pi$.
At this limit, the height is $h = 10 - 10/\pi.$
The volume $V=\pi r^2h$. Since any increase in height equals any decrease in radius, the limiting values provide the maximum volume because the volume is quadratic in the radius, but only linear in the height.
Comment: It is a nice, clean solution. Thanks! For clarification, I have added that the question should be solved with differentiation / optimization.
Answer: Calling $b, s$ the metal sheet dimensions, $r$ the tip radius and assuming an arrangement as depicted in the OP figure we have
$$
V = \pi r^2 s
$$
with the associated lagrangian
$$
L(r,\lambda,\epsilon) = V + \lambda_1(4r-s+\epsilon_1^2)+\lambda_2(2r+2\pi r -b+\epsilon_2^2)
$$
Here $\epsilon_i$ are slack variables to transform the inequalities into equations.
Now solving for the stationary points we have
$$
\nabla L = 0 = \left\{
\begin{array}{rcl}
 2 \pi  r s+4 \lambda _1+2(1+\pi ) \lambda _2&=&0 \\
 \epsilon_1^2+4 r-s&=&0 \\
 \epsilon_2^2-b+2 \pi  r+2 r&=&0 \\
  \epsilon_1 \lambda _1&=&0 \\
  \epsilon_2 \lambda _2&=&0 \\
\end{array}
\right.
$$
and after solving we get
$$
\left[
\begin{array}{c}
 V&r&\lambda_1&\lambda_2&\epsilon_1^2&\epsilon_2^2 \\
\frac{b^2 \pi  s}{4 (1+\pi )^2}&\frac{b}{2(1+ \pi) }&0&-\frac{b \pi  s}{2 (1+\pi )^2}&s-\frac{2 b}{1+\pi}&0 \\
\frac{\pi  s^3}{16}&\frac{s}{4}&-\frac{\pi  s^2}{8}&0&0&b-\frac{1}{2} (1+\pi ) s \\
\end{array}
\right]
$$
NOTE
$\epsilon_i = 0$ means that the $i-$constraint is verified at the boundary


Why can't sed find line in changelog

Question: I am experimenting with bash scripting and wanted to write a function that can add a new changelog item when you run a certain command.
Give a changelog, the user runs .changelog.sh and a new changelog item is appended to the changelog after the line ## [Unreleased]. Below is my code.
new_changelog_item()
{
    while read line; do
    if [[ $line == "## [Unreleased]"* ]]; then
        echo $line
        echo "LINE FOUND IN" CHANGELOG.md
        sed -i "" "s/$line/## [Unreleased]\n## [$version] - $(date '+%Y-%m-%d')\n### Added\n - ADD CHANGE HERE!\n/g" CHANGELOG.md
        return
    fi

    done < CHANGELOG.md
}

The odd thing is, when I add a line below, let's say  and look for that line instead of ## [Unreleased] the above code works accordingly IF there is a new line after the TESTING line. If I leave a new line after ## [Unreleased] it still does not work.
I'm assuming my code can't find it because of the []. If I remove those and add a new line it works. Is there a way around this where I can make it find the string even if it contains []? This would be ideal as I am following the Keep a Changelog format.
Comment: Don't modify a file while you're reading from it.
Comment: Actually, this doesn't modify the file you're reading from. `sed -i` creates a new file and renames it to the original filename.
Comment: @Barmar is it better to create a new file from scratch them delete the original one?
Answer: I was actually able to find some help here.
The sed replace wasn't working properly because the line was being evaluated as a bracket expression rather than as part of the string. To get around this, I ended up creating this variable before the replacement:
newvar=$(<<<"$line" sed 's/[].*[]/\\&/g')

Then instead of using $line in the sed statement I used $newvar. The code works correctly now.

Why can't sed find line in changelog


Save console and HAR (network) logs in a local drive

Question: I work as a technical support and we heavily rely with console and HAR (network) logs to resolve issues. There are some issue that cannot be replicated and we need to record it before it happened but there is no way to now when it will happen. Keeping chrome devtool running for a day is not advisable for it will create a huge file and there is a tendency that it will crash.
Provide me some idea on how I'm going to do this:

Gather console log and HAR (network) log continously until the user stop it.
Save the files locally by setting a file limit (e.g. 10 MB)
This could be distributed to multiple clients to be run on their local machine.

I want to make this from catch, all I ask is an idea and where should I start. Based on my research, I could use python with playwright or selenium.
If you can direct me to a site where I can do research, please do so. Not asking for any code. Just want to know how can I make this possible.
Thanks in advance.
I used chat GPT but it always give me an error whenever I try to run the code.
Answer: *** Disclaimer: Posted by HttpWatch Developer ***
If you're running on Windows you could used our HttpWatch product to record logs files and split them based on a time interval. The files can be saved in HAR or the proprietary HWL format.
You can also automate HttpWatch using Python if you want to control the recording of log files while driving the browser with a framework like Selenium.
Here's some more information about these features:
https://help.httpwatch.com/automatic_recording.html
https://www.httpwatch.com/features/automatedtesting.aspx
https://apihelp.httpwatch.com/