Is it possible to favorite/bookmark Search API results using Flags or similar?

Question: We are using the Flag module to create favorites of Nodes and this works great for allowing users to bookmark specific Nodes.
The client also wants to bookmark search results from the Search API Views page.
Ideally, this would be with a Flag also but I don't see how this would be possible as the search result is simply a URL and not en entity.
How could we allow users to bookmark a URL/search-result? It doesn't have to be a Flag, if there is another way.
EDIT:
Found this module that works perfectly for our needs:
https://www.drupal.org/project/bookmarks
Comment: To clarify: "bookmark" does not mean "a web browser bookmark" in this question. Is that correct?
Comment: That is correct. By "bookmark", I mean simply to create a Drupal flag-type "bookmark" that is linked to the user account so that we can display "bookmarked" URLs from this Drupal website along site the "Flagged" nodes on the user's "Favorites" page.
Comment: Found a solution.
Answer: Found a module that works perfectly for our needs:
https://www.drupal.org/project/bookmarks


What does it mean by 'Gaussian distribution at vector x'?

Question:
Write a MATLAB function that computes the value of the Gaussian
  distribution N(m, S), at a given vector x.

What does it mean by 'Gaussian distribution at vector x'?
What does the question want actually?
Comment: The Gaussian distribution is quite literally a function. In the case of a vector random variable, it's a function of a vector. When you evaluate a function at some particular value of its argument, $x$ (here a vector), you evaluate that function "at a vector, $x$"
Answer: In this case a vector is an object in MATLAB, an array of numbers. What it says is that you can apply such function in MATLAB to all the indices of such object and evaluate Gaussian distribution function on them. So for each of the elements in your vector x it returns their probability densities or cumulative probabilities depending on what exactly is the function you describe (it is not clear from the context). It does not transform x to vector of normally distributed values of the same size.
Comment: still not clear to me.
Comment: That means, I will obtain a new vector of the same size of input vector whose elements are normally distributed.


How do i stop player from continuesly falling when i collide with top block?

Question: I am using Windows Form Application and making a simple 2d platformer, with a picturebox that is the player and an array list of pictureboxes that are the blocks.
When i collide with Blocks[i].Top the "player" keeps falling into the top blocks. I think it is becuase
<code>{player.Top += 3;}
</code>
is always happening.
How do i tell the player to stop falling when i collide with the top blocks?
<code>private void timer1_Tick(object sender, EventArgs e)

    {

        for (int i = 0; i < blocks.Count; i++)
        {
            Rectangle playerRect = player.ClientRectangle;
            playerRect.X = player.Location.X;
            playerRect.Y = player.Location.Y;
            Rectangle blockRect = blocks[i].ClientRectangle;
            blockRect.X = blocks[i].Location.X;
            blockRect.Y = blocks[i].Location.Y;
            Rectangle Intersection = Rectangle.Intersect(playerRect, blockRect);

            if (jump == true)
            {
                //hur snabbt spelaren faller
                player.Top -= force;
                force -= 1;
            }

            if (player.Top + player.Height >= screen.Height)
            {
                player.Top = screen.Height - player.Height;
                if (jump == true)
                {
                    player.Image = Image.FromFile("gubbe_still.png");

                }
                jump = false;
            }
            else
            {
                player.Top += 3;
            }

            //sid kollision
            if (player.Right > blocks[i].Left &&
                player.Left < blocks[i].Right - player.Width / 2 &&
                player.Bottom > blocks[i].Top)
            {
                right = false;
            }

            //sid kollision
            if (player.Left < blocks[i].Right &&
                player.Right > blocks[i].Left + player.Width / 2 &&
                player.Bottom > blocks[i].Top)
            {
                left = false;
            }

            // top kollision
            if (player.Right - 5 > blocks[i].Left &&
                player.Right + 5 < blocks[i].Left + blocks[i].Width + player.Width &&
                player.Top + player.Height >= blocks[i].Top &&
                player.Top < blocks[i].Top)

            {
                jump = false;
                force = 0;
                player.Top = blocks[i].Location.Y - player.Height;

            }
}
</code>
Answer: You have some collision detection issues
<code>// top kollision
if (player.Right - 5 > blocks[i].Left &&
      player.Right + 5 < blocks[i].Left + blocks[i].Width + player.Width &&
      player.Top + player.Height >= blocks[i].Top &&
      player.Top < blocks[i].Top)
</code>
The first check (player.Right - 5 > blocks[i].Left) will fail if the player is standing off the left side of the block at all. You want something like:
<code>// top kollision
if ((player.Left > blocks[i].Left &&
      player.Left < blocks[i].Right) ||
      (player.Right < blocks[i].Left &&
      player.Right > blocks[i].Left) &&
      player.Top + player.Height >= blocks[i].Top &&
      player.Top < blocks[i].Top)
</code>


Navigate Shell command not working when the path includes an hash

Question: I'm having problem using the Navigate Shell command when the path include an # sign.
; this will create 2 folders at the root of your C: drive
myPath1 := "C:\delete_me\"
myPath2 := "C:\delete#me\"
if !FileExist(myPath1)
    FileCreateDir, %myPath1%
if !FileExist(myPath2)
    FileCreateDir, %myPath2%
; make an Explorer active and press Alt-1 and Alt-2
return

!1::
strWinId := WinExist("A")
TrayTip, %myPath1%, %strWinId%
For pExp in ComObjCreate("Shell.Application").Windows
    if (pExp.hwnd = strWinId)
        try pExp.Navigate(myPath1)
return

!2::
strWinId := WinExist("A")
TrayTip, %myPath2%, %strWinId%
For pExp in ComObjCreate("Shell.Application").Windows
    if (pExp.hwnd = strWinId)
        try pExp.Navigate(myPath2)
return

Alt-1 works well. But, with Alt-2, the Navigate command returns "file:///C:/delete#me/ » not found.".
If there is no "/" after the "#" (eg myPath := "C:\delete#me"), it works. But this cannot be a solution because the destination path can be deeper in a subfolder (eg. "C:\delete#me\xyz").
I tried to encode the "#", replacing it with "%23", without success. Found nothing on the web or MSDN about that. Any idea?
[keywords: haskmark, hashtag, number sign or pound]
Comment: You've tagged this autohotkey.  Why do you need a com object to navigate windows explorer?
Comment: This is used in [FoldersPopup](http://code.jeanlalonde.ca/folderspopup/), a "favorite folders" app, to navigate Windows Explorer to a selected favorite. Maybe you know AutoHotkey as a macro language. This can also be a pretty powerful portable app dev tool.
Comment: I just saw in your profile that you know AHK pretty well already :-) I'm using the Shell command to make sure the app works on any locale. Relying on the interface to change folders is risky on Windows int'l implementations.
Comment: for me, it opens up my webbrowser...
Comment: Hello Joe. Only with Alt-2 or with both paths?
Comment: Strange enough... Just found that if I press Alt-1 or Alt-2 when the active browser is Internet Explorer, both folders are opened correctly in a Windows Explorer.
Comment: It looks like Explorer assumes (at least in some cases) that `#` is a [fragment identifier](http://en.wikipedia.org/wiki/Fragment_identifier) and thus tries to open it in the default browser. It seems odd though that it would treat it as a file path only if there is no (back)slash after it.
Comment: I wonder if this happens in other version than Win7?
Comment: I tried to split the command in two steps. For example to navigate to "C:\delete#me\sub": 1) navigate the first part of the path ""C:\delete#me" (stopping before the "\"), and 2) using the relative URL addressing technique "./sub". But Navigate does not support relative addresses :-(
Comment: This is working for me .. it's faster than the SendInput solution.
https://stackoverflow.com/a/44531438/3503851
Answer: I have what looks to be a working solution for this, which I've also posted here:
4 options to change the current folder in Windows Explorer - Page 3 - AutoHotkey Community
https://autohotkey.com/boards/viewtopic.php?f=5&t=526&p=153676#p153676
;links:
;Explorer Windows Manipulations - Page 5 - Scripts and Functions - AutoHotkey Community
;https://autohotkey.com/board/topic/19039-explorer-windows-manipulations/page-5#entry297581
;Navigate2 Method (IWebBrowser2)
;https://msdn.microsoft.com/en-us/library/aa752134(v=vs.85).aspx
;4 options to change the current folder in Windows Explorer - AutoHotkey Community
;https://autohotkey.com/boards/viewtopic.php?f=5&t=526
;windows - Navigate Shell command not working when the path includes an hash - Stack Overflow
;https://stackoverflow.com/questions/22868546/navigate-shell-command-not-working-when-the-path-includes-an-hash

;an AutoHotkey v1.1 script
;note: will create folder: %A_Desktop%\abc#def\abc#def
;q:: ;explorer - navigate to folder (tested on Windows 7)
WinGet, hWnd, ID, A
WinGetClass, vWinClass, % "ahk_id " hWnd
if !(vWinClass = "CabinetWClass") && !(vWinClass = "ExploreWClass")
    return

vDir = %A_Desktop%\abc#def\abc#def
;vDir = %A_Desktop%\abc def\abc def
if !FileExist(vDir)
    FileCreateDir, % vDir

DllCall("shell32\SHParseDisplayName", WStr,vDir, Ptr,0, PtrP,vPIDL, UInt,0, Ptr,0)
for oWin in ComObjCreate("Shell.Application").Windows
    if (oWin.HWND = hWnd)
    {
        if !InStr(vDir, "#")
            oWin.Navigate(vDir)
        else
        {
            VarSetCapacity(SAFEARRAY, A_PtrSize=8?32:24, 0)
            NumPut(1, SAFEARRAY, 0, "UShort")
            NumPut(1, SAFEARRAY, 4, "UShort")
            NumPut(vPIDL, SAFEARRAY, A_PtrSize=8?16:12, "Ptr")
            NumPut(DllCall("shell32\ILGetSize", Ptr,vPIDL, UInt), SAFEARRAY, A_PtrSize=8?24:16, "Int")
            oWin.Navigate2(ComObject(0x2011,&SAFEARRAY))
            DllCall("shell32\ILFree", Ptr,vPIDL)
        }
        break
    }
return

Comment: This works efficiently :) .. This should be the answer.
Tested on Windows 10 build 18363
Answer: Unfortunately, there does not seem to be a solution to this. Shell.Application Navigate command fails if the path includes a hash (# as in C:\C#Projects).
Using AutoHotkey, the workaround would be to rely on the "second best" approach as identified by the tests in this thread: http://ahkscript.org/boards/viewtopic.php?f=5&t=526.
run, Explorer.exe
Sleep, 500
strFolder := A_ScriptDir
Send, {F4}{Esc}
Sleep, 500
ControlSetText, Edit1, C:\delete#me, A
ControlSend, Edit1, {Enter}, A

Comment: In the particular case where you're opening a new window, you can just `run C:\delete#me`.
Comment: Yes, you are right. This scenario is when you want to "navigate" the current Explorer to another folder.
Comment: For those interested, I invite you to jump in this thread where Lexikos is exploring various options: http://ahkscript.org/boards/viewtopic.php?f=5&t=526&p=17223#p25274
Answer: If you want to open a new window, there's no need for COM or unreliable workarounds: just run the folder.
Run C:\delete#me

If you want to open the path in an existing window which is already active, the simplest and most effective workaround is this:
SendInput {F4}{Esc}{Raw}C:\delete#me`n

So in the context of your script, you could use the following function to work around the # when it is present:
Navigate(pExp, myPath2)

;...

Navigate(Exp, Path)
{
    if RegExMatch(Path, "#.*\\")
        SendInput {F4}{Esc}{Raw}%Path%`n
    else
        Exp.Navigate(Path)
}

Comment: Yes. Your code is better that the one in my previous answer. No need for ControlSetText if you use the Raw option.
Comment: But when there is no #, do you agree that using the COM is better to navigate the current Explorer? This should be faster and probably more reliable than sending keystrokes to the front end.
Comment: Like you say, calling Navigate() is faster and more reliable, if it works at all. Activating the address bar (F4) also causes a bit of "visual interference".
Answer: When I saw that Navigate couldn't handle hash, I was shocked,
but sure enough I replicated the error.
I thought I'd try the short form path just in case. It works!
if vDir contains #
Loop, %vDir%, 2, 0 ;(0/1/2=files/both/folders, 0/1=recurse no/yes)
vDir := A_LoopFileShortPath

Comment: At first sight, I liked your solution. Unfortunately, it will not work when the # is part of the first 6 characters of the folder name. In this case, the short form name will still include the # and cause the bug.

    Example 1 is OK
    1 = C:\abc-xyz-very long folder # name\abc
    2 = C:\ABC-XY~1\abc
//
    Example 2 does NOT work:
    1 = C:\abc#xyz-very long folder name\abc
    2 = C:\ABC#XY~1\abc
Comment: Thank you, I couldn't remember from DOS days whether short forms were alphanumeric and tilde only or not.
Comment: Something I said on the other forum: perhaps it's possible to assign a special folder ID to the folder with the hash, and then put that into Navigate().
Comment: e.g. a special ID similar to 'shell:Desktop'.
Answer:
The following approach doesn't require a visible address bar, or SendInput,
also the previous navigation history is maintained.
In the worst-case scenario of a hash in the short-form path of the dir above the target dir,
a go-between folder is used which is navigated to.
A link is created there, invoked, and deleted.
Below, the workaround code is indented, to separate it from the standard code.
A hotkey of ctrl+q, when an Explorer window is active, launches the script.

-
^q:: ;explorer - navigate to directory (use go-between dir if short-form path of dir above target contains #)
WinGet, hWnd, ID, A
WinGetClass, vWinClass, ahk_id %hWnd%
if vWinClass not in CabinetWClass,ExploreWClass
Return

vDir2 = %A_Desktop%\Go-Between ;go-between dir
vDir3 = C:\delete#me ;target dir

if (SubStr(vDir3, 1-1) = "\")
vDir3 := SubStr(vDir3, 1, -1)
if !InStr(FileExist(vDir3), "D")
Return

    vPathLnk := ""

    if vDir3 contains #
    Loop, %vDir3%, 2, 0 ;(0/1/2=files/both/folders, 0/1=recurse no/yes)
    vDir3 := A_LoopFileShortPath

    ;vDir4 is the short-form path of the dir above the target
    ;paths of problem target dirs are of the form: *#*\*
    ;where there is at least one hash with a backslash to its right
    SplitPath, vDir3, , vDir4
    if vDir4 contains #
    {
    if !InStr(FileExist(vDir2), "D")
    FileCreateDir, %vDir2%
    if !InStr(FileExist(vDir2), "D")
    {
    MsgBox error`, go-between dir not found:`r`n%vDir2%
    Return
    }
    vNameLnk = Go-Between.lnk
    vPathLnk = %vDir2%\%vNameLnk%
    FileCreateShortcut, %vDir3%, %vPathLnk%
    }

