customising variables in Bootstrap 4 with SASS in .NET core

Question: I'm used to working on .NET MVC. I'm trying to learn .NET Core now and want to include Bootstrap with SASS. I'm completely new to the setup side of things and can't get it properly up and running.
I have set up my .NET core project and I've managed to install bootstrap 4 with libman. After I'd done it, I read that it's preferred to do it with npm but it seems to be fine.
All the defaults work as expected.
Now I'm trying to make custom changes and that's where it gets troublesome. Just to see if changes are applied, I've changed the primary colour code in the _variables file but nothing changes. I've also tried to create a custom scss file to override the others but again, it doesn't work. I'm sure it's me doing something wrong but I'm not sure what.
my file structure looks like this. It was created when I installed bootstrap 4:
file structure top
file structure bottom
the only thing I changed was adding the site.scss file for customisation.
_Layout.cshtml
<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">
    </environment>
</head>
</code>
My custom site.scss:
<code>$orange: #d95700;
@import "bootstrap";
$theme-colors: ( "primary": $orange );
</code>
When I make changes to the bootstrap.css they either show up or they get overridden by the _reboot.scss, depending on what it is. e.g. I can change the body bg color to red.
If anyone needs me to add any more information, I'm happy to do that.
Answer: Libman merely pulls in the libraries statically. Changing any of the SCSS files isn't going to cause the CSS file you're referencing to be updated. For that to happen, you'll need to set up a build of the SCSS with something like Webpack or Gulp.
However, if you want to actually modify the SCSS, then you should not rely on libman or even npm to pull in Bootstrap for you. Both of these will update the library in place, overriding any of your changes. Instead, you should simply download Bootstrap directly or you can include it in your project in a more updatable way by forking the Bootstrap project on GitHub and then including that in your repo as a remote. Then, you can commit changes out to your fork, and merge updates from the Bootstrap official repo into your fork.


Simple example of functional equation in Banach Algebra and how to solve it

Question: In my readings through Banach Algebra I noticed something. For real functions for example we know that the functional equation
$$
f(x+y)=f(x)f(y)
$$
Has as solution $f(x) = e^x$.
Now since bounded operators in $L^p(\mu)$ form a Banach Algebra as well I observed that a similar relationship holds for the translation operator. If $(T_yf)(x) = f(x -y)$ we have the relationship
$$
T_{x+y} = T_x T_y
$$
Which resembles pretty much the first functional equation I saw. From a random reading yesterday about quantum mechanics I saw that the translation operator can be expressed as something like an exponential as well. I wonder if therefore there's some techniques for solving functional equations in Banach Algebra that would allow to represent operators using functional equations.
Answer: What you are looking for is the called "One-parameter Semigroup" in mathematics. For example, Peter Lax's Functional analysis text, Chapter 34 showed that if $T_0=Id$ and $\forall x,y\ge0, T_xT_y = T_{x+y}$ and $T$ is continuous at $0$ (that is $\lim_{x\rightarrow 0} T_x = Id$), then $T$ must be of the form $T_t = e^{tG}$ where $G$ is known as the infinitesimal generator of the one-parameter semi-group. The proof is essentially to write $G$ as log of $T_t$, and it's not hard to show the power series for the usual log converges around $1$, because $T_t$ will be close to $Id$, hence its norm is not far from $1$.
Answer: About the exponential operator, it is well known in quantum mechanics, but I have us it in the past for a numerical method to solve the propagation of laser beams, named "Split-Step Fourier Method".
I left the wikipedia links hoping they will help you to understand how this operator can be used and its equations solved (since its a numerical method, I believe could be an example for a Banach Space):
Shift Operator, Split-Step Method, Baker-Campbell-Hausdorff formula
Comment: I think what I'd like to know is whether the exponential operator can be defined as solution of the functional equation I gave (the one involving the translation operator).
Comment: On the last links, on the special cases [[3](https://en.wikipedia.org/wiki/Baker%E2%80%93Campbell%E2%80%93Hausdorff_formula#Special_cases)], it is explained that for two operators to be equal to $e^X \cdot e^Y = e^{X+Y}$ is required that $X$ and $Y$ commute: $[X,Y]=0$, so, since the functional equation is defined for the translation operator, who can be represented as an exponential operator as is shown in [[1](https://en.wikipedia.org/wiki/Shift_operator#Definition)], to happen the right side the exponential operator "exponents" have to commute in a Banach Lie Group, as example.
Comment: I think the problem is that in [1] the assumption made is that you can perform a taylor expansion of the function. Which is not the assumption I am making since I am assuming $L^p$. Moreover I was wondering if specifically there's a technique to "solve" somewhat $T_{x+y} = T_x T_y$ to end up with $e^{-y \frac{d}{dx}}$.
Comment: I am afraid we are seeing the problem from a different angle: lets start from the right side, $T_x T_y = \log(e^{T_x}e^{T_y})=T_x + T_y + \frac{1}{2}[T_x,T_y]+\frac{1}{12}([T_x,[T_x,T_y]]+[T_y,[T_y,T_x]])+\cdots$ the monstrosity derived by the Baker-Campbell-Hausdorff Formula. By the other side, for the left part, I will make the following assumption $T_x(T_y) = T_{x+y} = T_x + T_y$, i.e., $T_u$ is a linear map [[4](https://en.wikipedia.org/wiki/Linear_map)], so the only way to both side to be equal is that $[T_x,T_y]=0$, so in general, some constraints must be true to be equal.
Comment: I think there's a miss-understanding. You're going from $T_x$ to $e^{T_x}$, I want to show that $T_x = e^G$ where $G$ is another linear operator. For example in the space of differentiable functions $T_x = e^{-x\frac{d}{dx}}$, how does this generalize to $L^p$ for example? My only thought was that since $B(L^p(X))$ is a Banach algebra and since $$ T_x T_y = T_{x+y}$$ I saw the resemblance with $f(x)f(y) = f(x + y)$ which has a solution an exponential.
Comment: I think essentially we're talking about different problems, because in your case you have $T_x$ and $e^{T_x}$ which are not the same operator, instead I am looking to represent $T_x = e^G$ where $G$ is another operator.
Comment: Maybe you are right and I don't understand your question (English is not native for me), what I was trying to pinpoint is that for some operator to behave as $T_x T_y = T_{x+y}$ must happen a lot of circumstances that aren't true in general, even for the Shift Operator where if $[X.Y]\neq 0$ the exponential split $f(x+y)=f(x)f(y)$ don´t happen.... when I was using the split-step Fourier method to simulate laser beams propagation through 1D thin holograms, I have to add another term of the expansion because it wasn't true for the differential equation that linear and non-linear stages commuted.
Comment: Looking for something totally unrelated I found these on Wikipedia, maybe it could be helpful to your research. Hope it helps you. [Cauchy's functional equation](https://en.wikipedia.org/wiki/Functional_equation) and [Functional equation](https://en.wikipedia.org/wiki/Cauchy%27s_functional_equation).


Twisted and Websockets: Beyond Echo

Question: In my ongoing curiosity about websockets, I'm noticing a trend:
The "hello world" of the websocket universe, at least at the moment, seems to be "echo" functionality.  That is, the demonstrated application is typically, "I send something, I receive something."
While aptly demonstrating that the protocol is functional, this example only actually demonstrates the same type of communication that the traditional request / response cycle enables.
For example, the only demonstration (on the server side) that I can find of twisted.web.websockets is the following:
import sys
from twisted.python import log
from twisted.internet import reactor
from twisted.web.static import File
from twisted.web.websocket import WebSocketHandler, WebSocketSite

class Echohandler(WebSocketHandler):

    def frameReceived(self, frame):
        log.msg("Received frame '%s'" % frame)
        self.transport.write(frame + "\n")

def main():
    log.startLogging(sys.stdout)
    root = File(".")
    site = WebSocketSite(root)
    site.addHandler("/ws/echo", Echohandler)
    reactor.listenTCP(8080, site)
    reactor.run()

if __name__ == "__main__":
    main()

How can I instead examine "push" capability here?  ie, how I can leave the web socket open, and then later, at some time determined by the occurrence of some event, send a message through the websocket, the content of which is also influenced by this event?
(Those interested by this question might also regard as compelling this question that I asked a few days ago: Making moves w/ websockets and python / django ( / twisted? ))
Comment: No, not necessarily.  Athena is a complete high-level messaging system, it doesn't just transport bytes.  And Orbited can use multiple transports, falling back to more primitive / less efficient techniques as it determines that the better ones aren't available.  This is something you want even in your situation, because if something *better* than websockets comes along, you'd probably like to take advantage of it without having to rewrite all your code.
Comment: @Glyph: Amazing.  This is point #6 in the question I asked here: http://stackoverflow.com/questions/4310706/django-comet-push-least-of-all-evils (outstanding 50 point bounty! ;-)).  Can you show a quick demonstration of how Orbited can be used with Websockets and then fall back to long-polling in the absence of proper support?
Comment: Given that websockets are disabled in Firefox 4 http://hacks.mozilla.org/2010/12/websockets-disabled-in-firefox-4/ , and even when they're done, they might want not work in all browsers, you probably want to investigate a higher-level abstraction for your two-way browser communication.  Websockets are just a way to optimize things like Athena http://divmod.org/trac/wiki/DivmodNevow/Athena and Orbited http://orbited.org/ .
Comment: As shoddy as the current spec (and support) is, aren't websockets actually a complete remake of Comet (Athena, Orbited, etc.?).  For the moment, I'm not interested in solutions that will work in all browsers; I just want to build something that will work between myself and other members of a collective - we'll have full control over our browser and firewall conditions.
Answer: This is an example of an updated EchoHandler that will instead of just being reactive, be proactive.
class ChattyHandler(WebSocketHandler):
    def connectionMade(self):
        self.transport.write('oh hai\n')
        self.saysomething()

    def saysomething(self):
        self.transport.write('still there?\n')
        reactor.callLater(5, self.saysomething)

Unfortunately, websockets from https://github.com/rlotun/txWebSocket/ doesn't seem to have the connectionMade() method, and instead the only thing you can hook into is the __init__. usually you would just override connectionMade() if it were a 'normal' twisted protocol. --Fixed in upstream
Comment: I maintain https://github.com/rlotun/txWebSocket/ and I have just added a `connectionMade` hook.
Comment: This raises TypeError: __init__() argument after * must be a sequence, not WebSocketTransport
Answer: Using hendrix, I showed how to set up a web app in a talk at Django-NYC that uses websockets to push messages from a telnet server to a web page.

Twisted and Websockets: Beyond Echo


What happens when this passage is repeated in just intonation?

Question:
What happens when this passage is repeated in just intonation?
My answer to this question is the pitch drifts up by a syntonic comma because of the F# being close to the E. I am not sure how to elaborate on this, but is this correct or is my reasoning correct?
Comment: My guess is that a correct answer to this question requires numbers.  What are the frequency ratios for the intervals in the passage?
Comment: Why wouldn't we get no drift at all if we play this on a piano tuned with just intonation? (Alternately, we get a great singer to sing this.)
Comment: @Dekkadeci indeed, there's no reason that it has to drift.
Answer: Let's say we do each interval just. Then e-a is 4:3 and a-f# is 5/4 : 3/2 = 5:6. So finally we get e-f# becomes 4:3·5:6 = 10:9.
So we get the so called small whole step, which is slightly smaller (by one syntonic comma) than the big whole step at 9:8 (9:8 / 10:9 = 81/80 is the syntonic comma).


How to avoid lost styles in browser recorded inputs

Question:
I have a custom input with my own css styles, but when the browser complete the recorded info for that fields , the styles lost
Answer: Work on
<code>::focus
</code>
element too.. i hope it will work.


Find the sharpest lower bound $c$

Question:
Fix an even number $n$. The random variables $X_1 , X_2 ,...,X_n$ take values in the set {−1, 1}. There is a constant $c$ so that, for $i \neq j$, $E[X_i X_j ] = c$. Find the sharpest
  lower bound you can for $c$.

I think $c$ should be greater than or equal to zero, but cannot prove it. Can you give me some ideas?
PS: Please don't downvote my problem if you don't have any ideas. This problem does make sense, since it's a problem in an ivy school's prelim exam. Thank you!
Comment: Can you share what you've tried, and exactly what you're having trouble with? It is quite frequent that questions posed as isolated exercises are downvoted when they are dumped without any apparent thoughts or efforts from the asker.
Comment: I don't put my thoughts because I have no ideas on this problem, so I want to get some hints from other people.
Answer: The random variable $(X_1+\dots+X_n)^2$ is non-negative, hence
$$ 0\leq \mathbb{E}[(X_1+\dots+X_n)^2]=\sum_{i=1}^n\mathbb{E}[X_i^2]+\sum_{i\neq j}\mathbb{E}[X_iX_j]=n+n(n-1)c$$
This implies that $c\geq -\frac{1}{n-1}$.
Thus it is enough to show that this bound is optimal. To do so, let $\Omega$ be the subset of $\{-1,1\}^n$ consisting of those sequences with an equal number of $1$s and $-1$s. Note that if $n=2k$ then $|\Omega|={n\choose k}$ since an element of $\Omega$ is determined by the positions of the $1$s.
Give $\Omega$ the uniform probability law, and let $X_i(\omega)$ be the $i$th entry of $\omega$. To compute $\mathbb{E}[X_iX_j]$, observe that there are ${n-2\choose k-2}$ elements of $\Omega$ such that $X_i(\omega)=1=X_j(\omega)$, ${n-2\choose k}$ elements of $\Omega$ such that $X_i(\omega)=-1=X_j(\omega)$, and $2{n-2\choose k-1}$ elements of $\Omega$ such that $X_i(\omega)$ and $X_j(\omega)$ have opposite signs. Therefore
$$ \mathbb{E}[X_iX_j]=\frac{{n-2\choose k}+{n-2\choose k-2}-2{n-2\choose k-1}}{{n\choose k}}$$
and this simplifies to $\frac{-1}{n-1}$ after some algebra if we recall that $n=2k$.
Comment: Why you only consider subset $\Omega$? I think if we want to compute $\mathbb{E}[X_iX_j]$, we should consider all the values from $\{-1,1\}^n$
Comment: I don't only consider a subset of $\Omega$. I defined $\Omega$ to be a subset of $\{-1,1\}^n$ having the properties I wanted.
Answer: Say you have $a$ of the variables being $1$ and $n-a$ being $-1$.  Then for $i \neq j$, $E[X_iX_j]=\frac {a(a-1)+(n-a)(n-a-1)-a(n-a)}{n(n-1)}$  This will be minimized (you need to justify this) when $a=\frac n2$ which will give you your bound.
Comment: I think you should consider all the situations with different $a$ and also you don't know what is the probability of each $a$

Find the sharpest lower bound $c$


VBA code to copy data from one worksheet & paste below last row of another worksheet

Question: I am trying to write a code to import data from one workbook to another.
The source workbook will change everytime.
The target workbook is History Statistics
After importing the data to source worksheet: Sheet 2, I wish to copy the entire data except headers & paste below the last row of target sheet: Sheet 1
I am able to do the first part of importing the data into worksheet Sheet 2. But I don't know why the code for copy-paste does not give any result even though it runs and gives no error. So, cannot find the error and cannot understand what is going wrong.
Please help me understand the problem! Thanks! :)
This is my code:
Public Sub Add_Data()

Application.ScreenUpdating = False

Dim TabName As String

TabName = "Sheet 2"

ActiveSheet.Name = TabName

count1 = Workbooks("History Statistics.xlsm").Sheets.Count
Sheets(TabName).Copy After:=Workbooks("History Statistics.xlsm").Sheets(count1)

Workbooks("History Statistics.xlsm").Activate

MsgBox ("Data has been added to the master file")

Dim WS As Worksheet
Dim ColList As String, ColArray() As String
Dim LastCol As Long, LastRow As Long, i As Long, j As Long
Dim boolFound As Boolean
Dim delCols As Range

On Error GoTo Whoa

Application.ScreenUpdating = False

'~~> Set your sheet here
Set WS = Sheets("Sheet 2")

'~~> List of columns you want to keep. You can keep adding or deleting from this.
'~~> Just ensure that the column names are separated by a COMMA
'~~> The names below can be in any case. It doesn't matter
ColList = "Object Code, Points, Type, F, Module, Global Resp. Area"

'~~> Create an array for comparision
ColArray = Split(ColList, ",")

'~~> Get the last column
LastCol = WS.Cells.Find(What:="*", After:=WS.Range("A1"), Lookat:=xlPart, _
LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
MatchCase:=False).Column

'~~> Get the last row
LastRow = WS.Cells.Find(What:="*", After:=WS.Range("A1"), Lookat:=xlPart, _
LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
MatchCase:=False).Row

'~~> Loop through the Cols
For i = 1 To LastCol
    boolFound = False
    '~~> Checking of the current cell value is present in the array
    For j = LBound(ColArray) To UBound(ColArray)
        If UCase(Trim(WS.Cells(1, i).Value)) = UCase(Trim(ColArray(j))) Then
            '~~> Match Found
            boolFound = True
            Exit For
        End If
    Next
   '~~> If match not found
    If boolFound = False Then
        If delCols Is Nothing Then
            Set delCols = WS.Columns(i)
        Else
            Set delCols = Union(delCols, WS.Columns(i))
        End If
    End If
Next i

'~~> Delete the unwanted columns
If Not delCols Is Nothing Then delCols.Delete

LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue

WS.Range(Cells(2, 1), Cells(LastRow, LastCol)).EntireRow.Copy Destination:=Sheets("Sheet 1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

End Sub

Comment: Your code is far more complicated then I'd guess from your description, please amend description, or delete non-relevant parts of the code. Have you tried [debugging](http://stackoverflow.com/documentation/vba/802/getting-started-with-vba/15512/debugging#t=201705091527354062327) your code? It should show you all the steps it does and you'll be able to see where it behaves differently then you expect.
Comment: @MátéJuhász: Will post the correct code as the Answer.
Comment: At the end, qualify `Cells()` with the sheet too...`WS.Range(WS.Cells(2, 1), WS.Cells(LastRow, LastCol)).EntireRow.Copy Destination:=Sheets("Sheet 1").Range("A" & Sheets("Sheet 1").Rows.Count).End(xlUp).Offset(1, 0)` ?
Comment: @BruceWayne: I just tried it, but does not give me the result.
Comment: @MátéJuhász: Thank you so much giving me the idea of debugging line by line. I figured out the error. The code `WS.Range(Cells(2, 1), Cells(LastRow, LastCol)).EntireRow.Copy Destination:=Sheets("Sheet 1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)` should be before the loop starts. Or else the code is running inside the loop and coming to the next line.
Comment: Nice you could use it? Did it resolve your problem? If yes then you're welcome to post it as an answer. If not, then please update your question and explain what's the current issue.
Answer: I figured out the error. The line
WS.Range(Cells(2, 1), Cells(LastRow, LastCol)).EntireRow.Copy Destination:=Sheets("Sheet 1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

should be before the loop starts. Otherwise the code is running inside the loop and coming to the next line.
Public Sub Add_Data()

Application.ScreenUpdating = False

Dim TabName As String

TabName = "Sheet 2"

ActiveSheet.Name = TabName

count1 = Workbooks("History Statistics.xlsm").Sheets.Count
Sheets(TabName).Copy After:=Workbooks("History Statistics.xlsm").Sheets(count1)

Workbooks("History Statistics.xlsm").Activate

MsgBox ("Data has been added to the master file")

Dim WS As Worksheet
Dim ColList As String, ColArray() As String
Dim LastCol As Long, LastRow As Long, i As Long, j As Long
Dim boolFound As Boolean
Dim delCols As Range

On Error GoTo Whoa

Application.ScreenUpdating = False

'~~> Set your sheet here
Set WS = Sheets("Sheet 2")

'~~> List of columns you want to keep. You can keep adding or deleting from this.
'~~> Just ensure that the column names are separated by a COMMA
'~~> The names below can be in any case. It doesn't matter
ColList = "Object Code, Points, Type, F, Module, Global Resp. Area"

'~~> Create an array for comparision
ColArray = Split(ColList, ",")

'~~> Get the last column
LastCol = WS.Cells.Find(What:="*", After:=WS.Range("A1"), Lookat:=xlPart, _
LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, _
MatchCase:=False).Column

'~~> Get the last row
LastRow = WS.Cells.Find(What:="*", After:=WS.Range("A1"), Lookat:=xlPart, _
LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, _
MatchCase:=False).Row

'~~> Loop through the Cols
For i = 1 To LastCol
boolFound = False
'~~> Checking of the current cell value is present in the array
For j = LBound(ColArray) To UBound(ColArray)
    If UCase(Trim(WS.Cells(1, i).Value)) = UCase(Trim(ColArray(j))) Then
        '~~> Match Found
        boolFound = True
        Exit For
    End If
Next
'~~> If match not found
If boolFound = False Then
    If delCols Is Nothing Then
        Set delCols = WS.Columns(i)
    Else
        Set delCols = Union(delCols, WS.Columns(i))
    End If
End If
Next i

'~~> Delete the unwanted columns
If Not delCols Is Nothing Then delCols.Delete

'copy-paste after last row
WS.Range(Cells(2, 1), Cells(LastRow, LastCol)).EntireRow.Copy Destination:=Sheets("Sheet 1").Range("A" & Rows.Count).End(xlUp).Offset(1, 0)

LetsContinue:
Application.ScreenUpdating = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub


Help computing some derivatives of $\frac{\|x-z\||^2}{\|x-z\|^2 + \|y-z\|^2}$?

Question: Ok, this shouldn't be that hard, but I'm having difficulties with this.
Consider a fixed $z \in \mathbb{R}^n$ and the function of two variables $f(x,y):\mathbb{R}^n \times \mathbb{R}^n \rightarrow \mathbb{R}$ given by
$f(x,y) = \frac{\|x-z\||^2}{\|x-z\|^2 + \|y-z\|^2}$. I want to compute $\nabla_xf(x,y)$, $\nabla^2_{xx}f(x,y)$ and $\nabla^2_{xy}f(x,y)$.
For $\nabla_xf(x,y)$, putting $D=\|x-z\|^2 + \|y-z\|^2$, I found
$\nabla_xf(x,y) = \frac{2}{D^2}\left[ D(x-z) - \|x-z\|^2(x-z)\right] = \frac{2}{D^2}\|y-z\|^2(x-z)$. Here I simply let the denominator squared and used the $f'g-fg'$ rule on the denominator, then the terms simplified since there is a term $\|x-z\|^2$ being added and subtracted. Now I just differentiate this simplified expression wrt both to $x$ and $y$ to get the other ones:
For $\nabla_{xx}f(x,y)$, putting $N=\|y-z\|^2(x-z)$ I got
$\nabla_{xx}f(x,y) = \frac{2}{D^4}\left[2D^2\|y-z\|^2I - 2DN(x-z)^T\right]$, just using the same derivative rule for the quotient. (Here $I$ is the identity matrix $n \times n$)
And wrt $y$ I got
$\nabla_{xy}f(x,y) = \frac{2}{D^4}\left[2D^2(x-z)(y-z)^T - 2DN(y-z)^T\right]$.
However I'm trying to use it all on a certain program that depends on these guys and it all points that I got the derivatives wrong, and I can't see the mistake for the life of me. What's wrong here?
Answer: I will do the $x$ case and leave you the $y$ case
$$
\phi(\mathbf{x})=
\frac
{\lVert \mathbf{x} - \mathbf{z} \rVert^2}
{\lVert \mathbf{x} - \mathbf{z} \rVert^2 +
 \lVert \mathbf{y} - \mathbf{z} \rVert^2}=
\frac
{N}{D}
$$
Note that
$ dD
= dN
= 2(\mathbf{x} - \mathbf{z})^T d \mathbf{x}$.
Thus
\begin{eqnarray*}
d\phi
&=& \frac{DdN-NdD}{D^2}
= 2\frac{D-N}{D^2} (\mathbf{x} - \mathbf{z})^T d \mathbf{x}
\end{eqnarray*}
The gradient is
$$
\frac{\partial \phi}{\partial \mathbf{x}}
= \frac{2\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^2}
(\mathbf{x} - \mathbf{z})
$$
Taking the differential once again
\begin{eqnarray*}
d\mathbf{g}
&=&
\frac{2\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^2}
d\mathbf{x}
-
\frac{4\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^3}
(\mathbf{x} - \mathbf{z}) dD \\
&=&
\frac{2\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^2}
d\mathbf{x}
-
\frac{8\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^3}
(\mathbf{x} - \mathbf{z}) (\mathbf{x} - \mathbf{z})^T d\mathbf{x}
\end{eqnarray*}
The second derivative is
$$
\frac{\partial \mathbf{g}}{\partial \mathbf{x}}
=
\frac{2\lVert \mathbf{y} - \mathbf{z} \rVert^2}{D^3}
\left[
D \mathbf{I}
- 4
(\mathbf{x} - \mathbf{z}) (\mathbf{x} - \mathbf{z})^T
\right]
$$
Comment: I see. Looks like I forgot that there is an additional 2 in the last terms of the 2nd order derivatives. One is from the derivative of the denominator D and other is because of the chain rule, because it's squared. Ty.


t() function doesn't render HTML

Question: It is the t() function and the way I assigned value to a body field
$my_body_content = t('!frequency new comment(s) sent to !title', array('!frequency ' => $frequency , '!url ' => $url , '!title ' => $title));
$ewrapper->field_body->set(array(
        'value' => $my_body_content
) );

the $frequency, $title and $url are already set. This is the configuration of the body field (it allows a tag)

But it is what I get

Why it doesn't render the HTML ?

UPDATE :
I edited the body by UI like this

and it worked! sounds the problem is because of the PHP code
Comment: Are you sure that string is generated from the code you are showing? The strings are quite different.
Comment: @kiamlaluno Yes I'm sure. There is an `IF` statement that this code is used in both sides of True and False position of `IF`. one of them is `comment(s)` another one is `comment` in the sentence
Comment: @kiamlaluno I tried `$my_body_content = 'hi';` and it was the result `hi`.
Comment: @kiamlaluno I updated the question
Comment: Then it was that: You are using two strings. By the way, if the strings are using plural and singular, there is a Drupal function for that.
Comment: I wonder why it works when the text is insert by UI but it doesn't when the text is inserted programmatically
Answer: This code should work for you
$link = l($title, $url);
$my_body_content = t('!frequency new comment(s) sent to !link', array('!frequency ' => $frequency , '!link' => $link));
$ewrapper->field_body->set(array(
    'value' => $my_body_content
) );

Comment: No, it was the result: `1new comment sent to !link`
Comment: your code works in `hook_preprocess_html` (for testing I used it in this function) but it doesn't work in node area
Comment: I tried `$my_body_content = 'hi';` and it was the result `hi`.
Comment: I updated the question
Answer: Ok, I found it. I should have add the format to field_body assignment as follow:
$ewrapper->field_body->set(array('value' => $my_body_content,'format'=>'full_html'));

t() function doesn't render HTML


Phonegap connection type returns null

Question: I want to get the connection type of my device, but the script return me null every time.
<code>function verificaconexiunea(){
                var conexiune = navigator.connection.type;
                alert(conexiune);
                var status={};
                status["Connection.UNKNOWN"]  = 'Conexiune necunoscuta';
                status["Connection.ETHERNET"] = 'Conexiune Ethernet';
                status["Connection.WIFI"]     = 'Conexiune WiFi';
                status["Connection.CELL_2G"]  = 'Conexiune Internet 2G';
                status["Connection.CELL_3G"]  = 'Conexiune Internet 3G';
                status["Connection.CELL_4G"]  = 'Conexiune Internet 4G';
                status["Connection.NONE"]     = 'Fara conexiune internet!';
}
</code>
The variable "conexiune" always return 0.
Can someone help me?
Answer: What version of Cordova? Did you wait for the deviceready event to fire?
Comment: Obviously devicready fire, because, how i said, that alert(conexiune); shows me "0". I use cordova 3.0.0.
Comment: Hmm, ok, I guess that is obvious but i wanted to be sure. So - did you add the connection plugin? Remember in Cordova 3 *every* single feature has to be added as a plugin.
Comment: Yes .. i added as a plugin in config.xml because plugins.xml doesn't exists. But still the same problem.
Comment: Adding it in config.xml is not good enough unless you're using PhoneGap Build. Are you? If you are building locally you need to add the plugin too.
Comment: Yes..i'm using phonegap build..how can i add the plugin?
Comment: Ah well then you do NOT have to add it. So I will say this - from what I know - the connection test is NOT always perfect. Since it doesn't throw an error but returns 0, it may mean it really can't just detect your connection. Are you on a 'odd' phone or a weird place connection-wise?
Comment: I have a lg oprimus black .. and the connection here supports 3G max signal ..:|
Comment: To be clear, PhoneGap Build still only supports 2.9, but that should be fine really. Unfortunately I don't have anything to suggest here. Since it returns 0 and not an error I'd assume it really can't read your device connection.

Phonegap connection type returns null


Is it possible to have a symmetric and transitive relation on $\mathbb Z$ that isn't reflexive?

Question: I was wondering this the other day and I have been trying to come up with an example for a bit but can't produce one. If there is a proof that such a thing couldn't exist I would be interested in seeing it. Seeing an example of such a set would also be cool as well. Thanks in advance !
Answer: The empty relation - nothing relates to anything else - is symmetric and transitive, but not reflexive.
Comment: In fact, this is essentially the only example: if $R$ is symmetric and transitive, then let $D=\{x: \exists y(xRy)\}$ be the set of elements which are $R$-related to anything at all; $R$ is reflexive if and only if $D$ is the whole domain of $R$. In particular, this means that, if $R$ is not reflexive, then there is some subset $S$ of the domain such that $R$, restricted to $S$, is the empty relation.
Answer: Well it is simple that is must be reflexive.Let R be relation in Z such that it is both symmetric and transitive.
Let xRy and yRx,but then by transitivity it must hold that xRx.
Thus such relation can not exist.
Comment: A relation on $X$ is just a subset of $X\times X$. There are no requirements for any element of $X$ to actually be related to anything. If every element is related to some other element, then--yes--symmetry and transitivity implies reflexivity.
Comment: In $\Bbb Z$ like elsewhere
Comment: There could be elements that are not related to any elements.
Comment: True,but then they would not belong to domain of the relation.
Comment: @TheCoolDrop It would still be a relation though. -1
Comment: If x is not related to anything then it does not belong to relation.It is absurdly obvious.I do not see a reason for -1 but ok
Comment: You can have a set though which is vacuously transitive. For example
Comment: But then same set is also vacously symmetric and thus also vacoulsy reflexive.
Comment: Just because $\forall y(\neg xRy)$ does not mean that $x$ is not in the domain of $R$. -1.


Standard FileField as dropzone upload area in Django form

Question: How can I set myfile form field as Dropzone.js upload area?
forms.py
class TestForm(forms.Form):
    title = forms.CharField(required=True)
    myfile = FileField()

views.py
class ExampleView(FormView):
    template_name = 'test.html'
    form_class = TestForm
    success_url = '/thanks/'

    def form_valid(self, form):
        print form.cleaned_data['title']
        print form.cleaned_data['file']
        return super(ExampleView, self).form_valid(form)

test.html
<form method="post" action="/test-form/">
    <input type="text" name="title" id="id_title">
    <input type="submit" value="Save">
</form>

Answer: Well, I just checked the dropzone website, and there are a few different ways.
One would be by configuring the paramName option: http://www.dropzonejs.com/#config-paramName
But it looks like you could just add the file field, e.g., <input type="file" name="myfile" />
You'll need to add class="dropzone" to the form.


Display POA in Ubercart 3 / D7 for products of zero dollars

Question: I'm building an ecommerce site where some products are price negotiable and want a way to add POA instead of a listing a price when a product is displayed.
I'm kinda surprised at how hard this is to do.. I have a snippet that works for Ubercart 1 in Drupal 5, but it looks like the hooks have changed in Ubercart 3 and I can't find a pricing hook:
    <?php
function zen_uc_product_display_price($price) {
  $output = '
';
    if ($price!=0) {
      $output .= uc_currency_format($price);
    } else {
      $output .= t('P.O.A');
    }
  $output .= '
';
  return $output;
}
function

zen_uc_product_sell_price($price, $teaser) {
  if ($teaser) {
    $output = '';
        if ($price!=0) {
            $output .= uc_currency_format($price);
        } else {
            $output .= t('P.O.A');
        }
    $output .= '';
  }
  else {
    $output = '
';
        if ($price!=0) {
            $output .= t('Price: !price', array('!price' => uc_currency_format($price)));
        } else {
            $output .= t('Price: P.O.A');
        }
    $output .= '
';
  }
  return $output;
}
?>

I've managed to hook the add to cart function and direct it to a webform with the following snippet:
<?php

function fmc_uc_product_add_to_cart( $variables ) {
$sell_price = $variables['form']['node']['#value']->price;
if ($sell_price <= 0) {
return '<form action="http://www.example.com/" method="post"><input type="hidden" name="product" value="' . drupal_get_title() . '" /><input type="submit" class="form-submit" value="' . t('POA') . '" /></form>';
}
else {
return fmc_uc_product_add_to_cart($variables);
}
}

But I'm having no luck with the pricing function, if anyones got a code snippet I can run in my template.php file that'd be the ideal solution, but any ideas / advice is hugely appreciated. Is there a way this can be broken out inside a node--product.tpl.php file maybe?
Answer: I have not tried this out but I would think you could override theme_uc_price() in your template.php something like this:
function THEMENAME_uc_price($variables) {
  if ($variables['price']) {
    $output = '' . uc_currency_format($variables['price']) . '';
    if (!empty($variables['suffixes'])) {
      $output .= '' . implode(' ', $variables['suffixes']) . '';
    }
  }
  else {
    $output = t('P.O.A');
  }
  return $output;
}

Comment: Perfect solution!
Comment: Oops... actually, I spoke to soon, something in this code is causing an internal server error for anything that does have a price... It works perfectly for items of $0 but kills anything that has a value for price.
Comment: What is the error in the web server log?
Answer: I finally managed to get this to work for me in Drupal 7/Ubercart 3 for an art gallery where we wanted POA to display for $0.00 and the price to display for priced items. The code below goes in the bottom of your theme template.php file.
 (please note to get all the code to show on here without this forum stripping bits out, I had to remove the opening tag before span so you just need to pop that back in eg: '(less-than-sign)span in line 2. Also right near the end replace '(less-than-sign)/div> as per this screenshot. Code to copy is below.

Hope this saves someone some hours!
    /* change uc price to show POA if price is zero */

 function YOURTHEMENAME_uc_price($variables) {
$output = 'span class="uc-price">';

if ($variables['price']!=0) {

  $output .= uc_currency_format($variables['price']);
} else {
  $output .= t('P.O.A');
}

$output .= '/div>';
  return $output;
}


How to add more Display Suite template suggestions

Question: If you have Display Suite installed, then on the "Manage Display" tab of any content type you will see template suggestions:

Possible template suggestions are:

ds-1col--node.tpl.php
ds-1col--node-page.tpl.php
ds-1col--node-page-search-result.tpl.php

None of these suit what I'm wanting to achieve, as I wanted a template to apply to all "search-result" view modes for any content type. So my template suggestion would be:

ds-1col--search-result.tpl.php

But it seems it's not by default accepted. Which hook can I use to add this template suggestion? I was thinking of hook_preprocess_node and adding my own template suggestion to theme_hook_suggestions but this didn't work as it wasn't using my suggestion on node types which have search_result view mode applied to them. The template was only being used on the ones without any search_result view mode configurations, and even then only normal node.tpl.php variables such as $content was passed to this DS template so I don't think it's the right way to do it.
Answer: The problem actually wasn't in ds-1col--search-result.tpl.php. It was when I suggested a custom template for a node when I was doing quick tests, with print $ds_content; in them, the nodes which didn't have the search_result view mode configured, weren't being preprocessed by display suite hence didn't have the $ds_content variable set which was being printed on the custom template. Hence it gave me the impression that it wasn't working.
But to answer the question, there's no special stuff you need to do to suggest a template for display suite. First copy the template from display suite folder to your themes folder. And then all you have to do is use the normal hook_process_node and suggest that template for a certain view mode.
Answer: In case you have Panels installed, DisplaySuite will benefit from the numerous layouts Panels (and its extentions) have to offer. You can even choose if you want to use the DS own Field UI, or the Panels editor to arrange the fields.
If you don't have Panels installed then ignore this reply. Maybe a more specific reply will help you out.
Comment: I just want to apply a single template to all node types on search_result view mode. Instead of doing a same template file for each single node type.


C: can't write data on file

Question: i want to open a file, write some data on it so i have to use (Fopen) " i can't use open because i need fopen in some other things "
now if i want to write on the file using fwrite it just don't i don't know why this is what i referred to in my code #option1, but if i get the file descriptor and use normal write method everything works fine see #option 2 below.
anyone can help me to make fwrite works ?
    char file_data[256] // has some values
    int file_size = strlen(file_data);
    FILE *file;
    file = fopen(MY_FILE_NAME, "w+");

    if(!file){//edited
           return false;
    }

    #option 1//this is not working
    fwrite(file_data,1,file_size,file);
    #end of option 1

    #option 2//this works
    int fd = fileno(file);
    int x = write(fd,file_data,file_size);//
    #end of option 1

EDIT
my file_data is something like this

4 bytes is reserved for an integer (required)
200 bytes is reserved for a string (optional)
Comment: file_data has some *binary* values or *ascii* values?
Comment: you can't use strlen() on such kind of data!
Comment: i just tried to put it hard coded on some example and still facing the same problem
Answer: buffered IO operations use a buffer that is managed by the C lib. Your "problem" is that fwrite is buffered meaning that in order to write to the file you most likely need to flush it with fflush() or just close the file.
Comment: i'm closing the file later in my code ... my problem is that it's not writing on that file and fwrite return a positive number !!
Comment: Tried used fflush ? Using your code and setting char file_data[256] = "testing" and then flushing it to a file = fopen("so_test", "w+"); works just fine.
Answer: If you want to check the fopen() return value, do like this:
if (file == NULL) return false;

then, if you want to write a string fputs() is preferable, IMHO, because it communicates better that what you're writing is a string.
Since, according to your last edit, you aren't writing ASCII strings, this is what you should code:
#include <stdio.h>

struct String
{
    int size;
    char data[200];
};

int main()
{
    struct String s;

    FILE* file = NULL;
    file = fopen("filename", "wb+");

    memset(&s, '\0', sizeof(s));
    strcpy(s.data, "Hello, world!");
    s.size = strlen(s.data);

    fwrite(&s, 1, sizeof(s), file);

    if (!file) return 1;

    fclose(file);
}

Comment: i tried fputs still facing the same problem my friend thanks a lot
Answer: First of all:
if(!file < 0 ){
       return false;
}

file is either NULL (on failure) or not (on success) - there's no point in testing it against 0 as it's a pointer (therefore, unsigned).
Your fwrite call seems OK, but you should make sure that the amount you're trying to write is correct (is there a null-terminated string inside file_data?).
Another problem you may be facing is that you don't close or flush the file - this may cause some data to remain in the file-buffer and not be written to the disk.
Comment: no i don't think there is a null char at the end because sometimes the filedata will only hold the first 4 bytes as an integer
Comment: In that case using strlen seems wrong, as it only works for strings (null terminated).
Answer: At first sight, the mistake seems to be at line #2:
int file_size = strlen(file_data);

This only works if there exists a terminal nul character. So file_size must be either provided for example as a function argument or the you must use the full size of the array.
The following should work:
int write_in_my_file(int data_int, const char* data_str)
{
  size_t written;
  FILE* file = fopen(MY_FILE_NAME, "wb+"); /* SuperJulietta */
  if (!file) return false;

  written = fwrite(&data_int, sizeof(data_int), 1, file);
  if (written == sizeof(data_int))
  {
    if (opt_str) fputs(opt_str, file);
  }
  fclose(file);
  return written == sizeof(data_int);
}

Note: this code was not compiled, and error handling is partial.
Edit : if you don't close the file, you'll have to call fflush instead.
Answer: I think you need to either do fclose(file) or fflush(file).  because fopen is buffered IO so It does not write immidiately, so to ensure that file write is done, you need to do this.
Answer: fwrite is used for binary output, so you have to open file with "wb"
Comment: The "b" flag has no effect on *nix systems.
Answer: You have to put a fflush(file); after the fwrite to force the writing of the data or you can also remove the buffer completely by doing a setbuf(file, NULL); after your fopen call.
Answer: I guess your fwrite code is not the problem.
Whenever the first byte in your file_data is \0 then you write nothing. Since the data is not a string, write 256 bytes. This code works:
#include <stdio.h>
#include <string.h>
#define MY_FILE_NAME "sample.bin"
#define SAMPLE_DATA  "Content Content"
int main()
{
    char file_data[256];
    int file_size = sizeof(file_data);

 // fill in some sample data
 memcpy(file_data, SAMPLE_DATA, sizeof(SAMPLE_DATA));

    FILE *file = fopen(MY_FILE_NAME, "w+");
    if (file) {
  fwrite(file_data, 1, file_size, file);
  fclose(file);
    }
}

You see, this is your fwrite. I use sizeof instead of strlen to determine the amount of bytes that will be written...
BR

C: can't write data on file


Is there any way to reorder the nodes in a View?

Question: I have a complicated View containing many pages and attachments. When I built the View, I didn't think much about the order of the pages and attachments, but now I would like to change the ordering because it affects how they are displayed in the end. I would also like the flexibility to add additional pages in the future and be able to control where those attachments appear in the page.
I know you can control an attachment's position using the Above/Below options, but I have one page with 6 attachments and I can't seem to break the ordering except by creating and deleting nodes.
Edit: I discovered that I can accomplish this by exporting the View and reordering the code there and then reimporting, but if a cleaner solution exists, I would love to hear it.
Answer: You may also consider using the draggableviews module. Basically you create an "administrative" display of your view allowing arbitrary reordering of the content of the "main" display using drupal drag-and-drop interface.
There's also a comparison page for node ordering modules on drupal.org
Answer: You can ues the Nodequeue module. Nodequeue allows you to create and arbitrarily sort "queues" of nodes and it integrates with the Views module.

The Nodequeue module allows users to collect nodes in an arbitrarily ordered list. The order in the list can be used for a any purpose, such as:

A block listing teasers for the five top news stories on a site
A user's favorite music albums
A group of favorite from which one is randomly displayed

Nodequeue provides a simple drag-and-drop interface to manually order any queue.


How do I bind an empty string instead of a zero for an int field in Spring MVC?

Question: I'm using the code below to bind the content that comes from the list to the view.
It's a list of person objects. This person object has one numeric field(year).
Sometimes the content of the year field in the db is zero.
When that happens it is binding zero on the input field of the form.
Instead I would like to bind an empty string.
That is, just leave the field blank instead of showing the number zero.
How do I do that?
Obviously, when there is an actual year it should keep displaying the year.
Model
@Entity
public class Person implements Serializable{

    private static final long serialVersionUID = 1L;

    private String name;

    private int year;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }

}

DTO
public class PersonList {

    private List<Person> personList;

    public List<Person> getPersonList() {
        return personList;
    }

    public void setPersonList(List<Person> personList) {
        this.personList = personList;
    }

}

Controller
@RequestMapping(value = "/person", method = RequestMethod.POST)
public ModelAndView editPerson(@ModelAttribute PersonList personList)
{
    //perform operations

    //display results
    ModelAndView modelAndView = new ModelAndView("Person.html");
    modelAndView.addObject("personListBind", personList);

    return modelAndView;

}

View
<form action="person" method="post" th:object="${personListBind}">

    Name:
    <input type="text" th:field="*{personList[__${itemStat.index}__].name}" />

    Year:
    <input type="text" th:field="*{personList[__${itemStat.index}__].year}" />

Answer: One way is to use derived value methods, so the UI sees the field as a string.
Model
@Entity
public class Person implements Serializable {

    // all members from question are here, including getYear() and setYear()

    @Transient // Not a database column
    public String getYearStr() {
        return (year == 0 ? "" : Integer.toString(year));
    }

    public void setYearStr(String yearStr) {
        this.year = (yearStr.isEmpty() ? 0 : Integer.parseInt(yearStr));
    }

}

View
    Year:
    <input type="text" th:field="*{personList[__${itemStat.index}__].yearStr}" />

Comment: This worked perfectly. Thank you. Couple questions. 1) Which of the available Transient should be used? I opted for org.springframework.data.annotation.Transient and it worked well. In fact, even removing Transient it worked well and didn't create a db field. So why it's needed? 2) How does the view knows which field to call if yearStr is not there? Yes, there is getYearStr but not yearStr like in the view. So not sure how the mapping occurs. For the other fields there is something like private String name. Then the view uses "name". So it matches.
Comment: @jkfe No, `name` and `year` does not access the *fields* by those names. A *getter* method named `getName()` implies a *property* named `name`. A `setter` method named `setName()` implies that the property is updatable. That's why `getYearStr()` makes Thymeleaf see a property named `yearStr`. The *fields* are `private` cannot be seen by Thymeleaf.
Comment: I see. Thanks for the explanation. Sure, private. Forgot about that. What about transient?
Answer: Something along these lines should work for you if I understand correctly.
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

<input type="text" th:if="${year eq 0}" value="No year">
<input type="text" th:unless="${year eq 0}" th:value="${year}">

Comment: How does that make the POST handling work *(see Controller `editPerson` method)*?
Comment: Looks like I misunderstood what he was trying to do completely. Your solution looks good I think.
Comment: theChoosyBeggar I tried this, but did not work to display empty field. But looks promissing. Would like to learn about this if and unless in thymeleaf. Maybe I did something wrong. Can you clarify? I see Andreas mentioned the issue with POST. Would like to try to get to that. Maybe doing a requestparam and converting on the controller would work.
Comment: Using this thymeleaf condition idea I could make it correctly display blank when year is zero and show the year when there is one. This is the code: . The problem is that when I edit the field and click save and then check the value in the controller, it continues to be zero. Guess that's what andreas was refering to as the POST issue. No way to solve that?


Can $f(x)=\sin(x)  +  \cos^2(x)$ take the value $\sqrt{2}$?

Question: Can $f(x)$ take the value of $\sqrt{2}$, where
 $$f(x)  = \sin(x)  +  (\cos(x))^2\quad ?$$
When equating the value of $f(x)$ to $\sqrt{2}$, it gives imaginary values of $\sin(x)$.
Thanks in advance.
Comment: I thought the main goal should be that of leading, or at least making an effort to lead the OP to an answer; not just answering the question.
Comment: Do you know how to find the max and min of a function? If so, you could see if the max is larger than $2^{1/2)$ or not.
Comment: The function is $2\pi$-periodic, so you just need to check the interval $[0,2\pi)$.  What does the derivative tell you?
Comment: @AntonioVargas Actually i did not try by using derivation . I made a quadratiic equation and then tried to find the roots of this equation.
Comment: @Antonio: I was referring to the answers below. Yours I thought was fine. I mean, for someone starting, to throw in a lot of machinery.... I don't know.
Answer: Since $\cos^2x=1-\sin^2 x$, our equation becomes $\sin^2 x-\sin x+\sqrt{2}-1=0$.
Solve the equation $w^2-w+\sqrt{2}-1=0$. The roots are
$$w=\frac{1\pm \sqrt{1-4(\sqrt{2}-1})}{2}.$$
The discriminant $1-4(\sqrt{2}-1)$ is negative, so our quadratic in $w$ has no real roots. It follows that there cannot be a real number $x$ such that $\sin x+\cos^2 x=\sqrt{2}$.
This does not fully answer the question. We can ask whether there are complex non-real solutions.  For that, look at the two non-real values of $w$ obtained above. Call them $w_1$ and $w_2$. Recall that if $z$ is a complex number, then
$$\sin z=\frac{e^{iz}-e^{-iz}}{2i}.$$
So we want to solve the equations
$$e^{iz}-e^{-iz}=2iw_j \quad (j=1,2).$$
Multiply both sides by $e^{iz}$, and simplify. We get
$$e^{2iz}-2iw_je^{iz}-1=0.$$
Make the substitution $u=e^{iz}$. We arrive at the equations
$$u^2-2iw_j u-1=0 \quad (j=1,2).$$
These are a quadratic equation with complex coefficients. One can write down the solutions in more or less the usual way, and from them obtain the values of $z$ that work. There are  infinitely many of them, just like there are, for example, infinitely many $x$ such that $\sin x=1/2$.
Remark To show that there are no real solutions, one does not need to recall the Quadratic Formula. We are interested in the equation  $\sin^2 x-\sin x-1+\sqrt{2}=0$.
If we complete the square, we get
$$\sin^2 x-\sin x-1=\left(\sin x-\frac{1}{2}\right)^2-\frac{5}{4}.$$
Since $\left(\sin x-\frac{1}{2}\right)^2\ge 0$, it follows that
$\sin^2 x-\sin x-1$ must always be $-\frac{5}{4}$. Since $\sqrt{2}-\frac{5}{4}$ is positive, we conclude that we cannot have $\sin^2 x-\sin x-1+\sqrt{2}=0$.
 .
Answer: The local extrema will occur where $f\,'(x)=0$, or when factored, $(\cos x)(1-2\sin x)=0$. We can use the identity $\sin^2 x+\cos^2x=1$ to compute the possible extrema as
$$\cos =0 \implies \qquad \pm\sqrt{1-0^2}+0^2=\pm1 $$
$$\sin = 1/2 \implies \qquad \frac{1}{2}+\left|1-\frac{1}{2^2}\right|=5/4.$$
Of course $f$ is periodic and bounded so its image must be $(-1,5/4)$, which does not include $\sqrt{2}$.
$\hskip 1.6in$
This reasoning applies to the reals. Allowing complex arguments is another story.
Answer: You ask if $f(x) = \sin x + \cos ^2 x$ can be equal to $\sqrt 2$. In short, no, it can't.
Now is when I take a moment to thank anon for noting that $1 < \sqrt 2$. That whole arithmetic thing.... yeah. Anyhow.
If one uses the first derivative test, then you can note that the max should occur around $\pi/6$ or $5 \pi / 6$ (plus multiples of $2\pi$ if desired). At both of these values, the function is a mere $1.25$, which (I hope anon checks me again) is less than $\sqrt 2$.
Comment: $\sqrt{2}>1$ no?
Comment: @anon: Thank you for catching my error as well. Some sort of silliness must be in the air tonight.
Answer: Put $\sin x =:u$. Then the question is whether the function
$$g(u):=u+(1-u^2)={5\over4}-\Bigl(u-{1\over2}\Bigr)^2$$
can take the value $\sqrt{2}$ in the interval $-1\leq u\leq 1$. This is obviously not the case.


Should I fit regression line to scatter or to the mean values?

Question: I have two random variables and I am trying to see if and how much they are correlated. One of them (say X) is discrete and the other (say Y) is continuous. I used Seaborn to do the linear regression on the scatter plot for X-Y and I got the following:

In this case, the correlation between the two comes out tp be 0.5. I then took mean of all Y values for a given X and then did the regression again and got this:

Now I get the correlation to be close to 1! My question is, which one of these provides realistic description of the datasets and why?
Comment: Actually the situation may be even more complicated than I assumed in my comments to @AdamO - it's not just that the conditional mean is not linear in `dist`. Apparently even the distribution "around" the conditional mean seems to be a function of `dist`. Maybe you need a GLM. I suggest that you ask another question where first of all you describe in much more detail your problem (what are `assort`  and `dist`? How are they measured? What is your hypothesis on the relationship between them?) and  then you ask which model would be the more appropriate for this problem.
Answer: The averages may be close to linearly related but individual points are not.
There is variation from a linear relationship. A correlation coefficient can show this in two ways. 1) if there is scatter (which is deviation from linear). 2) if the relationship is not linear (which is, clearly, deviation from linear).
What you found out is that the function describing the relationship of the averages is pretty much linear (your second analysis, which shows that the 'line' versus 'averages of multiple points', is nearly the same model), but the linear relation has a lot of scatter on top of it (the first analysis). This means that, the two coordinates for a point are not strongly linearly related.
The correlation tells how much, in the case for 'any point', one variable can be (linearly) related to another one. Your first image clearly shows that this is not the case (or at least not so much, since you end up in the middle between 0 and 1).
The best image to show the relationship would be the combination of both images. In that way another observer could directly see what is going on (which is two things at the same time, there is a linear trend, but still there is also some, non uniform, scatter). I would plot the averages, or maybe boxplots, with estimates and the data points on top of it (some jittering would be nice, it is currently difficult to see how many points you have in your 4 and 5 'dist' levels). Although this can be done in multiple ways. It depends on what your readers would like to see, or can handle.
An interesting point is to see that the lines are not the same in the two different cases. This is because the different weights. In the second image each average counts the same weight. In the first image this is not the case. It seems to me that there are four heavy points, the three at assort=0 and the one at dist = 4 and assort = 0.75, which dominate the line.
It looks like the linear relation ship is mostly in the variation of the scatter among the different 'dist' levels. It might be interesting to see what happens with the median or with other percentile levels (you chose the mean in your second study, but you may wonder whether it shows correctly what is going on). Also showing the variation of the scatter (and not just the means) seems to me a correct way to present the data.
Answer: That is simply regression to the mean! The averages will always be less disperse, less heterogeneous than the specific observations.
In a regression model, however, it is good to assess the adequacy of the straight-line approximation obtained in linear regression. Calculating averages over the domain of one or more regressors is a very good exploratory analysis, but I would not compare the sample correlation to the aggregate correlation because there will be regression to the mean.
Comment: Just now somebody asked me to build a Bayesian model because fluctuations are not Gaussian. Do you have any good reference for that?
Comment: @Peaceful that is a separate question, and probably too broad for this site without more specific details. It is a known fact to statisticians that linear regression is perfectly suited to modeling conditional means if "fluctuations" (errors) are not Gaussian.
Comment: @AdamO well, it depends on what method you use to estimate the linear model. If you use OLS and errors are not normal, then inference is *not nearly* perfect, including confidence intervals and $p$-values, which the OP seems to care about. Now I don't know Seaborn and I can't be quite sure which estimator it implements, but I would be frankly quite surprised if it had anything "fancier" than OLS, such as for example the Huber $M-$estimator or the sandwich estimator.
Comment: @Peaceful the point is not just that the errors are (evidently) non-Gaussian. It's also quite evident that the conditional mean is not a linear function of `dist` (btw, `dist` is ordinal, not just categorical, right?), since the response appears to have an upper bound. It's not easy to say since you have much more observations at values of `dist` < 4, than you have for `dist` equal to 4 or 5, but I think you have sufficient elements to rule out the possibility that the conditional mean is linear in `dist`.
Comment: @AdamO: The point is that I have never heard of Building a Gaussian model for regression! Can you suggest something to start with?
Comment: @DeltaIV the point of regression and Pearson correlation is to summarize the strength of the first order trend in the data. It's clear that there is some form of positive association in these data, and the regression model tells us that. If the OP is interested in a different question, then they should edit the question to address the scope and purpose of the analysis. The observation that aggregate means more closely conform to the regression line than individual observations was the question.


get how much time python subprocess spends

Question: I'd like to time how long does the subprocess take.
I tried to use
start = time.time()
subprocess.call('....')
elapsed = (time.time() - start)

However it's not very accurate (not sure related to multi-process or sth else)
Is there a better way I can get how much time the subprocess really spends?
Thank you!
Answer: It depends on which time you want; elapsed time, user mode, system mode?
With resource.getrusage you can query the user mode and system mode time of the current process's children. This only works on UNIX platforms (like e.g. Linux, BSD and OS X):
import resource
info = resource.getrusage(resource.RUSAGE_CHILDREN)

On Windows you'll probably have to use ctypes to get equivalent information from the WIN32 API.
Comment: [This other answer](https://stackoverflow.com/a/13933797/6196010) is quite more explicit about how to go about this.
Comment: this answer looks fine for timing python code, but if we are running a subprocess, this may not be accurate, since Popen.wait() uses a busy loop. [https://docs.python.org/dev/library/subprocess.html#subprocess.Popen.wait]
Comment: @ggg Not sure if this is really a problem: Popen.wait() should run in the current process. Therefore, the resource usage of child processes should not be affected.
Answer: This is more accurate:
from timeit import timeit
print timeit(stmt = "subprocess.call('...')", setup = "import subprocess", number = 100)

Answer: It took me a little while to implement Roland's solution due to the annoyingness of passing around python code as strings, so I thought I'd share a working example.
This script times an external program in the working directory, and redirects its standard output and standard error to files.
from timeit import timeit

reps = 500
stdout = open("add_numbers_outputs.log", 'w')
stderr = open("add_numbers_errors.log", 'w')
external_command = "./add_numbers"
parameter = str(1000000) # one million

call_arguments = """[
        '%s',
        '%s'], # pass additional parameters by adding elements to this list
        stdout=stdout,
        stderr=stderr
""" % (external_command, parameter)

print "Timing external command "+external_command+" with parameter "+parameter

time_taken = timeit(stmt = "subprocess.call(%s)" % call_arguments,
        setup = """import subprocess;
stdout = open("add_numbers_outputs.log", 'w');
stderr = open("add_numbers_errors.log", 'w')
""",
        number = reps) / reps

print "Average time taken for %s repetitions: %f seconds" % (reps, time_taken)

Comment: If it would make your code easier, you can pass a function to `timeit()` and avoid having to put any Python code inside of strings.


problema com jQuery ajax

Question: Estou enfrentando um problema ao utilizar o google charts, onde o mesmo está funcionando perfeitamente no Internet Explorer, porém ao executar a mesma página no google chrome ou no firefox, os gráficos não são apresentados
minha action
[OutputCache(Location = OutputCacheLocation.None)]
        public string TopClientes(int top, DateTime dataInicio, DateTime dataFim)
        {
            using (BindContext context = new BindContext())
            {
                var dados = from l in context.LogEntity
                            where l.Date >= dataInicio && l.Date <= dataFim
                            group l.LogId by new { HostName = l.HostName } into bg
                            select new TopClientsViewModel()
                            {
                                Client = bg.Key.HostName,
                                Count = bg.Count()
                            };

                var logs = dados.OrderByDescending(a => a.Count).Take(top).ToList();

                DataTable dt = new DataTable();

                //Act -----------------
                dt.AddColumn(new Column(ColumnType.String, "Cliente"));
                dt.AddColumn(new Column(ColumnType.Number, "Consultas"));

                foreach (var log in logs)
                {
                    var row1 = dt.NewRow();
                    row1.AddCellRange(new[] { new Cell(log.Client, null), new Cell(log.Count, null) });
                    dt.AddRow(row1);
                }

                var json = dt.GetJson();

                return json;
            }
        }

minha view
@model Deltacompy.SSH.BindWeb.Models.BindLogGraficosViewModel
@{
    ViewBag.Title = "Reports";
}

Reports

@using (Html.BeginForm())
{

            @Html.LabelFor(a => a.Top, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.Top, new { htmlAttributes = new { @class = "form-control" } })

            @Html.LabelFor(a => a.DataInicio, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.DataInicio, new { htmlAttributes = new { @class = "form-control" } })

            @Html.LabelFor(a => a.DataFim, htmlAttributes: new { @class = "control-label" })
            @Html.EditorFor(a => a.DataFim, new { htmlAttributes = new { @class = "form-control" } })

                <button type="submit" class="btn btn-primary" id="btnPesquisar">

                </button>

}

@section styles {
    <link href="@Url.Content("~/Content/googlechart.css")" rel="stylesheet" />
    <link rel="stylesheet" href="@Url.Content("~/Content/bootstrap-datetimepicker.css")" />
}

@section scripts {

}

meu js
function topClientes(url, top, dataInicio, dataFim, title, container) {
    // Load the Visualization API and the piechart package.
    google.load('visualization', '1.0', { 'packages': ['corechart'] });

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

        var jsonData = $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            url: url,
            data: "{ top: " + top + ", dataInicio: '" + dataInicio + "', dataFim: '" + dataFim + "'}",
            async: false
        }).responseText;

        // Create our data table out of JSON data loaded from server.
        var data = new google.visualization.DataTable(jsonData);

        var options = {
            'title': title,
            bar: { groupWidth: "95%" },
            animation: {"startup": true},
            'height': 300,
            'width': '100%',
        };

        // Instantiate and draw our chart, passing in some options
        var chart = new google.visualization.ColumnChart(document.getElementById(container));
        chart.draw(data, options);
    }
}

Erro do console do chrome
Uncaught Error: Invalid JSON string: <!DOCTYPE html>

        <title>JSON primitivo inválido: object.</title>
        <meta name="viewport" content="width=device-width" />

Erro de Servidor no Aplicativo '/'.

 JSON primitivo inválido: object.

             Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

             Detalhes da Exceção: System.ArgumentException: JSON primitivo inválido: object.

            Erro de Origem:

Exceção sem tratamento foi gerada durante a execução da atual solicitação da Web. As informações relacionadas à origem e ao local da exceção podem ser identificadas usando-se o rastreamento de pilha de exceção abaixo.

            Rastreamento de Pilha:

[ArgumentException: JSON primitivo inválido: object.]
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +874
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +438
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth) +466
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +378
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth) +1462
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +277
   System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) +103
   System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +206
   System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input) +86
   System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +298
   System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +123
   System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +160
   System.Web.Mvc.ControllerBase.get_ValueProvider() +85
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +154
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +199
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +1680
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +59
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout) +94
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +574
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +82
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +105
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +588
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +47
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +65
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +139
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +604
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +50
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +98
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +73
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +151
   System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object callbackState, BeginInvokeDelegate`1 beginDelegate, EndInvokeVoidDelegate`1 endDelegate, TState invokeState, Object tag, Int32 timeout, SynchronizationContext callbackSyncContext) +106
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +551
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +103
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

            Informações sobre a Versão: Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:18.104.22.168