for oWin in ComObjCreate("Shell.Application").Windows
if (hWnd = oWin.Hwnd)
{
vDir1 := oWin.Document.Folder.Self.Path
if (vDir1 = vDir3)
break

    if vDir3 contains #
    {
    if !(vDir1 = vDir2)
    oWin.Navigate(vDir2)
    while !(oWin.ReadyState = 4)
    Sleep 10

    oItem := oWin.Document.Folder.Items.Item(vNameLnk)
    oItem.InvokeVerbEx("open")
    break
    }

oWin.Navigate(vDir3)
break
}

oWin := ""

    if !(vPathLnk = "")
    FileRecycle, %vPathLnk% ;send to recycle bin
    ;if !(vPathLnk = "")
    ;FileDelete, %vPathLnk% ;delete
Return


What would happen if a team would let the draft timer run out?

Question: Watching the NHL draft and teams are 'on the clock'... They only have a few minutes to announce their pick.
But what would happen if a team, by inadvertance, let that timer run out?
Answer: If a team fails to get their pick in before the clock expires, the next team in the draft order is allowed to pick instead. Once that next pick is made, the original team can then use their "missed" pick.
It doesn't happen very often, but it does happen. The most common scenario for a "missed pick" is if the team on the clock is planning to trade picks with another team but the negotiations break down at the last minute, leaving them scrambling to make a move.


prove that $(n \Bbb Z /k \Bbb Z)/(m \Bbb Z /k \Bbb Z) \cong n\Bbb Z / m \Bbb Z$

Question: I need to prove thae following -
given $n,m,k \in \Bbb N$ such that $n|m , m|k$
prove that $(n \Bbb Z /k \Bbb Z)/(m \Bbb Z /k \Bbb Z) \cong \Bbb Z / \frac  mn \Bbb Z$
What I tried and what missing - I know that $k \Bbb Z , m \Bbb Z$ are normal in $n \Bbb Z$ i don't know how to prove it.
I also found that using the 3rd Isomorphism theorm -
$(n \Bbb Z /k \Bbb Z)/(m \Bbb Z /k \Bbb Z) \cong n \Bbb Z / m \Bbb Z$
and this is already close .. now im stuck .
any help will be appreciated
Answer: Hint: for $n=1$ we have the isomorphism $(\mathbb{Z}/k\mathbb{Z})/(m\mathbb{Z}/k\mathbb{Z})\simeq \mathbb{Z}/m\mathbb{Z}$ via $(l+k\mathbb{Z})+m\mathbb{Z}\mapsto l+m\mathbb{Z}$. Now generalize this map to $n\ge 2$.
Answer: You can consider the following homomorphism:
$$ \phi:\frac{<n>}{<k>} \longrightarrow \frac{<n>}{<m>} $$ which send
$$ np+<k> \longmapsto np+<m> $$ where $p\in\mathbb{Z}$.
This a homomorphism of groups, and in particular $\phi$ is surjective. Now if you show that $ker\phi=\frac{<m>}{<k>}$ by the fundamental theorem of isomorphism you have finished.
But now $$np+<m>=<m>;$$ so is zero in the quotient; iff $np \in <m> $ iff $  p=ml+<k>$ iff $p\in \frac{<m>}{<n>}$.
Intact if $p=ml+<k>$ then $np=nml+n<k>$; obviously $nml\in<m>$ and $<k>$ is a subgroup of $<m>$ since $m|k$.


Somar Campo Time MySql

Question: Caros, possuo uma tabela com uma coluna do tipo TIME, a qual armazena o horario trabalhado no dia, e estou tentando fazer a soma destes horarios ao final de um mês, porem sem sucesso.
Usei as seguintes query:
Query 1:
SELECT TIME_FORMAT((SELECT sum(TOTAL)
FROM horario where PRESTADOR='NOME'
and MONTH(data) = 1 and YEAR(data) = 2015), '%H:%i:%s') as total;

Resultado "null";
Query 2:
SELECT SEC_TO_TIME( SUM( TIME_TO_SEC(TOTAL))) AS total_horas
FROM horario where PRESTADOR='NOME' and MONTH(data) = 1 and YEAR(data) = 2015;

Resultado "6.14:24:00";
Query 3:
SELECT sum(TOTAL)
FROM horario where PRESTADOR='NOME'
and MONTH(data) = 1 and YEAR(data) = 2015;

Resultado: "1526400";
O resultado correto seria 158:24:00
Comment: Ola, acabei de resolver o problema, mas no banco são armazenadas horas como exemplo "08:48:25". Usei o time_format para resolver o problema, deixando a query assim :"SELECT time_format(
SEC_TO_TIME( SUM( TIME_TO_SEC( TOTAL
 ) ) ),'%H:%i:%s') AS total_horas FROM horario where PRESTADOR='NOME'
and MONTH(data) = 1 and YEAR(data) = 2015;"
Comment: Depois não se esqueça de responder a sua própria pergunta e marca-la como certa.
Comment: O que exatamente você está armazenando no banco? Pode mostrar um trecho dos dados da sua base?
Comment: Mas você armazena horários pontuais ou um intervalo por dia? Pois se você for fazer a soma dos segundos vai chegar a um número diferente do total trabalhado.
Answer: Caros, obrigado pela ajuda,consegui resolver o problema usando o time_format deixando a query assim:
SELECT time_format( SEC_TO_TIME( SUM( TIME_TO_SEC( TOTAL ) ) ),'%H:%i:%s')
AS total_horas FROM horario where PRESTADOR='NOME' and MONTH(data) = 1 and YEAR(data) = 2015;

Comment: Nossa senhora, ajudariam muito desenvolvedores  simplificar isso ai, acredito que muitos que usam mysql algum momento precisem somar horas.

Somar Campo Time MySql


Solve $(y^2+2x^2y)dx+(2x^3-xy)dy=0$