Comment: O que o Console do Chrome pega da requisição? Já verificou?
Comment: @CiganoMorrisonMendez, adicionei ao post o erro do console.
Answer: Não é assim que se monta um JSON para enviar para a requisição:
var jsonData = $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: url,
        data: "{ top: " + top + ", dataInicio: '" + dataInicio + "', dataFim: '" + dataFim + "'}",
        async: false
    }).responseText;

A mensagem de erro mostra isso claro: que o JSON não está na formatação correta.
Use a função do JavaScript $.toJSON() para isso:
var meuJson = { top: top, dataInicio: dataInicio, dataFim: datafim };
var jsonData = $.ajax({
        type: 'POST',
        dataType: 'json',
        contentType: 'application/json',
        url: url,
        data: $.toJSON(meuJson),
        async: false
    }).responseText;

Comment: o problema na realidade era a declaração no meu script da variável top, sendo que ao rodar top no console ele me retorno `Window {top: Window, location: Location, document: document, window: Window, external: Object…}`, sendo isso o problema, mudei o nome da variável e resolvi meus problemas.

problema com jQuery ajax


Statistical significance between years; what test to use

Question: I have a data set (2003 rows and 2 columns) containing: years (2011 and 2013) and contact with hospital (yes/no). The persons answering the question are independent between 2011 and 2013.
What test should I use to check if there is a statistical difference between the years?
What test should be used if contact with hospital had three or more alternatives?
Answer: If you don't care about the ordered relationship of years, use a chi-square test. If further types of contact with the hospital have no order (ie no contact, had contact or uninsured) chi-square is still applicable.
If you need to know the effect of advancing years on hospital contact, use logistic regression. If you have a collection of counts of contacts per year (ie 0,1,2,...), consider a count model, such as Poisson regression.
Comment: Thank you for your response! What if I was to add a change that happened in 2012, so 2011 the change had not yet happened and 2013 the change had happened. And I would still have the question of difference between 2011 and 2013, that is to say is there a statistical difference before the change and after the change between 2011 and 2013 for persons having contact with the hospital or not? Would it still be the same sort of suggested tests?
Comment: Yes, you create a variable representing the era before and after the change and then proceed with chi-square or logistic regression.
Comment: Please accept an answer if it answers your question.