Question: Solve $(y^2+2x^2y)dx+(2x^3-xy)dy=0$
My attempt
$Mdx + Ndy$ form
$M = (y^2+2x^2y)$, $N =(2x^3-xy) , M_y=2y+2x^2, N_x=6x^2-y$
I am not getting in of standard forms here...
Another attempt:
$2x^2 d(xy)+y(ydx-xdy)=0$,
$2d(xy)=yd(y/x)$ Any clue pls???
Comment: Have you heard about integrating factors?
Comment: Integrating factor on the form $x^\alpha y^\beta$ was possible too. One obtain $\alpha=-5/2$ and $\beta=-1/2$. It was not very difficult. Moreover, without guessing a particular form for the integrating factor, it is more tiresome but  the general method to find an integrating factor works well.
Comment: it was with more fractions staff. He assumes $x^{\alpha} y^{\beta}$ as integrating factor. But it goes messy. I was thinking of alternate simple method
Answer: $$y(y+2x^2)dx+x(2x^2-y)dy=0$$
$$y(y+2x^2)(2xdx)+2x^2(2x^2-y)dy=0$$
An obvious change of variable appears : $\quad t=x^2$
$dt=2xdx \quad\implies\quad y(y+2t)dt+2t(2t-y)dy=0$
$$\frac{dy}{dt}=\frac{y}{2t}\frac{y+2t}{y-2t}$$
This is an ODE of the homogeneous kind. The usual change of function is : $\quad y=tu$
$\frac{dy}{dt}=u+t\frac{du}{dt} \quad\implies\quad u+t\frac{du}{dt}=\frac{tu}{2t}\frac{tu+2t}{tu-2t}=\frac{u}{2}\frac{u+2}{u-2}$
$$t\frac{du}{dt}=\frac{u}{2}\frac{u+2}{u-2}-u$$
This is a separable ODE. I suppose that you can take it from here.
HINT:
First, solve for $t(u)$, not for $u(t)$.
Second, $\quad \begin{cases} t=x^2\\ u=\frac{y}{x^2} \end{cases}\quad$ to come to the relationship between $y$ and $x$.
Comment: good way, liked ur substitution.
Comment: A typo at the end was corrected.
Comment: Job well done, haven't seen you for quite a while...
Answer: Here is another way
$$y(y+2x^2)dx+x(2x^2-y)dy=0$$
Substitute $y=tx$
$$t(t+2x)=(t-2x)y'$$
Note that $y'=t'x+t$
$$t(t+2x)=(t-2x)(t'x+t)$$
After some simplifications you get:
$$t'(t-2x)=4t$$
Consider now $x'=\frac {dx}{dt}$
$$x'+\frac x {2t}=\frac 1 4$$
Which is easy to solve.....
Answer: I thought it might be useful to demonstrate Jacquelin's suggestion from the comments. We're given the ODE
$$M(x,y)\,\mathrm dx+N(x,y)\,\mathrm dy=0$$
Distributing an integrating factor $\mu(x,y)$ across both sides we get
$$\mu M\,\mathrm dx+\mu N\,\mathrm dy=0$$
To meet the conditions of exactness, we require
$$(\mu M)_y=(\mu N)_x\implies\mu_y M+\mu M_y=\mu_xN+\mu N_x$$
$$\implies \mu_y(y^2+2x^2y)-\mu_x(2x^3-xy)=\mu(4x^2-3y)$$
Let's attempt the traditional guess of $\mu(x,y)=x^ay^b$. Substituting into the PDE above, we have
$$\begin{align*}
bx^ay^{b-1}(y^2+2x^2y)-ax^{a-1}y^b(2x^3-xy)&=x^ay^b(4x^2-3y)\\[1ex]
(a+b)x^ay^{b+1}-(2a-2b)x^{a+2}y^b&=-3x^ay^{b+1}+4x^{a+2}y^b
\end{align*}$$
$$\implies\begin{cases}a+b=-3\\2a-2b=-4\end{cases}\implies a=-\frac52,b=-\frac12$$
(You can verify that $(\mu M)_y=(\mu N)_x$.) Now we seek a solution $\Psi(x,y)=C$ for which $\Psi_x=\mu M$ and $\Psi_y=\mu N$. We have
$$\Psi_x=x^{-5/2}y^{3/2}+2x^{-1/2}y^{1/2}\implies \Psi=-\frac23x^{-3/2}y^{3/2}+4x^{1/2}y^{1/2}+f(y)$$
$$\Psi_y=2x^{1/2}y^{-1/2}-x^{-3/2}y^{1/2}=-x^{-3/2}y^{1/2}+2x^{1/2}y^{-1/2}+\frac{\mathrm df}{\mathrm dy}$$
$$\implies\frac{\mathrm df}{\mathrm dy}=0\implies f(y)=C$$
where $C$ is an arbitrary constant. We thus arrive at a solution
$$\Psi(x,y)=\frac23x^{-3/2}y^{1/2}\left(6x^2-y\right)=C$$
Answer: $$(y^2+2x^2y)dx+(2x^3-xy)dy=0....(i)\\
\implies y^2dx+2x^2ydx+2x^3dy-xydy=0\\
\implies y(ydx-xdy)+x^2(2ydx+2xdy)=0$$
Which is the form of :
$$x^ay^b(mydx+nxdy)+x^{a'}y^{b'}(m'ydx+n'xdy)=0$$
So, comparing both equations we get:
$a=0, b=1, m=1, n=-1, a'=2, b'=0, m'=2, n'=2$
Now,
$$\frac{a+h+1}{m}=\frac{b+k+1}{n}\\
\implies \frac{h+1}{1}=\frac{1+k+1}{-1}\\
\implies h+k+3=0.....(ii)$$
and $$\frac{a'+h+1}{m'}=\frac{b'+k+1}{n'}$$
$$\implies \frac{2+h+1}{2}=\frac{k+1}{2}\\
\implies h-k+2=0.....(iii)$$
Solving equation (ii) & (iii) we get, $h=-\frac{5}{2}, k=-\frac{1}{2}.$
So,I.F.= $x^{-\frac{5}{2}}y^{-\frac{1}{2}}$
Multiplying equation (i) with the I.F. we get,
$$(x^{-\frac{5}{2}}y^\frac{3}{2}dx+2x^{-\frac{1}{2}}y^\frac{1}{2})dx+(2x^\frac{1}{2}y^{-\frac{1}{2}}-x^{-\frac{3}{2}}y^\frac{1}{2})dy=0$$
Therefore the solution is:
$$\int{Mdx}+\int{(\text{terms of N not containing x})dy}=c\\
\implies \int{x^{-\frac{5}{2}}y^\frac{3}{2}dx}+2\int{x^{-\frac{1}{2}}y^\frac{1}{2}dx}=c\\
\implies -\frac{2}{3}x^{-\frac{3}{2}}y^\frac{3}{2}+4(xy)^\frac{1}{2}=c\\
\implies 4(xy)^\frac{1}{2}-\frac{2}{3}\left(\frac{y}{x}\right)^\frac{3}{2}=c$$

Solve $(y^2+2x^2y)dx+(2x^3-xy)dy=0$


Drupal Form Button + "Are you sure"-Button

Question: I am trying to add an own JS function to a Drupal Core Form - think Config, Development, Clean Cache. This function basically just asks if the user is sure. Here is what I have so far:
Drupal.behaviors.confirm_delete = {

    attach: function (context, settings) {

         jQuery("#field-module-subsections-values input[id$='-remove-button']", context).bind('mousedown', function (ev) {

            ev.stopImmediatePropagation();
            ev.preventDefault();

            var followLink = window.confirm(question);

            if (followLink) {
                jQuery(this).click();
            }

            return false;

        });
    }
}

The problem I have is, that the function gets called before the click-event (thanks to mousedown), but the Ajax action on the button still fires. Maybe someone has a hint as to why?
Answer: Using hook_form_alter you can implement simple popups like this using #attributes.
 $form['submit']['#attributes'] => array(
  'onclick' => 'if(!confirm("Are you sure?")){return false;}',
 );

or
$form['submit']['#attributes']['onclick'] = 'if(!confirm("Are you sure?")){return false;}';

Comment: Thanks for your answer. But can I assign it to one certain button instead of the whole form?
Comment: Yes, just replace the 'submit' with your button.


Conexão HTML e SQL

Question: Estou projetando uma base de dados com onde tenho uma tabela com índices calculados de dados de outras tabelas. Estou projetando também uma dashboard em HTML para expor esses índices. Minha base de dados está armazenada em um servidor MySQL. Como eu faço para extrair esses dados e expor na dashboard fazendo o link entre as duas tecnologias?
Comment: Você vai precisar de alguma linguagem de programação para fazer isso. Acredito que é mais simples e a que mais se adéqua para você é o [tag:php].
Answer: Como já falaram do PHP vou dar um exemplo mínimo usando PHP + Mysql.
Usando PHP você deveria criar um arquivo .php e definir nele sua conexão com o banco de dados.
Ex:
<?php
define("HOST", "nomedohost");    #Para o host com o qual você quer se conectar.
define("USER", "nomedousuario");          #O nome de usuário para o banco de dados.
define("PASSWORD", "senha");           #A senha do banco de dados.
define("DATABASE", "bancodedados");       #O nome do banco de dados.
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
?>

E então chamar ele quando precisar se conectar ao banco de dados.
Para usar um arquivo PHP, o arquivo que você vai chamar deve ser .php Ex: index.php
E nele você deve fazer a requisição do seu arquivo .php com o banco de dados, vamos imaginar que aquele arquivo que você criou se chama db.php.
Como eu vi que você já conhece SQL, vou dar um exemplo usando o Mysql.
Vamos imaginar que sua tabela é assim:
Nome da tabela: users
Colunas: username, profile
username: Foo
profile: é um cara legal.

Arquivo PHP com seu HTML
<?php
    require_once('db.php');
    $username = "Foo";
    $sql = "SELECT * FROM `users` WHERE `username` = '$username'"; #sua query sql, um exemplo o SELECT *
    $query_exec = $mysqli->query($sql); #Executa o comando select.
    $row = $query_exec->num_rows; #Número de resultados encontrados.
    $get = $query_exec->fetch_array(); #Cria um vetor associativo com os dados.
    if($row > 0) {
        #encontrou resultados.
        $usuario = $get['username'];
        $perfil = $get['profile'];
        echo "{$usuario} {$perfil}"; #Pode fazer um echo de um html, ex: echo '
'.$perfil.'
';
        #O resultado do echo seria: Foo é um cara legal.

    } else {
        #não encontrou nada.
    }

?>
<!DOCTYPE html>

 <?php echo $usuario; ?>

Existem muitas formas de você manipular o echo do PHP, pode fazer usando AJAX, AJAX+Json, a linguagem web acaba sendo muito extensa, mas como você precisa aprender a usar o banco de dados, você pode começar fazendo algum curso de PHP, e caso não tenha conhecimento nenhum em programação, faça um curso de lógica de programação.
Answer: Você não vai conseguir fazer essa conexão com html. Para fazer isso você precisará de uma linguagem de programação que suporte essa conexão.
Comment: Ok! Já tenho um conhecimento elementar de algumas linguagens front-end and back-end, mas estou me aprimorando! Uma das que eu não havia tido contado era a PHP, mas já comecei a dar uma olhada! Muito obrigado!
Comment: E como seria esse link do PHP com HTML?
Comment: https://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_oo

Conexão HTML e SQL


Find where $f(x)=x^4-4x-2$ is strictly decreasing and where it is strictly increasing

Question: I have found that $f'(x)=0$ at $x=1$. I'm not sure if I should use an open interval or a closed interval to say where the function is strictly increasing and where it is strictly decreasing. I have read different definitions on that, and some suggest that it should be $(-\text{inf},1]$ and $[1,\text{inf})$, and others suggest that it should be $(-\text{inf},1)$ and $(1,\text{inf})$. So, what is correct? I need it to show that the function at most has two roots.
Thanks in advance.
Comment: I.e., find where $f'(x)<0$ and where $f'(x)>0$. I.e., find when $x^3<1$ (i.e. $x<1$) and when $x^3>1$ (i.e. $x>1$).
Answer: $f'(x) = 4x^3-4 = 4(x^3-1) > 0 \iff x > 1 \iff \text{ f is stritcly increasing .I hope this helps}$.
Answer: The general criterion is $f$ is strictly increasing on $[a,b]$, say, if $f′(x)>0$ on the open interval $(a,b)$. Hence, if $f′(x)>0$ on an interval, except on a discrete subset of $(a,b)$, $f$ is strictly increasing on the interval.
In the present case, $f$ is strictly increasing on the closed interval $[1,+\infty)$.
Comment: Thank you! So it is okay to say that f has a root in [-1,0] and a root in [1,2] because of what you said and the intermediate value theorem?
Comment: That's perfectly right.


Why is the double factorial $(-1)!! = 1$, by definition?

Question: By definition, the double factorial $(-1)!! = 1$. How can this be rationalized?
Comment: I couldn't find any specific answers to this on math.stackexchange.com, but worked out an answer for myself. Therefore, I've answered the question myself.
Answer: Looking at the expression for a double factorial in terms of ordinary factorials,
$$(2k-1)!! = \frac{(2k)!}{2^{k} k!}$$
and setting $k=0$,
$$(0-1)!! = \frac{0!}{2^0 0!} = 1.$$
This maintains consistency with the convention that $0! = 1$.
Answer: This is a "double factorial":

The product of all odd integers up to some odd positive integer n is often called the double factorial of n (even though it only involves about half the factors of the ordinary factorial, and its value is therefore closer to the square root of the factorial). It is denoted by n!!

From the link above, we have that for odd $n$ there is a $k\in \mathbb{Z}$ such that $n = 2k-1$, so $$n!! = (2k-1)!! = \dfrac{(2k)!}{2^k k!}.$$
$$\text{At}\;k = 0,\;\;\;(2\cdot 0 - 1)!! = (-1)!! = \frac{0!}{2^0 0!} = \frac{1}{1\cdot 1} = 1.$$
Recall that $0! = 1$, by definition (as representing the "empty product").

For even $n = 2k\,$ for $k \in \mathbb{Z}$: $$n\,!\,! = (2k)\,!\,! \;= \;2^k\, k\,!$$

Note: in both the odd and even case, $k$ is usually taken to be $k \ge 1$.
Comment: +1 for extending the answer to cover the even number double factorials, too.
Answer: One answer is to maintain that
$$
n!!=\frac{(n+2)!!}{n+2}
$$
for all $n$.  In this case, we must have
$$
(-1)!!=\frac{(-1+2)!!}{(-1+2)}=\frac{1!!}{1}=1.
$$


Views block link defaults to target="_blank" using rewrite output

Question: My client is using d6 and views 3.  They want to be able to display a box containing a random static image with an internal link to display in the same browser tab or an external link that would display in a new tab.  I created a content type with a field to upload an image, a text field to include a url, and (for simplicity's sake) a text field to include the target (either _self or _blank).  Then I built a views block to display each image using the 'rewrite the output of this field' option on the image field.  The text for the rewrite looks something like this:
[field_image].

The problem I'm having is even when field_target_value has target="_self" in it, views or something is ignoring it and the a tag is always showing up in firebug with target="_blank".  Another weird thing is that when I display the page source, the target doesn't appear at all.  When you click on the image, it does in fact bring the page up in a different tab as expected.
I've looked in the views code and did not see anything in there that seems to be the cause.  There is some custom code and theming on the site but I have not been able to find anything in there either.
Anyone have any clues why or thoughts on the strategy I am trying to use ??
Answer: Print the results from the views template.you can rewrite the views template for that specific field and check the link that whether its external or internal using the drupal function url_is_external and you can add the attribute target="_blank" to those views fields that are external urls.
Off topic suggestion : if you want all external links on your website should open in new tab then you can use the extlink module to open all external links in new tabs.

External Links is a small module used to differentiate between
  internal and external links. Using jQuery, it will find all external
  links on a page and add an external icon  indicating it will take you
  offsite or a mail icon  for mailto: links.
Answer: Thank you for the suggestions. I ended up using the linkimagefield module and removing the rewrite from the view but it still showed the same behavior.  I finally tracked it down as some javascript code originally added to check if the URL started with the letters http.  If so, the link was treated as external and target='_blank' was added, overriding any other target attribute included.  So this was ultimately not a drupal thing.


Regexp for slightly different strings in javascript if condition

Question: So i am getting in loop with this problem, that should be relatively easy, the problem is that i have slightly different strings that came from Database:

Honda VIP..., Honda LL Ultra..., Honda LL..., Honda LL start 5000i, Honda LL ultra 5000i

where i present image1.svg if the string that comes is (Honda VIP..., Honda LL Ultra..., Honda LL...)
or i present image2.svg is the image tha comes is exactly (Honda LL start 5000i, Honda LL ultra 5000i)
my code is:
...

else if (panel.match(/Honda VIP|Honda LL Ultra|Honda LL/i)) {
   return 'asset/image1.svg';
else if (panel.match(/Honda LL start 5000i|Honda LL ultra 5000i/i))
   return 'asset/image2.svg';

but the return is always image1, because if falls in "Honda LL" or "Honda LL ultra". i've tried to use \s+ into white spaces of the second else if:
panel.match(/Honda LL\s+start\s+5000i|Honda LL\s+ultra\s+5000i/i)

but no results.
Can someone help me on that?
Comment: Is this because they're always matching the final `Honda LL` in the first regex? If that's the case, try swapping the conditions.
Comment: That is not Java code! Did you mean JavaScript?
Comment: omg sorry.. my fault
Comment: i tried swaping the conditions but no effect..
Answer: Whatever this language is, it looks like the Honda LL at the end of the first regex is matching everything that the second regex would match.
Swap the conditions, so that the more-specific patterns would be matched first:
else if (panel.match(/Honda LL start 5000i|Honda LL ultra 5000i/i))
   return 'asset/image2.svg';
else if (panel.match(/Honda VIP|Honda LL Ultra|Honda LL/i)) {
   return 'asset/image1.svg';

Comment: Or make it an exact match: `panel.match(/^(Honda VIP|Honda LL Ultra|Honda LL)$/i)`
Comment: @Andreas or stop using regex, and use, say, a switch (a little harder to do case insensitively, though).
Comment: uhmm i see that "Honda LL" is getting all the conditions, because it falls there..  but  can i search for some string that contais/ends with  start 5000i or ultra 5000i and then falls into image2?
Comment: @Andy Turne i cannot change the base code.. theres a lot of else if conditions there.. ( but with differente other makes.. )
Comment: @Bruno if you can't change the code then I'm not sure what you're hoping you can do.
Comment: Andy, i can't change the else if conditions. Just the regex expressions to catch what i want. thank you for your help! it worked
Answer: By the way, can we have a regexp to start with some exactly string and then have variations in front? I was trying
} else if (panel.match(/^(Honda|.*B16|B18|B20|Vtec)$/i)) {
          return 'image.svg';

Like i want to catch the string that starts with Honda something B16 or Honda B16, or Honda B18 and so on at that list.. my code doesn't even get hit. but shouldn't the /^ /$ be working and catching the first string and then check the others?
I tried
} else if (panel.match(/^(Honda)$.*B16|B18|B20|Vtec/i)) {
          return 'image.svg';

but if i hit like 'CRX B16' it gets hited, but it shouldn't because it doesn't start with Honda...


How to bulk update select list fields?

Question: I have a content type and it has a select list field. There are two options Yes or No and this field is not a required field.
The website has about 100,000 nodes and I want to bulk update all nodes in order to select the "Yes" for each node. Is there any way to do this?
Comment: Sure, I'm waiting for your answer, thanks and are you familiar with the `BATCH API`? If you're it would be perfect for me to get your help on [that](http://drupal.stackexchange.com/questions/189450/is-it-a-good-way-to-change-multiple-text-fields-values-via-mysql-or-is-there-any#comment230746_189456) question.
Comment: Is this a one time thing? Have you got access to the database?
Comment: Yes, it will be one time. I have access to the database but I don't want to change it via MySQL etc. because it can cause some problems (http://drupal.stackexchange.com/questions/189450/is-it-a-good-way-to-change-multiple-text-fields-values-via-mysql-or-is-there-any). Thanks.
Comment: Erm, you already have an answer there?
Comment: @Kartagis, I think the structure is different and I can't change the values as mentioned in the answer of other question, can I?
Comment: What should the updated value become for a node that currently has value **No**? Should it become **Yes** or remain **No**?
Comment: @Pierre.Vriens, good question :) For this case, every node should have the **Yes** value. But for other cases we should check the current value first and then change if needed, you're right.
Answer: You have multiple options:

You can use code that iterates over all nodes and changes the value of the field (you will need some module to execute the code, for example devel).
Other option is to use the Views Bulk Operations module, build a view which shows a list of nodes of that type, and add a views bulk operations field which has the option to edit a node, and this will allow you to select all the nodes in a view and modify a field with the same value.
Answer: Question refinement
This answer ALSO takes into account the answer to my extra comment like "What should the updated value become for a node that currently has value No? Should it become Yes or remain No?". And to which you answered like "Good question :) For this case, every node should have the Yes value. But for other cases we should check the current value first and then change if needed, you're right".
Step 1: Create a Rules Component
Have a look at this example of a Rules Component (in Rules export format):
{ "rules_set_an_initial_value_for_a_text_field" : {
    "LABEL" : "Set an initial value for a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node" : { "label" : "Node", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
      { "NOT data_is" : { "data" : [ "node:field-optionlist" ], "value" : "A" } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-optionlist" ], "value" : "B" } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in "Step 2" below.
In my case I have a selection list field with machine name field_optionlist.
This field actually has 3 possible values, like so:

A (=Advanced).
B (=Basic).
C (=Custom).

As an example, I decided to use a Rules Condition "The selected value must NOT be Advanced" (assume that's the value I do not want to reset).
For any other value of that field I want the Rules Action to change the value of that field to Basic.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.
Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.
If you want, just grab (copy) the exported rule above, change all occurences of the machine name of that field to match the machine name of your field (and adapt the possible values like 'A' and 'B' in my example). After doing so you can simply import this Rules Component in your own environment.
After you imported this Rules Component, navigate to admin/config/workflow/rules/components in your own site. Then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node identifier and hit the Execute button. Depending on the node id you selected (i.e. if it has that field, and if the Rules Condition is satisfied), your node will be updated accordingly.
After you're confident your Rules Component works perfect for all variations of your nodes, move on to step 2 below.
Step 2: Let VBO to the bulk of the work
This step is pretty easy ... Just create an appropriate view of all your about 100.000 nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.
If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.
Attention: to process 100.000 nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Video tutorials
If you're not familiar (enough/yet) with Rules, checkout the 32 (!!!) great, and free, video tutorials Learn the Rules framework.
Happy VBO-ing while Rules-ing!
Answer: You need something along the lines of
<?php
$nodes = node_load_multiple(array(), array('type' => 'page'));
foreach($nodes as $node) {
  // Only modify nodes that have something in the body field
    $node->field_select['und'][0]['value'] = 'yes';
    node_save($node);
}

Modify as needed. Don't forget to clear the caches afterwards.
Another option is installing the Administrative Views and Views Bulk Operations modules, and pointing to Change Value, as seen in the below screenshot
Answer: In such scenario, one could be required to preserve node timestamps or avoid whole node_save() process, in this case you would do:
$key = 'value'; // Key that holds the field value.
$value = '1'; // Assuming '1' is the value for the option "Yes".
$bundle = 'article'; // Name of the node type.

// Get $bundle node ids.
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', $bundle)
  ->execute();

if (isset($result['node'])) {
  // Load matching nodes.
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);

  foreach ($nodes as $nid => $node) {
    // Update the field(s). Assign whole array since some nodes may
    // come with an empty field.
    $node->field_foobar[LANGUAGE_NONE] = array(array($key => $value));

    // Give other modules the opportunity to act before saving fields.
    field_attach_presave('node', $node);

    // Save field data (modules can also hook here).
    field_attach_update('node', $node);
  }

  // Reset cache for the updated nodes.
  entity_get_controller('node')->resetCache($nids);
}

Answer: Install and enable the Views Bulk Operations module and create a view with a page display.
Add => Bulk operations: Content (Content) field in view.
Refer

Select the Fields you want to set the default value.
Save the view, and go to the page it created. If you have more than one page of results, you can choose to select all items on the current page, all items on all pages, or you can manually check boxes corresponding to individual nodes. At least one checkbox must be checked to proceed.
Now you set the default value and save it.

How to bulk update select list fields?


How to free C++ instance in JNI?

Question: I want to know how to free the instance of c++ class.
I tried like this but error occurred.
<code>Live *pLive = Live::getInstance();
// do something with pLive
env->DeleteLocalRef(reinterpret_cast<jobject>(pLive));
</code>
I need your help. Thank you.
Comment: This is impossible to answer without seeing the definition of `Live`. Especially as it appears to be a singleton...
Answer: Since you're not calling anything on env to create the object, I assume Live::getInstance returns a C++ object and not a JNI object?  In that case, use delete.  You only use DeleteLocalRef on a JNI object.  (A JNI object is an object that actually exists inside the JVM and is directly accessible in Java).  Trying to DeleteLocalRef on a C++ object will always crash, as its not in the JVM's shared memory
Comment: As it is not a Java object reference, you mean.

How to free C++ instance in JNI?


Double pipe to save output to file in C

Question: I have created something like "linux pipe" to redirect  output from one program to another and it's working like a charm. But now I want to save final output to a file. On the internet I saw that I need to create double pipe, but everything I create is not working.
Here is my actual code of "pipe":
 int pipes[2];
 int pid;
 pipe(pipes);
 if(pid=fork()){
         int fd = open("t.txt", O_CREAT | O_TRUNC | O_RDWR, 0644);
    if (fd < 0) {
        perror("open()");
        exit(EXIT_FAILURE);
    }
   close(pipes[1]);
   dup2(pipes[0],STDIN_FILENO);
    execvp(sec_command[0],sec_command);

 }
     else{

   close(pipes[0]);
   dup2(pipes[1],STDOUT_FILENO);
   execvp(first_command[0],first_command);
 }

Thanks
Comment: You don't need an extra pipe to save the output to a file.  You need to open the file you want and have the code write to that.
Comment: please, post a [Minimal, Complete and Verifiable Example](https://stackoverflow.com/help/minimal-reproducible-example) so we can test it. And please, also indent appropiately the code to make it readable.
Answer: No. You don't need to.  You just need to do a second dup2 in the child process (which will be capturing its input from the pipe) to the file descriptor of the file you want the output to go.  You haven't post a Minimal, Reproducible Example, and your code is wrong (it execs in the parent and child process) so i've tried to work a complete solution.  Here it is:
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

pid_t
subcommand_to_file(
        char **subcommand_args,
        char *file)
{
    int pipes[2];
    pipe(pipes);
    pid_t pid = fork();
    if (pid < 0) {
        perror("fork");
        return -1;
    } else if (pid == 0) { /* child */
        int fd = open(file,
                O_CREAT | O_TRUNC | O_RDWR,
                0666); /* permissions controled by umask */
        if (fd < 0) {
            perror("open");
            exit(EXIT_FAILURE);
        }
        close(pipes[1]); /* close output descriptor of pipe */
        dup2(pipes[0], STDIN_FILENO); /* redirect input */
        close(pipes[0]); /* not needed after dup2 */
        dup2(fd, STDOUT_FILENO); /* rediect output */
        close(fd); /* not needed after dup2 */
        execvp(subcommand_args[0], subcommand_args);
        perror("execvp");
        exit(EXIT_FAILURE);
    }
    /* parent */
    close(pipes[0]); /* close input descriptor of pipe */
    dup2(pipes[1], STDOUT_FILENO);
    close(pipes[1]); /* not needed, after dup */
    return pid; /* so if you want to wait for the child */
}

int
main(   int argc,
        char **argv)
{
    int opt;
    char file[256];

    /* default value for filename */
    snprintf(file, sizeof file, "%s.out", argv[0]);

    while ((opt = getopt(argc, argv, "f:")) != EOF) {
        switch (opt) {
        case 'f':
            strncpy(file, optarg, sizeof file);
            break;
        }
    }

    argc -= optind;
    argv += optind;

    pid_t child = subcommand_to_file(argv, file);
    if (child < 0) {
        fprintf(stderr,
            "subcommand_to_file: %s\n",
            strerror(errno));
        exit(EXIT_FAILURE);
    }
    /* copy input to output to pass stdin to  subprocess */
    int c;
    while((c = getchar()) != EOF) {
        putchar(c);
    }
    close(STDOUT_FILENO);
    wait(NULL);
    fprintf(stderr, "%s terminated\n", argv[0]);
    exit(EXIT_SUCCESS);
}

The above program is called as
$ a.out -f output_file  command [args ...]

and will end when the command program is finished.  Just try
$ a.out -f out.txt echo a b c

and you will get
$ cat out.txt
a b c
$ _

Double pipe to save output to file in C


Error setonclickListener undefined for the type button

Question: Hello i'm getting the error:

the method setonclickListener(new onclickListener(){}) is undefined
  for the type button

Here's my code:
public class Sliding extends Activity {
    /** Called when the activity is first created. */
    private LinearLayout MenuList;
    private Button btnToggleMenuList;
    private int screenWidth;
    private boolean isExpanded;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sliding);
        MenuList = (LinearLayout) findViewById(R.id.linearLayout2);
        btnToggleMenuList = (Button) findViewById(R.id.button1);
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenWidth = metrics.widthPixels;

        btnToggleMenuList.setonclickListener(new onclickListener() {
            public void onclick(View v) {
                if (isExpanded) {
                    isExpanded = false;
                    MenuList.startAnimation(new CollapseAnimation(MenuList, 0,(int)(screenWidth*0.7), 20));
                }else {
                    isExpanded = true;
                    MenuList.startAnimation(new ExpandAnimation(MenuList, 0,(int)(screenWidth*0.7), 20));
                }
                }
        });
    }
}

can anyone tells me why?
Comment: import android.view.View.OnClickListener; and use setOnClickListener instead-of setonclickListener
Answer: Replace this
btnToggleMenuList.setonclickListener(new onclickListener() {
        public void onclick(View v) {

By
btnToggleMenuList.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

Also make sure you have the below import statement
import android.view.View.OnClickListener;

Answer: Change it to
View.OnClickListener()

Answer: Write this:
btnToggleMenuList.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

Rather than:
btnToggleMenuList.setonclickListener(new onclickListener() {
    public void onclick(View v) {

Answer: Try this:
  btnToggleMenuList.setonclickListener(new onclickListener() {

        @Override
        public void onclick(View v) {


jspdf text stretched in MS Edge

Question: I have a line of text I recently added to a jspdf-driven PDF action in our Ember application. It looks fine in Chrome, Firefox, Safari et al, but in Edge the character spacing is out of whack - it's very wide, thus lengthening the line and causing overlapping text (this line is right-aligned with more text that's left-aligned). Here's the relevant code:
  doc.setFont('Helvetica').setTextColor(153, 153, 153).setFontSize(size);
  doc.text(string, this.get('positioning').rightEdge, yPos, { 'align': 'right' });

(positioning is an object with a bunch of magic numbers for document locations, and string, yPos, and size are integer method arguments. doc is the jsPDF object being added to, if that's not obvious.)
Here's what it looks like in Chrome (i.e. what we want to see):

Here's the Edge result:

I've tried left-aligning the text, and it's still stretched. Changing the size doesn't seem to help either. If I pass a negative value for the charSpacing argument to the doc.text() call, I can mitigate the problem, but that then mangles other browsers; I'd need to pass that argument only for Edge, which feels really kludgy.
Why is jspdf and/or Edge doing this, and what can I do about it?
ETA: I've discovered that this only happens (for me) with a string built around a call to Date.Prototype.toLocaleDateString(), like so:
`Draft - Printed on ${Date.now().toLocaleDateString('en-us', dateFormatOptions)} at ${Date.now().toLocaleTimeString('en-us', timeFormatOptions)}`;

So jspdf has a problem with localized strings, maybe?
Comment: Not relevant to the question per se, but trying to fix this is what uncovered this question as well: https://stackoverflow.com/q/56259199/306084
Comment: you can check whether JSpdf supports the Edge browser or not. Ref: https://github.com/MrRio/jsPDF/issues/280 From this link, Edge is not listed there. If you think that it is officially supported by JSpdf than you can consult them about the issue. They can give some hint may help to narrow down the issue.
Comment: Thanks, @Deepak-MSFT! I found the answer, which has to do with RTL characters in the output of `toLocaleDateString()` and `toLocaleTimeString()`. Strip those out and the problem goes away.
Answer: This turns out to be another case of IE's toLocaleString has strange characters in results: Edge is adding unicode formatting characters to the output of toLocaleDateString() and toLocaleTimeString() and they're causing jspdf to do weird stuff. Using a regular expression to strip out the RTL characters resolves the issue.

jspdf text stretched in MS Edge


equivalent x86_64 instructions to ARMv7 ones

Question: I'm trying to port some ASM instructions in a source code I have in C and ASM.
Can anyone help me to find an instruction set and to understand the uses of the instructions of ARMv7?
Actually I'm handling interrupts, so I want to "translate":
iretq
int $0x80
int $0x04

I've never programmer in ARMv7 ASM.
Thanks!
Comment: Wouldn't it be more productive to ask "what do these instructions do"? Then you would learn something and might be able to port the code yourself, rather than just asking for someone else to do the translation work for you
Comment: `movs pc, lr` and `svc #0`.  I am not sure how an answer is helpful.
Comment: iretq = returns from interrupt; int = calls an interrupt, 1st argument is interrupt number on IDT. thanks anyway... ;)
Answer: The corresponding Intel intsructions are iret and int, respectively. That said, interrupt handling is highly CPU- and platform-specific; translating commands one-to-one most likely won't yield a working program. If you're developing an application, you shouldn't be messing with interrupts (even int 80h - there are better ways to perform a syscall). If you're developing a driver or an OS kernel, you should learn assembly systematically, rather than translating line by line.
The int command might be theoretically present in application code - it invokes an interrupt, that's an exotic but legitimate way of interacting with the OS. The iret command, on the other hand, should only be used in an interrupt handler. It's never used outside of kernelspace.
Comment: If you're developing an application, you shouldn't be messing with interrupts (even `int 80h` - there are better ways to perform a syscall). If you're developing a driver or the OS kernel, you should learn assembly systematically, rather than translating line by line.
Comment: Platform is Android, CPU is ARMv7 Processor rev 0 (v7l). I also want to know a how-to ASM for that configuration. I wasn't asking for translation if very hard to do with only that information. I want to learn. The problem isn't people think they know when they don't, the problem is I've never used ARM before ;)


Saving form after altering it

Question: I'm altering the "Edit menu link" form
function module_name_form_menu_edit_item_alter(&$form, &$form_state, $form_id) {
    $form['html_content'] = array(
        '#type' => 'textarea',
        '#title' => t('HTML Content'),
        '#maxlength' => 180,
        '#required' => FALSE,
        '#description' => 'Put here the HTML code of the menu'
    );
}

The text area is showing fine, but it's not saving the information I put into.
How can I solve that?
Comment: Are you expecting Drupal to automatically save the data in this custom form element, associate it with the menu link, then re-load it for you every time you re-load that menu link in any context??!!
Comment: Hi Clive, I'm new to Drupal. Any ideas how to save this? Using "set_variable" is not the right way in my opinion since there are lots of menu links.
Answer: Generally speaking, only the form builds with system_settings_form() automatically saves the form field content of all the form fields present in the form. This is because its form submission handler (system_settings_form_submit()) contains the following code.
  foreach ($form_state['values'] as $key => $value) {
    if (is_array($value) && isset($form_state['values']['array_filter'])) {
      $value = array_keys(array_filter($value));
    }
    variable_set($key, $value);
  }

The form you are altering has a different form submission handler, menu_edit_item_submit(), which doesn't contain similar code. The function that is called for saving the menu item, menu_link_save() saves the fields it knows of, and which are defined in the database schema for the table used for this purpose.
  if (!$existing_item) {
    $item['mlid'] = db_insert('menu_links')
      ->fields(array(
      'menu_name' => $item['menu_name'],
      'plid' => $item['plid'],
      'link_path' => $item['link_path'],
      'hidden' => $item['hidden'],
      'external' => $item['external'],
      'has_children' => $item['has_children'],
      'expanded' => $item['expanded'],
      'weight' => $item['weight'],
      'module' => $item['module'],
      'link_title' => $item['link_title'],
      'options' => serialize($item['options']),
      'customized' => $item['customized'],
      'updated' => $item['updated'],
    ))
      ->execute();
  }

db_update('menu_links')
  ->fields(array(
  'menu_name' => $item['menu_name'],
  'plid' => $item['plid'],
  'link_path' => $item['link_path'],
  'router_path' => $item['router_path'],
  'hidden' => $item['hidden'],
  'external' => $item['external'],
  'has_children' => $item['has_children'],
  'expanded' => $item['expanded'],
  'weight' => $item['weight'],
  'depth' => $item['depth'],
  'p1' => $item['p1'],
  'p2' => $item['p2'],
  'p3' => $item['p3'],
  'p4' => $item['p4'],
  'p5' => $item['p5'],
  'p6' => $item['p6'],
  'p7' => $item['p7'],
  'p8' => $item['p8'],
  'p9' => $item['p9'],
  'module' => $item['module'],
  'link_title' => $item['link_title'],
  'options' => serialize($item['options']),
  'customized' => $item['customized'],
))
  ->condition('mlid', $item['mlid'])
  ->execute();

In your case, you need to alter the form, adding the form field, and a form submission handler that saves your data in your own database table.
As there are more than one button on that form, I prefer associate a new form submission handler to the specific button, such as with the following code.
$form['actions']['submit']['#submit'][] = 'mymodule_menu_edit_save_submit';

You could also be interested in doing something when the menu item is deleted (in which case, you should delete the data from your database table); the delete button is $form['actions']['delete'].
Comment: It's not possible to edit the menus table schema? (instead of adding my own table)
Comment: To alter the schema defined from another module is generally not preferable; the reason is that you could introduce compatibility issues with future versions (e.g. Drupal will add a database row with the same name you are using for your own data, or Drupal will change the name of the database table used for saving the menu item links). If you are going to alter a database table used by Drupal, you need to implement the code to alter the table, and implement [hook_schema_alter()](http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_schema_alter/7).
Comment: So far, I have never seen a case where altering an already existing table was justified. Consider there could be also collateral performance effects. (A database schema is optimized for the fields being defined, not for the fields added from third-party modules.)
Comment: Good. Where to save the data then? (I'm using variable_set and variable_get right now)
Comment: You just save the data in a database table your module creates when it is installed.
Comment: Do you think using variables could alter performance considerably?
Comment: Drupal variables are always loaded when Drupal bootstrap, and kept in memory in the `$conf` global variable; if you are going to save the data for a possibly indefinite number of menu links in one or more Drupal variables, there should be a performance issue. Considering what you are going to save, I would not suggest using Drupal variables in this case, also because what you are saving is not necessary for rendering the actual page being required.

Saving form after altering it


Prove radius of convergence for general power series.

Question: Question:
Show that the radius of convergence of $\sum_{k=0}^\infty c_kx^k$ is $\lim_{n\to\infty} \frac{c_n}{c_{n+1}}$ if this limit exists
My attempt:
The only thought that occurred to me was to attempt the ratio test:
$\lim_{k\to\infty} |\frac{c_{k+1}x^{k+1}}{c_kx^k}| = \lim_{k\to\infty} |\frac{c_{k+1}\not x^k x}{c_k\not x^k}| = x\lim_{k\to\infty}\frac{c_{k+1}}{c_k}$
But I am unsure of this being the correct method, or how to connect what I am doing with the conclusion I'm seeking.
Comment: Please add the definition of $s_n$ to your question. It is probably the sum of the first $n$ terms of the sequence $c_k$?
Comment: Sorry. I didn't notice the discrepancy. I am looking at the question right now; it's not explicitly defined in any of the questions. However, in previous proofs, $s_n$ represents the sum of the first n terms, so I think you are right. Would it be safe to assume that?
Comment: I would assume it represents the sum of the first $n$ terms *without* taking $x$ on board. The existence of the limit should not depend on $x.$
Answer: Lecornu, french mathematician, have proved that, if the ratio $c_{n+1}/c_n$ has a limit L then L is a singular point of $f(x)=\sum_{n=0}^\infty c_n x^n$. But this is not necessary the unique singular point on the circle of convergence.
(counterexample: $f(x) = \frac{x}{1-x}+\ln(1+x) =\sum_{m=1}^\infty \left(1+\frac{(-1)^m}{m}\right)x^m$ have two singular points, 1 and -1, but  $c_{n+1}/c_n$ converges to 1.)
see Hadamard, sur le rayon de convergence des séries ordonnées selon les puissances d'une variable, Comptes rendus de l'académie des sciences de Paris, 23 janvier 1888.
Hadamard, La série de Taylor et son prolongement analytique, Scientia, 1903.
Hadamard & Mandelbrot, La série de Taylor et son prolongement analytique, 1928.
Comment: But doesn't this counterexample conform to the radius of convergence, just not a single point of convergence?
Comment: if you know the singular points, you know the radius of convergence: this is the smallest distance between 0 and the singular points.


DataCache constructor not accessible on staging server; works fine locally

Question: I am using Azure's Cache Service preview, following their tutorial. Things work great locally using IIS Express. However, when I deploy to the staging server, I receive the following error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'Microsoft.ApplicationServer.Caching.DataCache.DataCache(string)' is inaccessible due to its protection level
I am initializing DataCache with the following code, which throws the above error:
_cache = new DataCache("cacheName", "configurationName");

I am using the Azure Cache NuGet package and all the DLLs look correct in the bin directory. Any help would be greatly appreciated.
Answer: This ended up being a conflict with the AppFabric role feature which was installed on the staging server (Windows 2008 R2). Once that feature was removed, the Azure Cache worked fine.


how to set PATH in CentOS so that it is visible in PHP

Question: I need my PATH environment variable to include /usr/local/bin when seen from PHP, so that I can execute binaries that are in /usr/local/bin with exec() in PHP code without writing their full path, e.g. exec("ffmpeg");
If from php I run echo getenv("PATH") it outputs:
  /sbin:/usr/sbin:/bin:/usr/bin
However if I log into the server as root via ssh and I write in the terminal
  echo $PATH
I get:
    //sbin://bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
So the /usr/local/bin is already included when I log into the command line, but not when PHP is run.
So how do I add directories to the path environment variable in such a way that they are recognized also by PHP?
I tried to add
  SetEnv PATH $PATH:/usr/local/bin
to /var/www/vhosts/mydomain.net/conf/vhost.conf (which contains other directives which do have effect), but it doesn't change a thing.
I also tried by adding that to a .htaccess file (dunnow if it made sense) but it didn't work either.
I already searched the forum and found a lot of similar or identical questions but no answer, or at least none that works.
Answer: In your apache startup script, try to export your custom path.
IIRC, Apache defaults to common envvars when started. So, even changing its value in user's env won't do the trick.
Comment: What is the apache startup script that I have to edit?
Comment: /etc/rc.d/init.d/httpd is default startup script for Apache on CentOS
Answer: Well, depending on your needs you can either set it in the script (Documenation Link)
<?php
 // Works as of PHP 4.3.0
set_include_path('/inc');

// Works in all PHP versions
ini_set('include_path', '/inc');
?>

or you can set it in the php.ini file itself (Documentation Link)
include_path=".:/php/includes

Comment: I may be wrong but I don't think that has anything to do with my question which was about the PATH environment variable for executing binaries with exec()... or will the include_path directive also work for exec()??
Answer: edit the php.ini
the clause include_path indicate in which path php take the script.
Comment: I think include_path is for php files to be included with the include() and require() directives, I don't think that has any relation with the environment variable PATH, or has it?


Prove by Induction that Norms in a Finite Dimensional Space are Equivalent?

Question: I would have thought that this is a good candidate for an inductive proof, but I have searched for one and failed. Is there such a proof, and if not why not ? Here's how far I got.

It's easy to establish that equivalence is transitive so it's only necessary to prove that any norm is equivalent to a norm of choice, e.g. $ ||.||_1$
In any finite space any norm satisfies $||.|| \le M ||.||_1$. Prove this by picking a basis and applying the triangle inequality.
That leaves to prove the other half of the equivalence inequality that $||.||_1 \le m ||.||$
Base case for induction: $Dim(V) = 1$. For a basis vector $e_1$ in $V$ any vector $v = \nu_1 e_1$ and $||v|| = ||\nu_1 e_1|| = |\nu_1|.||e_1|| = ||v||_1.||e_1||/||e_1||_1$ So, $||v||_1 \le m||v||$ where $m = ||e_1||_1/||e_1||$

But, I can't prove the inductive step that if true for $Dim(V) = n$ then true for $Dim(V) = n+1$.
(I have some references for the topological proof - it's specifically an inductive proof that I'm looking for),
Answer:
I am not sure induction is the best way to go.
There are plenty of resources on MSE about the equivalence of norms in finite dimensional spaces. For example, here.
One possible way to go is to observe that the unit ball of any norm in finite dimensional space is compact with respect to the usual Euclidean topology. That is, the set $B=\{x\in V: ||x||\leq 1\}$ is compact. Since $||\cdot||_1$ is continuous in the Euclidean topology, it is bounded on $B$, so there exists some constant $M>0$ so that

$$||x||_1\leq M\enspace\forall x\in B$$
Hence, since $||x/||x||||=1$ for all $x$,
$$||x||_1 \leq M||x|| \enspace \forall x\in V$$
whence you get the other direction you seek.
Comment: Thanks, but it's specifically an inductive proof that I'm interested in.


customize url of path of file entity

Question: I'm using the media module to build an imagebank.
Is there a way to customize the url of a file? Currently is looks like this: file/20 and I would like t to look like this imagebank/image/20.
Any ideas?
thx in advance
Answer: File entity doesn't currently integrate with Pathauto but integration is being worked on in Add support for Pathauto.
Please help test the latest patch and provide feedback including if it works correctly and any issues you might have found!
Comment: Thx Devin.
The patch seems to do the trick. I'll run some more tests laters on.

customize url of path of file entity


If $\mathfrak{m}_1\mathfrak{m}_2\cdots \mathfrak{m}_n=0$ then $A$ is an Artinian ring.

Question: I want to prove the following:
Let $A$ be a Noetherian commutative ring with unity, and suppose that zero ideal is a product $\mathfrak{m}_1\mathfrak{m}_2\ldots \mathfrak{m}_n$ of maximal ideals in $A$. Then $A$ is Artinian.
The first step in this theorem is to prove that the quotients $\displaystyle\prod_{i=1}^{j-1}\mathfrak{m}_j/\prod_{i=1}^{j}\mathfrak{m}_j$ are finite-dimensional vector spaces over $A/\mathfrak{m}_j$. Here, there is a natural scalar product, and it is well defined, but first I am not sure why they are finite-dimensional.
The following steps are easy. The proof follows inductively using a short exact sequence. However, I am studying another proof with the same first step.
I have to prove two things:

I can refine the sequence
$A\supset \mathfrak{m_1}\supset \mathfrak{m}_1\mathfrak{m_2}\supset \cdots\supset \mathfrak{m}_1\mathfrak{m_2}\cdots\mathfrak{m}_n= 0$
to a composition series $A\supset B_1\supset\cdots\supset B_r=0$.
If $N\subset A$ is a submodule and $N_i=N\cap B_i$ then some subset of such $N_i$'s is a composition series of $N$. So, any chain of submodules of $A$ has finite length.

I do not know how to prove this. I will appreciate your ideas for both propositions.
Comment: The vector spaces are finite dimensional because they're Artinian as modules (being quotients of ideals of $A$), and in vector spaces fin dim = Artinian = Noetherian.
Answer: Use the Chinese remainder theorem, $A = A/(\prod \mathfrak m_i)\simeq A/(\mathfrak m_1^{n_1})\times\cdots\times A/(\mathfrak m_i^{n_i})$. It's enough to show $A/\mathfrak m_j^{n_j}$ is Artinian. (if you assume $\mathfrak m_i$ are distinct, then $A$ is just a finite product of fields, hence Artinian, without assuming it's already Noetherian.) This follows from $\mathfrak m_j + \mathfrak m_j^{n_j}$ is the only prime ideal, as it consists of only nilpotent elements, so it has Krull dimension $0$.
Note that this is false if $A$ is not assumed to be Noetherian in the first place. Let $A=F[x_1, x_2, \cdots]/\mathfrak m^2$ where $\mathfrak m=(x_1, x_2, \cdots)$. Then $\overline{\mathfrak m}^2=0$, but $A$ is not Artinian: $(\bar x_1, \bar x_2, \bar x_3, \cdots)\supsetneq (\bar x_2, \bar x_3, \cdots)\supsetneq(\bar x_3, \cdots)\supsetneq \cdots$ form an infinite chain of decreasing ideals of $A$. In particular, $\prod_{i=1}^{j-1}\mathfrak{m}_j/\prod_{i=1}^{j}\mathfrak{m}_j$ is not finite-dimensional vector spaces over $A/\mathfrak{m}_j=F$.
Comment: Adapted accordingly.
Comment: @AndrésFelipe It is very bad form to move the goalposts on a question after it has been answered. In general one should NOT make edits that invalidate existing answers.  That said, I'd like to ask *Just a user* if they would rather see your edit rolled back, or if they would rather let you make the edit and update this solution.
Comment: Sorry, I forgot a hypothesis. The ring $A$ has to be Noetherian. Now, I edited this.
Comment: Thank you for your answer @Justauser. And sorry for editing my question after this.
Answer: We shall not pay attention on refining the chain to be composition chain. We only need to use the factors in the chain. We can prove as follows:
Suppose $A$ is Noetherian. Then it is clear that $A/\mathfrak{m}_1...\mathfrak{m}_n$ is Noetherian as for $A$-module. Consider the following exact sequences: $$0\rightarrow \mathfrak{m}_1...\mathfrak{m}_{n-1}/\mathfrak{m}_1...\mathfrak{m}_n \rightarrow A/\mathfrak{m}_1...\mathfrak{m}_n \rightarrow A/\mathfrak{m}_1...\mathfrak{m}_{n-1}\rightarrow 0$$
We can deduce that both $\mathfrak{m}_1...\mathfrak{m}_{n-1}/\mathfrak{m}_1...\mathfrak{m}_n$ and $A/\mathfrak{m}_1...\mathfrak{m}_{n-1}$ are Noetherian as for $A$-module. Repeating using this methods, one can find that for any $1\le i\le n-1$, $\mathfrak{m}_1...\mathfrak{m}_i/\mathfrak{m}_1...\mathfrak{m}_{i+1}$ is Noetherian as for $A$-module, hence it is also Noetherian as for $A/\mathfrak{m}_{i+1}$-vector space (If $IM=0$, then $A$-module $M$ is equivalent to $A/I$-module $M$.). Hence $\mathfrak{m}_1...\mathfrak{m}_i/\mathfrak{m}_1...\mathfrak{m}_{i+1}$ is Artinian as for $A/\mathfrak{m}_{i+1}$-vecor space, so does as for $A$-module. Inductively back to deduce that $A/\mathfrak{m}_1...\mathfrak{m}_i$ is Artinian as for $A$-module for all $i$, hence $A$ is Artinian.


Siebel DB question

Question: One of my client has a Siebel program installed and a .DBF database. I'd like to know if it's possible to make requests directly to this "db file" within a c# application?
Do I need to install Siebel on my dev machine too?
Thanks!
UPDATE
It worked. You'll need some dll and a EXE file :
•   dbctrs8.dll
•   dbcon8.dll
•   dbserv8.dll
•   dbodbc8.dll
•   dblgen8.dll
•   dbeng8.exe
(this is from Siebel 7, but  you'll be able to find what dll you'll need because you'll get an error anyway).
You'll need a computer that has Siebel installed and "copy" the ODBC connection parameters from it. So, go to that computer and go to run, execute, odbcad32. Find the ODBC connection, check the parameters (you'll see the main dll + other parameters). Then go to the target computer and add an ODBC connection with the same parameters.
If the "ODBC Driver" is not available, you'll need to install it manually. I followed the procedure there :
http://www.developer.com/db/article.php/3712461/Installing-a-Custom-ODBC-Driver-on-Windows-for-SQL-Anywhere.htm
Answer: The dbf is an instance of a local SQL Anywhere database, so you could connect to it via the Siebel Local database driver - or install Siebel Dedicated Web Client and grab the controls that will appear in your C# IDE.

Siebel DB question


Calculating significance of difference between 2 groups using bootstrap

Question: I'm calculating the significance of the difference between 2 groups using the bootstrap method in the way I haven't found in the literature but anyway makes sense to me. Now I want to double-check if I'm not shooting myself in the knee.
We have 2 groups with n (n is usually >1M and distribution is skewed) samples:

 x: [x1, x2, x3, ..., xn]
 y: [y1, y2, y3, ..., yn]

Procedure: For N(=1000?) times repeat:
 1. For both groups, get bootstrap samples of size n and calculate mean. (It can also be some other statistic.)
 2. Calculate the difference between means (or some other statistic).

Now we have the distribution of differences. Can we make statements such:
I'm 95% confident that the difference of means is between a and b?
or 'Difference of means is statistically significant if 95% confidence interval doesn't include 0'?
Comment: Another option would be a permutation test https://stats.stackexchange.com/questions/20217/bootstrap-vs-permutation-hypothesis-testing.
Comment: Why are you doing this? Why not a standard test?
Comment: It gives you a distribution of differences and feels intuitive. And you don't need to make any special assumption about the data - I think.
Comment: You are able to construct a confidence interval at a given level based on bootstrap sampling.
Answer: You don't say anything about the populations from which your data were randomly sampled. If sample sizes are at least moderately large and the data do not show
signs of severe skewness (e.g., far outliers on one one side of center), then
a two sample t confidence interval is probably the simplest and best choice.
If data are from continuous non-normal populations, then a two sample Wilcoxon (rank sum) procedure may provide a useful confidence interval (CI).
For example, suppose we have samples of sizes $n_1 = 30$ and $n_2 = 20$ from respective distributions $\textsf{Gamma}(\text{shape}=5, \text{rate}=.2)$ and
$\textsf{Gamma}(6, .4).$
set.seed(2019);  n1=30;  n2=20
x1 = rgamma(n1, 5, .2);  x2 = rgamma(n2, 6, .4)
summary(x1);  sd(x1)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  7.653  16.314  24.456  27.025  33.651  59.145
[1] 13.13563  # sample SD
summary(x2);  sd(x2)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  5.847   9.563  14.717  14.795  19.022  26.130
[1] 6.076901

In in each sample, the sample mean and median are near each other.
Boxplots show no outliers. Also, notches in the boxes are nonparametric CIs; non-overlapping CIs suggest that the two population
medians are different.
boxplot(x1, x2, notch=T, col="skyblue2")

Especially knowing the populations, one might raise theoretical objections
to either the 95% Welch t CI $(6.67, 17.79)$ or the 95% Wilcoxon CI $(4.79, 17.11)$. But we know less just looking at descriptions of the sample, and there are no strong warnings in those descriptions against using either kind of CI. Results from relevant R procedures are shown below. Neither CI includes $0,$ so one can conclude that the difference
$\delta = \mu_1 - \mu_2$ is significantly different from $0.$
t.test(x1, x2)$conf.int
[1]  6.673883 17.786275
 attr(,"conf.level")
 [1] 0.95

wilcox.test(x1, x2, conf.int=T)$conf.int
[1]  4.785996 17.109673
 attr(,"conf.level")
 [1] 0.95

However, you specifically asked about making a bootstrap confidence
interval for the difference in population means. Your interest in making a bootstrap CI may be that you want to have the experience doing one, or that doing a bootstrap is a class assignment. There are very many
styles of bootstrap CIs; I will illustrate one of the simpler styles.
You seek a CI for $\delta = \mu_1 - \mu_2,$ which can be estimated
by $D = \bar X_1 - \bar X_2.$ If you knew the distribution of $D,$ then you could use it to find bounds $L$ and $U$ such that
$$0.95 = P(L \le D - \delta \le U) = P(-U+D \le \delta \le -L+D),$$
so that a 95% CI for $\delta$ would be of the form $(D-U, D-L).$
Recall that our observed value of $D$ is  $D_{obs}= \bar X_1- \bar X_2 = 12.23,$
which we use in the bootstrap procedure.
d.obs = mean(x1) - mean(x2);  d.obs
[1] 12.23008

Not knowing the distribution of $D$ we use bootstrapping to find
useful approximations $L^*$ of $L$ and $U^*$ of $U.$ In order to do this we take a large number $B = 2000$ of samples of size 30 with replacement
form x1 and then find their means $A_1^*.$ Similarly, we 're-sample' from x2 to find means $A_2^*.$ From these, we find a vector of 2000 quantities $D^* = A_1^* - A_2^*.$  We would like to have a 'bootstrap distribution' of $D - \delta.$ Because $\delta$ is unknown, we use
$D_{obs}$ as a proxy.
Then we find $L* \approx L$ and $U^* \approx U$
by taking quantiles .025 and .975 of $D^* - D_{obs}.$ From there, the 95% bootstrap Ci for $\delta$ is of the form
$(D_{obs}-U^*, D_{obs}-L^*),$ where $D_{obs}$ returns to its original role.
In the R code below, we use .b instead of $*$ to indicate quantities arising from re-sampling. The 95% bootstrap CI for $\delta$ is
$(6.99, 17.29).$ This is called a nonparametric CI because the
bootstrap procedure did not involve the assumption that data are normal.
set.seed(1234);  B = 2000
D.b = replicate(B, mean(sample(x1,n1,rep=T)) -
      mean(sample(x2,n2,rep=T)) - d.obs)
d.obs - quantile(D.b, c(.975,.025))
    97.5%      2.5%
 6.991987 17.289737

Addendum (per revision of question and comment): I agree with @Dave, that the t.test
should be OK for such a large sample--even if markedly skewed.
I do not
have much experience bootstrapping huge samples,
but the bootstrap works well in the example I
show below, comparing large exponential samples with respective population means 100 and 102.
The 95% t CI is $(1.016. 2.343)$ and the 95%
nonparametric bootstrap CI is $(1.026, 2.344).$
set.seed(807)
x1 = rexp(10^5, 1/102);  x2=rexp(10^6, 1/100)
t.test(x1, x2)$conf.int
[1] 1.016061 2.343464
 attr(,"conf.level")
 [1] 0.95

set.seed(1234);  B = 2000
n1 = length(x1); n2 = length(x2)
d.obs = mean(x1) - mean(x2)
D.b = replicate(B, mean(sample(x1,n1,rep=T)) -
      mean(sample(x2,n2,rep=T))-d.obs)
d.obs-quantile(D.b, c(.975,.025))
  97.5%    2.5%
1.02571 2.34406

Comment: Does it matter that you resampled from each group separately rather than resampled the full sample and computed a mean difference within each sample? In the former, the number in each group is fixed; in the latter, the groups may have more or less in a given bootstrap sample than in the original sample.
Comment: Because the goal is a bootstrap CI of the difference between two population means, I can't see the logic in combining the two groups. (What if one population has much larger variance than the other?) // For a _permutation test_ of the difference, I might simulate the null distribution by randomly re-assigning $n_1$ of the $n_1+n_2$ observations to Gp 1 and the remaining $n_2$ to Gp 2; then computing whatever distance metric.
Comment: Thank you! Both of my samples are larger than 100k points and their distributions are skewed: values are only positive and have a long tail. This is why I hesitate to use t-test. Do you have any comments on that?
Comment: @Dave's comment is confirmed by my Addendum to the Answer.
Answer: "Difference of means is statistically significant if 95% confidence interval doesn't include 0"
Significant at the $\alpha=0.05$-level. Do specify that. If you want a p-value, you can find how big of a confidence interval you need for an endpoint of your CI to just kiss 0. But CIs and hypothesis testing have a ice duality.
I have to agree with BruceET, though. You seem to be out-clevering yourself. You would use bootstrap if you want to test something weird like $(\kappa_1^3 - \kappa_2^3)^{1/3}$ ($\kappa_1$ and $\kappa_2$ are the kurtosis of distributions 1 and 2, respectively). Then you would do your process and make inferences. But don't overthink testing means. BruceET has it right.
Comment: @Miha With that many points, t-testing is probably safe if what you want to examine is a difference in means. If you want to examine something funky about the kurtosis, then another test (such as the bootstrap procedure you described) would apply, F-test for comparing the variances, etc.
Comment: Thank you! I added details about my sample distributions (over 100k points and skewed). Would you add anything to that?


Find the maximum number of people who participated in exactly three games?

Question:
Gauri Apartment housing society organised annual games,
  consisting of three games: snooker, badminton and tennis.
  In all, $510$ people were members in the apartments'
  society and they were invited to participate in the games.
  Each person participating in as many games as he/she feels like.
  While viewing the statistics of the performance, Mr Capoor realised the following
  facts.
  The number of people who participated in at least two games
  was $52$% more than those who participated in exactly one game.
The number of people participating in $1$, $2$ or $3$ games respectively
  was at least equal to $1$.
Being a numerically inclined person, he further noticed an interesting thing:
  The number of people who did not participate in any of the three games
  was the minimum possible integral value with these conditions.
What was the maximum number of people who participated in exactly three games?

(a) $298$
(b) $300$
(c) $303$
(d) $304$
From the question I have drawn this venn diagram

and concluded that
$a+d+c+x=\dfrac{152\times (s+b+t)}{100} \\
\{s,b,t,a,d,c,x,\}\geq 1$
I don't know how to proceed.
I look for a short and simple way.
I have studied maths up to $12$th grade.
Comment: I have converted the image stating the problem to text, hoping that it would be more readable. Please confirm accurate translation and remove the picture if you so see.
Comment: The sentence "The number of people who did not participate in any of the three games was the minimum possible integral value with these conditions." is ambiguous.
Comment: If we mark $u := a+b+c$ we get equation: $u+x = 1.52*(510-x-u) $ which hasn't solution in whole numbers.
Comment: I think the condition "at least one person participated in two games"  translates to at least one of $a,b,c$ being greater than zero, not all.
Comment: Further, why is letter $b$ used (in the diagram and the equations) for two different things? Some typo?
Answer: Let $P=N_2+N_3$ count those who participated in at least two games, $Q=N_1$, those who participated in one game.
Then $$P=\frac{152}{100}Q \implies \frac{P}{Q}=\frac{38}{25}$$ Or $(P,Q)=(k\,38,k\,25)$.
The total number of players who played at least one game is $P+Q=k(38+25)=k\, 63$ (hence $k \,63\le 510$). We are told the players that didn't played is minimized, hence $P+Q$ is maximized.  The maximum $k$ is 8. And $P+Q=8 \times 63 = 504$, and $(P,Q)=(304,200)$
Now, $P=N_2+N_3=304$ We have the restriction that at least one person participated in exactly two games, i.e. $N_2 \ge 1$. Then the maximum value of $N_3$ is $304-1=303$


How do I reduce the possibilities in Mastermind based on feedback?

Question: I am following Donald Knuth's algorithm to solve the game Mastermind.
However, I am stuck on step two:

Create a set S of remaining possibilities (at this point there are
1296). The first guess is aabb.

Remove all possibilities from S that
would not give the same score of colored and white pegs if they were
the answer.

For each possible guess (not necessarily in S) calculate
how many possibilities from S would be eliminated for each possible
colored/white score. The score of the guess is the least of such
values. Play the guess with the highest score (minimax).

Go back to
step 2 until you have got it right.

I generate the set of possibilities (basically 6 x 6 x 6  x 6). From here, I formulate the initial guess of aabb. The "mastermind" gives feedback in the form of x white pegs and y black pegs.
The white pegs indicate one of the four colors in our guess was correct but in the wrong location. The black pegs indicate that one of the four colors in our guess was correct and in the correct location.
From here the next guess has to be modified based on that information.
My question is: Given that my first guess is aabb and my feedback is, say 1w1b, what permutations do I remove from the set of possibilities?
Comment: @justhalf Sorry, I removed my comments because they were wrong. Both of your answers make sense now. I didn't realize we compare the possibility to the current guess.
Comment: Do you want us to list them, or describe the set?
Comment: Or just the general pattern of how you would go about getting them.
Comment: The general pattern? Not the permutations to remove for this particular case? Do you want an algorithm or what?
Comment: @Beta, I think OP wants an algorithm
Comment: Then you're not asking step 2 (evaluating our guess), it's step 3 (create new guess)
Comment: I have tried implementing this algorithm, but it's very slow, haha. Using random guess and possibility removal seems to work faster (although not the smallest step) on general case. It can guess 6 colors 5 pegs in under 8 guesses. Or step 3 can be changed to just consider the possibility in `S` instead of everything. See my code here: http://ideone.com/CVU0oL
Comment: When you say slow do you mean your program takes a long time to run or that it takes a lot of guesses? This algorithm should always terminate in 5 guesses or fewer.
Comment: Takes a long time to run. That's why I said using random guess is "faster although not [in] the smallest step[(guess)]".
Comment: @justhalf I'm a bit curious why it's so slow - if I finish this up I'll post a link with the speed of the program.
Comment: Because it needs to use every possible combinations (6^5 * 7C2) as a guess, and count the possibility reduce, which makes the algorithm to consider all the remaining possibilities (on the first step, this is 6^5 also). So the number of operations is in the order of 6^10, which is 60,466,176. That's huge!
Answer: It's actually quite clear in the step 2. Here is the explained version.
You can go through each permutation, computes its score (like 3w, 1w3b, etc) with respect to the current guess, and removes those permutation which give different score that the actual score.
Answer: def CalcScore(answer, solution):
    """ A function that will return a tupple of the number of white & black pegs """
    ...

todel = []
for poss in poss_answers:  # Assuming that poss_answers is a list/array of possible ansers
    if not current_score == CalcScore(ThisTry, poss):
       todel.append(poss)
for delthis in todel:
    poss_answers.remove(delthis)


Como pegar a posição de um elemento  que está dentro de um SVG via Javascript?

Question: Tenho um SVG que contem, entre outros itens, um elemento <circle>.
Consigo manipulá-lo via Javascript, alterando propriedades CSS como visibility, mas não consigo pegar a posição dele na tela.
Minha ideia é que, quando o mouse passa sobre determinada
, outra
 seja exibida tendo como base a posição do <circle>.
Tentei utilizar o offsetTop, mas não funcionou.
Answer: A posição do circle é definida pelos atributos cx e cy.
<svg>
    <circle cx="50" cy="50" r="15"></circle>
</svg>

var circulo = document.querySelector('circle');
circulo.addEventListener('mouseover', function() {
    console.log(this.getAttribute('cx'), this.getAttribute('cy'));
});

http://jsfiddle.net/6L59khr6/
Essa posição é relativa à do elemento SVG.
Comment: Referente a pergunta do Dionei, nos comentários, não extamente, pois depende da proporção e escala do SVG.
Comment: Assim, para saber a distância do < circle > para o topo da tela eu teria que pegar a coordenada "cy" e depois somar com a coordenada do < svg > ?
Comment: Exatamente, Dionei.
Comment: Bom, de qualquer forma já é um caminho... Vou trabalhar nisso para resolver meu problema.
Obrigado pela ajuda.


Maximum number of iscsi connections

Question: Is there a way to increase the maximum number of iscsi connections on windows to avoid this error?
Connect-IscsiTarget : Exceeded max sessions for this initiator.
Answer: As said on the official page : the maximum iSCSI target instances per iSCSI Target Server is 256 :/
Comment: Is that for windows servers 2012 only?
Comment: No, same for 2022+
https://docs.microsoft.com/en-us/windows-server/storage/iscsi/iscsi-target-server-limits
Comment: is the problem related to number of iscsi target instance ???

Maximum number of iscsi connections


Is it ever convenient to maximize different functions of the likelihood than the logarithm?

Question: We all know that it's often much more convenient to maximize the log-likelihood rather than the likelihood to get a parameter estimate, since it amounts to the same thing by the fact that the logarithm function is continuous and strictly increasing. It ends up simplifying exponential terms, turns products into sums, has lots of other nice analytical properties, and it's often more numerically stable than maximizing the raw likelihood.
However, you could also maximize say, the cube-root of the likelihood if you were so inclined, or indeed use any other order-preserving function. Does this ever actually make any problems easier, or is the logarithm really the only game in town?
Answer: No. You do log to transform a product into a sum, which is convenient in optimization because it makes derivatives easier to deal with. The monotonicity of log is just a necessary pre-condition for such a transformation to be useful. The fact that a power function is monotonic doesn't do any service for dealing with a product.


OpenLDAP: Setting up SSL: Implementation specific error

Question: I'm trying to set up an SSL certificate that I received from Let's Encrypt. I have the 4 files from LE:

cert.pem
chain.pem
fullchain.pem
privkey.pem

Following some tutorials, I made sure that ldap user has read access to these files, copied them anywhere I saw fit, but nothing really works. All I get every time is ldap_modify: Other (e.g., implementation specific) error (80)
I tried creating a dozen kind of .ldif file to try and configure the SSL, all of them eventually threw the error message above.
The lates configuration I tried is this:
dn: cn=config
changetype: modify
replace: olcTLSCACertificateFile
olcTLSCACertificateFile: /etc/pki/tls/cert.pem
-
delete: olcTLSCACertificatePath
-
replace: olcTLSCertificateKeyFile
olcTLSCertificateKeyFile: /etc/pki/tls/private/privkey.pem
-
replace: olcTLSCertificateFile
olcTLSCertificateFile: /etc/pki/tls/certs/cert.pem

The /etc/pki/tls/cert.pem files is the one created by copying the chain.pem file to a ca-trust folder, and extracting the trusted certificates.
Comment: the strangest thing to me is that whatever order, or combination I run these commands, there is always the very same error message
Answer: The problem (which I don't fully understand) was with SELinux.
I don't really know what SELinux does apart from making my life harder, but after disabling it, the problem went away.
I, of course, understand the security risk it poses, so I enabled it back and ran the following command as my final solution, which seems to have solved the problem:
setsebool -P allow_ypbind=0 authlogin_nsswitch_use_ldap=0

I'm open to accepting answers that explain why this solution works, because this is really cloudy for me and I'd like to understand it a bit more deeply.


Python parsing set-cookie header

Question: In PHP I send one cookie with secure and http only flags, and other without
setcookie("c2","value");
setcookie("c1","value", 0, "/", "", true, true);

It produces header
Set-Cookie: c2=value, c1=value; path=/; secure; httponly

In firebug I can see, this is OK (c1 secure flag is True, c2 is False)
I want to get which one of them is not using secure flag
My python code:
cookies = Cookie.SimpleCookie()
cookies.load(headers['set-cookie'])
print cookies

Output:
Set-Cookie: c1=value; Path=/\\r\\nSet-Cookie: c2=value

headers['set-cookie'] does contain original set-cookie header, it's ok
According to python documentation printing(handling as string) SimpleCookie instance should create set-cookie header. Point is, that something is missing after parsing original header.
Morsels also contains wrong values (secure and http only).
Is this some kind of misconfiguration or it's a bug in python library ?
Thanks :)
Comment: I ended up splitting cookies by ^([^"]|"[^"]*")*?(,) regex. But more pythonic solution would be appriciated :)
Answer: This might be a bit late but saw your question and thought you may still need help.
The code I use to read a cookie is:
import Cookie,os
def getCookieData():
    try:
        cookie = Cookie.SimpleCookie(os.environ["HTTP_COOKIE"])
        session = cookie['usrSession'].value
        return session
    except (Cookie.CookieError, KeyError):
        return None

My cookie string its something along the lines of:
Cookie: usrSession=12345

Hope this helps
Comment: You are parsing the cookie header sent with an HTTP request.  But the question is about how to parse the Set-Cookie header returned with an HTTP response.

Python parsing set-cookie header