Security concern over method of removing tags from html

Question: I am using findAndReplaceDOMText, a library that lets you wrap text that spans multiple tags.
Consider wrapping o b in  tags in the following html:

foo bar

It generates the following:

foo bar

This works great. My concern is that my strategy for removing these tags may open up the potential for code injection. The below code does work, I am just worried of potential code injection opportunities, particularly because I'm working on a chrome extension, so the target page's HTML may be malformed.
import $ from 'jquery'

export default function clearMarks() {
  $(".deepSearch-highlight").parent().each(function() {
    const contents = []
    const $parent = $(this)
    $parent.contents().each(function() {
      const $node = $(this)
      let html

      if ($node.hasClass("deepSearch-highlight")) {
        html = $node.html()
      }
      else if (this.nodeName === "#text") {
        html = this.data
      }
      else {
        html = this.outerHTML
      }
      contents.push(html)
    })
    $parent.html(contents.join(""))
  })
}

My goal is to restore the html to exactly what it was before it was transformed with findAndReplaceDOMText. In the "additional information" section you can see how a simpler clearMarks function will result in a change to the number of text nodes.
Does my strategy have any security vulnerabilities I'm missing? Is there a more secure/more elegant/generally better way of achieving my goal?

Additional Information:

I am using the findAndReplaceDOMText option preset: "prose" which:

Ignore non-textual elements (E.g.


Find specific node to uninstall a module

Question: I want to uninstall a module but I'm getting the following message. The "Name of Module" field type is used in the following field: node.field_feature_interest. How can I find this node so I can remove their relationship between each other so that I can delete the module?
Answer: I figured out how to do it:

Go to content types
Features Article ->Manage Fields
Delete field


Problema ao marcar todos os checkbox

Question: Como devo proceder para marcar os input's checkbox? Está apenas desmarcando.
Seguem os códigos para auxílio:
HTML

<input type="checkbox" ng-click="marcarDesmarcarTodos('checkParticipantes')" id="ckeckAll" name="checkAll" />Marcar/Desmarcar Todos

<input type="checkbox" name="checkParticipantes" ng-click="ckeckMarcarDesmarcarTodos()" ng-model="participante.selecionados[pessoa.ID_PESSOA_EVENTO]" />

JavaScript - AngularJS
$scope.ckeckMarcarDesmarcarTodos = function () {
        if( $('#ckeckAll').is(':checked')) {
            $('#ckeckAll').prop("checked", false);
        }else {
            $('#checkAll').prop("checked", true);
        }
    };

$scope.selectedAll = false;
$scope.marcarDesmarcarTodos = function ()
{
    $scope.selectedAll = !$scope.selectedAll;
    if ($scope.selectedAll) {
        $scope.participante.selecionados = {};
        angular.forEach($scope.participante, function (item) {
            $scope.participante.selecionados[item.idPessoaEvento] = $scope.selectedAll;
        });
    } else {
        $scope.participante.selecionados = {};
    }
};

Answer: Faça assim:
$scope.ckeckMarcarDesmarcarTodos = function () {
     if( $('#ckeckAll').is(':checked') ) {
           $('#ckeckAll').prop( "checked", false );
     } else {
           $('#ckeckAll').prop( "checked", true);
     }
};

Faltava apenas um else para marcar os checkbox, tambem troquei o removeAttr por prop, que é mais indicado.
Comment: Wagner, ainda continua do mesmo jeito.
Comment: Wagner, infelizmente não funcionou !
Comment: Como está os checkbox que serão marcados/desmarcados? coloca o código deles ai pra vermos.
Comment: Wagner, editei os códigos novamente abaixo da pergunta, conforme vc solicitou.
Comment: Coloca um id nos checkbox assim id="checkParticipantes", ai no script altere para $('#checkParticipantes').prop( "checked", false ); e  $('#checkParticipantes').prop( "checked", true);
Answer: Salve o valor atual em uma varíavel:

var isChecked = $('#ckeckAll').is(':checked');

E "inverta" o valor de checked

$('#ckeckAll').prop('checked', !isChecked);

Se for checado, irá alterar para não checado e vice versa.
$scope.ckeckMarcarDesmarcarTodos = function () {
  var isChecked = $('#ckeckAll').is(':checked');
  $('#ckeckAll').prop('checked', !isChecked);
};

Answer: Uma solução puramente Angular (sem jQuery):

angular.module('myApp', [])
.controller('myController', function($scope){
  $scope.selected = {};

  $scope.items = ['Item 1','Item 2','Item 3','Item 4'];

  $scope.checkAll = function(){
    angular.forEach($scope.items, function(i){
      $scope.selected[i] = true;
    });
  };

  $scope.checkNone = function(){
    $scope.selected = {};
  };
});

      <input type="checkbox" ng-model="selected[i]" ng-false-value="" />{{i}}

    Marcar Todos

    Desmarcar Todos

{{selected|json}}

A utilização de código jQuery em conjunto com Angular é geralmente não recomendada porque a execução ocorre ao largo do ciclo digest do Angular, o que pode quebrar o 2-way binding.
Comment: Concordo OnoSendai! Sempre melhor utilizar apenas Angular (ou outro framework), assim como quando se utiliza jQuery, procurar usar ao máximo todos os recursos e não utilizar JS puro.

Problema ao marcar todos os checkbox


How to pass Navigator function as a parameter in Dart?

Question: I have a custom widget which represents a button and this widget is in a separated folder called "Widgets" inside the "lib" folder, and that is the button widget file
import 'package:flutter/material.dart';

Widget buttonWidget(String text, Function action) {
  return ElevatedButton(
    onPressed: () => action,
    child: Text(text, style: const TextStyle(fontSize: 20),
  );
}

now in the main.dart file I want the buttonWidget to use the Navigator.pushNamed function, so I called the buttonWidget like the
buttonWidget("Navigate", Navigator.pushNamed(context, '/screenTwo')),

but the buttonWidget call gives me this error
The argument type 'Future<Object?>' can't be assigned to the parameter type 'Function'.

Answer: You need to create an anonymous function surrounding the call, just as you would if you were directly passing it to the onPressed parameter.
buttonWidget("Navigate", () => Navigator.pushNamed(context, '/screenTwo')),

or
buttonWidget("Navigate", () {
  Navigator.pushNamed(context, '/screenTwo');
}),


Burr Distribution Derivation from Conditional Inverse Weibull and Generalized Gamma Distributions

Question: A Weibull distribution, with shape parameter alpha and

Am I supposed to find the MGFs of both distributions and then use the iterated rule/smoothing technique/law of total expectation followed by uniqueness theorem to find the PDF of the Burr distribution?  Or am I supposed to use the definition of conditional distribution to find the joint distribution and then integrate over the support of $\beta$ in order to get the PDF?  I tried the latter, but of course I ended up with an integral that seems impossible to integrate.  How would you go about solving this?  Here's what I have so far:
$$f_{W^{-1}}(w)=\frac{\lambda w^{-\lambda-1}e^{-(\frac{1}{w\beta})^\lambda}}{\beta^\lambda}$$ on $0<w<\infty$.
This implies that $$f_x(x)=\frac{\lambda \tau x^{-\lambda -1}}{\Gamma(\alpha)}\int_{0}^{\infty}\frac{(\frac{ \beta }{\theta})^\alpha e^{-(\frac{1}{x\beta})^\alpha}e^{(\frac{\beta}{\theta})^\tau}}{\beta^{\lambda+1}}d\beta$$
But how on Earth do I integrate that?  Surely there's a better way, but I have on idea what it is.
Answer: It was a mistake on your Professor's part, the $\lambda$ parameter of the Inverse Weibull should be $\tau$ which would link the Inverse Weibull and the Generalized Gamma which should have $e^{-(\frac{\beta}{\theta})}$. If you have the course textbook 'Loss Models from Data to Decisions' you can find this problem on page 65. $$$$
But if you don't, once you make the changes above you will be left with a function of $w,\beta,\tau,\alpha,\text{ and }\theta$; you would then integrate out the $\beta$ using U Substitution leaving you with a function of $w,\tau,\alpha,\text{ and }\theta$ which is the Inverse Burr Distribution PDF $f(x| \tau,\alpha,\beta)$.
Comment: I knew it.  What he gave us makes no sense at all.  He makes mistakes like this all the time and it really bugs me.  Glad you see it too.
Comment: You may also want to look up the Inverse Weibull in the back. For some reason the Univariate Transformation doesn't lead to what the book has...
Comment: I noticed that too!  They're apparently using the reciprocal of one of the parameters $\theta$.  There're just so many things wrong with this problem.


Polynomial decomposition by Kronecker's method: usefulness of moduli

Question: In B. L. van der Waerden's Algebra it's said that one can considerably simplify usage of Kronecker's method for polynomials over the ring of integers by factoring the given polynomial modulo 2 and possibly modulo 3, so that one gets an idea what degrees the possible factor polynomials might have, and to what residue classes the coefficients modulo 2 and 3 might belong.
I don't have a clue how that information might help. Can someone explain that? I would be really grateful for a little example too, that would help me for good.
Moreover, I might be wrong in understanding what is a polynomial modulo ring element. Is that just polynomial with coefficients modulo that element?
Comment: See the [Wikipedia article on Polynomial Factorization](https://en.wikipedia.org/wiki/Factorization_of_polynomials) for entry points into modern literature.
Answer: Suppose that $p(x)$, with integer or rational coefficients, factors over the rationals into $p_1(x)p_2(x)...p_k(x)$. Then, modulo $q$, it must factor in at least $k$ factors (not necessarily of the same degree).
So, the idea is that factorizations modulo $q$ gives you a bound from below on the number of irreducible factors over the rationals. In the extreme case that you find that modulo $q$ the polynomial is irreducible of the same degree, then the polynomial is forced to be irreducible over the rationals.
Comment: Beware that the claim holds only for *monic* polynomials, e.g. $\, (30x+1)^n\,$ has $n$ prime factors in $\,\Bbb Z[x]\,$ but none $\bmod 2,3,5\ \ \ $
Comment: @BillDubuque $0$ is a lower bound of $n$. For the implication about irreducibly one doesn't need to restrict to monic polynomials. It is enough to remember the degree of the original polynomial.
Comment: Your claim implies $\,(30x+1)^n\,$ has at least $n$ factors $\!\bmod q$. That is false for $\,n\ge 1\,$ and $\,q = 2,3,5.\ \  $
Comment: @BillDubuque There is no claim as to the nature of those factors. $(30x+1)^n$ modulo $2$ is $1\cdot 1\cdot ...\cdot 1$. One only needs to keep track of the degrees.
Comment: Glad to see you edited it. Note also that a factor might even vanish $(\equiv 0)$ if the polynomial is not primitive.


Using categorical encoding across multiple dataframes in python

Question: I have a DataFrame X_Train with two categorical columns and a numerical column, for example:

A
B
N

'a1'
'b1'
0.5

'a1'
'b2'
-0.8

'a2'
'b2'
0.1

'a2'
'b3'
-0.2

'a3'
'b4'
0.4

Before sending this into a sklearn's linear regression, I change it into a sparse matrix. To do that, I need to change the categorical data into numerical indexes like so:
X_Train['acat'] = pd.factorize(X_Train['A'])[0]
X_Train['bcat'] = pd.factorize(X_Train['B'])[0]

Then I change it into a sparse matrix:
X_Train_Sparse = scipy.sparse.coo_matrix((X_Train.N, (X_Train.acat, X_Train.bcat)))

I have another similar DataFrame, X_Test, for example:

A
B
N

'a4'
'b3'
0.6

'a5'
'b5'
-0.1

'a6'
'b2'
-0.1

'a6'
'b1'
-0.5

'a6'
'b3'
0.3

I also need to change this to a sparse matrix. How do I use the same bcat categorization from X_Train for X_Test so that the linear regression treats 'b1' in X_Train as the same variable as 'b1' in X_Test? Implicit in this is that, if there is any B value in X_Test that is not in X_Train, this B value should be dropped because there was no learning from this B value so no prediction can be made from it.
Comment: You have multiple questions in one question, better split those up and create a new question for each subquestion, e.g. the sparse matrix part.
Comment: Thanks! but the sparse matrix part was not a question. I only gave it as an explanation for why I need the encoding.
Answer: You have to apply the categorical encoding in advance of splitting:
Sample:
import pandas as pd
df = pd.DataFrame({'A': {0: "'a1'",  1: "'a1'",  2: "'a2'",  3: "'a2'",  4: "'a3'",  5: "'a4'",  6: "'a5'",  7: "'a6'",  8: "'a6'",  9: "'a6'"}, 'B': {0: "'b1'",  1: "'b2'",  2: "'b2'",  3: "'b3'",  4: "'b4'",  5: "'b3'",  6: "'b5'",  7: "'b2'",  8: "'b1'",  9: "'b3'"}, 'N': {0: 0.5,  1: -0.8,  2: 0.1,  3: -0.2,  4: 0.4,  5: 0.6,  6: -0.1,  7: -0.1,  8: -0.5,  9: 0.3}})

Code:
# Encode categories
df['B'] = pd.Categorical(df['B'])
# Split data into train/test
df_train, df_test = df.iloc[:5], df.iloc[5:]

Result:
df_train['B'].cat.codes

Out[58]:
0    0
1    1
2    1
3    2
4    3
dtype: int8

df_test['B'].cat.codes

Out[59]:
5    2
6    4
7    1
8    0
9    2
dtype: int8

Comment: Thanks! In my application, the train and test are already separate. To implement your solution, I can merge them, generate the categorical, and split them again. I will try that.
Comment: @JafarSadeq, let me know if it worked and if it answered feel free to upvote and accept the answer, this will help future readers and give me a few points. Happy Coding!
Comment: Sorry, I'm still a noob. Yes it definitely solved it. I accepted the answer but my votes don't count yet. Thanks again!


Interface between Controller and Service Layer

Question: I am a newbie to .Net MVC and my question today is regarding the MVC pattern.
In our application we have a Service Layer which talks with the DB.
The Controller is Currently talking with the Service layer to get the values from the DB.
Our new Manager requires this service layer interaction from the Models and not from the Controller.
He does say that this architecture is to achieve a thin Controller. We are now starting to port the service layer interaction from controller to models.
And here comes my question. Apart from having a thin Controller, is there any other benefits from enforcing this pattern.
I would like to know the advantages and disadvantages of both pattern.
Some links would also be helpful
Comment: There are really 4 things; your `Controllers`, your `Views`, your `Model` and your `ViewModels`. Your `Model` is everything behind your `Controllers` (services, helpers, repository, database). Your `ViewModels` are what you pass from your `Controllers` to your `Views` and back. In a sense, your services are inherently your `Model`. Call services from your `Controllers`.
Comment: @Shanky, NEVER call Services from ViewModels!
Comment: To clarify, he is asking you to enforce service calls within the 'view' models?
Comment: Thin controllers are a great idea; call services from your controllers and have very little other logic in them. You do not want to be calling services from your model.
Comment: @ ChirsBint. Is that MVC pattern that requires service calls to be made from Models. Or Is it just an option to use either Model or Controller for Service Calls. Can you please elaborate your comment.
Comment: Your controller should call the service. The models represent your data.
Comment: @ Sam Leach. I'm talking about the ViewModels. We are now shifting all the service calls from Controller to View Models. Does that have any advantage. If not so,Can you describe the disadvantages of the same.
Comment: @SamLeach, Thanks but why. Please put me some links to prove this to my manager.
Comment: @Shanky, see my answer. Google 'MVC pattern' for evidence. I think there is some confusion between you, your manager and the mvc pattern. :)
Comment: @SamLeach, OfCourse i agree. :). I think he might not mean the View models. My wild guess is he needs an extra layer between the Controller and Service.
Answer:
Why you shouldn't call services from your ViewModels:

ViewModels are supposed to be classes that contain some data that is interchanged between the View and the Controller. They should not perform any action or retrieve further data. They are dumb models, they don't do anything expect transport data.
What is a View Model
If you are having trouble understanding what a View Model is and what it isn't, think of it like a subset of your model. It only contains data that you need to display on a given view at a given time.
Answer: There are 3 types of Models - View Model, Domain Model and Data Model. Check here.
If you are talking about View Models then its a bad idea. There are ways to achieve a thin controller, but ViewModel never should interect with services. If its possible a Controller Action should only invoke a service and throw the result to View. Like this:
[HttpGet]
public ActionResult GetAnimals(int id)
{
    var viewModel = new AnimalsService(id).GetViewModel();
    return View(viewModel);
}

But in reality many times you can't do that for some obvious reasons. There are few things you can do though. Like don't validate models in controller, you can do that in service layer. Don't hesitate to create more services for different jobs, like pagination, context related logic or some third party api invocation. Create helper or utility classes for repititive codes. Also I think its ok to write fat services.
Comment: Also service models often operate on domain model, that means you need to at least map domain model to view model in controller. I tried to move mapping into service, but after some thinking I realized its bad idea, as services speak in their own language(domain model) thus should not use VM. To remediate your issues you can create facade, as additional layer just before controller, if someone still has this problem in 2019 :) Is this worth the effort? If controller is very big, I think yes.