Thread not stopped while communicating with external modul

Question: I'm developing an application that use an external device to communicate with an electronic board using USB protocol. When I want to display results obtained during communication inside TextBlock an error msg appears saying

The calling thread cannot access this object because a different thread owns it

How could I stop this thread or print the appropriate info in my textblock?
Here the code used :
<code>    /// ******************************************************************
    /// <summary>
    /// RX_Thread
    ///
    /// Description:
    /// Second thread which receives data from configured receive port
    /// (CANDemo_RxChannel)of XL interface.
    /// </summary>
    /// ******************************************************************
    #region EVENT THREAD (RX)
    public  void RX_Thread()
    {
        // object to be fill with received data
        XLClass.xl_event receivedEvent = new XLClass.xl_event();

        // result of XL driver func. calls
        XLClass.XLstatus xlStatus = XLClass.XLstatus.XL_SUCCESS;

        // WaitForSingleObject values
        WaitResults waitResult = new WaitResults();

        // note: this thread is destroyed by MAIN
        while (true)
        {
            // wait for hardware events
            waitResult = (WaitResults)WaitForSingleObject(CANDemo_RxChannel.eventHandle, 1000);

            // if event occured...
            if (waitResult != WaitResults.WAIT_TIMEOUT)
            {
                // ...init xlStatus first
                xlStatus = XLClass.XLstatus.XL_SUCCESS;

                // afterwards: while hw queue is not empty...
                while (xlStatus != XLClass.XLstatus.XL_ERR_QUEUE_IS_EMPTY)
                {
                    // ...receivedata from hardware queue
                    xlStatus = CANDemo_RxChannel.xlReceive(ref receivedEvent);

                    //  if receiveing succeed...
                    if (xlStatus == XLClass.XLstatus.XL_SUCCESS)
                    {
                        // ...print rx data
                        string BigContained = CANDemo.XL_GetEventString(receivedEvent);
                        //GetInfo(BigContained);
                       // ((XLClass.xl_event)xlEventCollection.xlEvent[0]).tagData.can_Msg.id = 0x74D;
                        if (receivedEvent.tagData.can_Msg.id == 0x76D)
                        {
                            if (receivedEvent.tagData.can_Msg.data[0] == Convert.ToByte(2) && receivedEvent.tagData.can_Msg.data[1] == Convert.ToByte(80) && receivedEvent.tagData.can_Msg.data[2] == Convert.ToByte(250))
                            {
// i want to writ the data in my Texbloxk but i get error :
                                    txtframeContainer.Text = "Enter in diagnostic mode   SupplierSpecific --> Ok ";
                            }
                        }
                    }
                }
            }
            // no event occured
        }
    }
    #endregion
    /// ------------------------------------------------------------------
</code>
waiting for your feedback guys...
Comment: here some additional data of error obtained :
Comment: at System.Windows.Threading.Dispatcher.VerifyAccess()
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Controls.ContentControl.set_Content(Object value)
   at RelevantInfo.MainWindow.RX_Thread() in C:\Users\barras\Desktop\who knows\RelevantInfo\RelevantInfo\MainWindow.xaml.cs:line 219
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback,
Comment: Please _edit_ your question when you want to add information.
Comment: Also, your question title has very little to do with your problem.
Answer: You can only update the ui from your ui thread, so if you update a ui object you have to get the ui thread and invoke the update on that thread:
<code>if (Application.Current.Dispatcher.CheckAccess())
{
     txtframeContainer.Text = Result;
}
else
{
    Application.Current.Dispatcher.Invoke((Action)(() =>
    {
        txtframeContainer.Text = "Enter in diagnostic mode   SupplierSpecific --> Ok ";
    }));
}
</code>
Comment: thank you thats work as magic here what i have used :         private void YourMethod(string Result)
        {
            if (Application.Current.Dispatcher.CheckAccess())
            {
                textBox1.Text = Result;
            }
            else
            {
 access
                Application.Current.Dispatcher.Invoke(new System.Action(() => YourMethod(Result)));
            }
        }
Comment: yes thats it , thanks man ;)
Answer: This error will be caused by you trying to update a UI control on a thread that is not the UI thread.
Have a look at this question: How to update the GUI from another thread in C#? it should give you the answer


Prime Number test in java

Question: public static boolean isPrime(int number)
{
  boolean result = true;

  if (number == 0)
  {
     result = false;
  }

  for (int i=2; i < number/2; i++)
  {
     if (number % i == 0)
     {
        result = false;
     }
  }

  return result;
}

Any ideas why when int number = 4, the result returns as true? What can I do to fix this? I am happy with the code I have but why does 4 return as true?
Comment: if `number` is 4, how many times does the for-loop execute?
Comment: 1. Do not set default value of `result` as `true`. For `4` the for loop will not execute so you are returning the default value of `result` which is `true`
Comment: Can't you just do it on pen and paper? Take `number = 4`. Then `i = 2`. Then `number % i = ...`.
Comment: @SotiriosDelimanolis that is exactly what does not happen.
Comment: @arunmoezhi if you don't set the default value to `true`, no number will ever be reported as prime.
Comment: @Sneftel: exactly. But it is a good programming practice to set it to false and modify the logic according to it. It it better to give red lights at all corners rather than giving green lights to all corners.
Comment: @arunmoezhi That doesn't make any sense. Primality testing (as implemented here) is based on the failure to find integer factors, and that for-loop is iterating over possible integer factors.
Comment: `as implemented here`. I suggested to change the implementation
Answer: for (int i=2; i < number/2; i++)

If you enter 4 here, it will never enter the loop because
2 < 4 / 2

never equates to true (2 is not smaller than 2).
Instead, use <=.
Comment: Pretty sure you can do `(int)Math.sqrt(number)` instead of `number/2` : )
Answer: Effective way how to do this method is :
(sorry for duplication, but after some time, someone can find this topic and not previous one)
public static boolean isPrime(int number) {
    //Everything less or equal 1 is not prime number
    if (number <= 1) {
        return false;
    }

    //2 is very special case, so I check it separately
    if (number == 2) {
        return true;
    }

    //This will help me rid off all even numbers
    if (number % 2 == 0) {
        return false;
    }

    //It is important to count the sqrt before using it in for-loop condition.
    //If you use it in for-loop condition, it will be counted every single iteration.
    int square = (int) Math.sqrt(number);

    //I already checked %2, so now I need to check only odd numbers
    for (int i = 3; i <= square; i += 2) {
        if (number % i == 0) {
            //If I find one number, I do not have to continue
            return false;
        }
    }
    return true;
}

Comment: Or even add an extra check for 3 as factor and use then `for (int i = 5, d=2; i <= square; i += d, d=6-d) {` to only check for factors that are neither divisible by 2 nor by 3. This is the [2-3-wheel](https://en.wikipedia.org/wiki/Wheel_factorization). Also in use are 2-3-5 and 2-3-5-7 wheels.
Answer: Your for loop never executes when number = 4. This is because:
for (int i=2; i < number/2; i++)

Executes when i == 2 and i < 2. That will never happen if number == 4, because then it'll be i < 4 / 2 which is i < 2. To solve this, remove the /2 or do something else... not quite sure what you're going for there.
Answer: When number==4 the boolean condition of the first if is false and the first evaluation of the for condition is also false. So the result is the value you used to initialize result (true).
Answer: Also, you might want to return the result instead of storing it in a variable because the code will continue to execute after the first conditional... So here is the working solution:
public static boolean isPrime(int number) {
  if (number <= 1) { /* Since 1 isn't technically a prime number */
     return false;
  }

  for (int i=2; i <= number/2; i++) {
     if (number % i == 0) {
       return false;
     }
  }
  return true;
}

Comment: @libik: why doesn't it?
Comment: 1 is not prime, so <= 1 will return false :)
Answer: Better and faster version of your code:
public static boolean isPrime(int number) {
        if (number <= 1) {
            return false;
        }
        for (int i=2; i*i <= number; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }

Answer: Another solution:
public static boolean isPrime(int number) {
    if (number < 2) {
        return false;
    }

    for (int i=2; i <= (int)Math.sqrt(number); i++) {
        if (number % i == 0) {
            return false;
        }
    }

    return true;
}

Prime Number test in java


Riemann surface arising as a quotient of the upper half-plane.

Question: Let $H$ be the upper half-plane $\{z \in \mathbb C \mid \Im(z) > 0\}$. For a fixed real $\lambda > 0$, let be the automorphism $$d_\lambda : H \to H, z \mapsto \lambda z .$$
Denote $\Gamma$ the subgroup of $\mathrm{Aut(H)}$ generated by $d_\lambda$. The goal is to determine the Riemann surface $H/\Gamma$.
Let's discard the trivial case $\lambda=1$. [Edit, false : $H/\Gamma$ is open as the open set $\{ z \in H \mid |z|<1 \}$ is a fundamental domain of the holomorphic projection.] One have $\pi_1(H/\Gamma) \simeq \Gamma \simeq \mathbb Z$. Hence, as no compact Riemann surface has $\mathbb Z$ as fundamental group, $H/\Gamma$ must be an open Riemann surface.
As I don't know a lot of open Riemann surfaces, I'm tempted to test $\mathbb C^\ast$ and the punctured unit disk $\mathbb D^\ast$ that matches those properties. But $\mathbb C^\ast$ has universal cover $\mathbb C \not\simeq H$, and so $H/\Gamma \not\simeq \mathbb C^\ast$. This leaves me with $\mathbb D^\ast$. How can I show that $H / \Gamma$ is (or isn't) biholomorphic to $\mathbb D^\ast$ ? If it isn't, does this quotient look like a well-know surface ?
P.S. Does that kind of quotient have a name ? I'm aware of the name of modular curve when $\Gamma$ is a subgroup of $PSL(2,\mathbb Z)$ which is not the case here.
Comment: Don't you require a fundamental domain to contain unique representatives of an orbit? In my view, $\{z ∈ H;\; 1 < |z| < λ\}$ is a fundamental domain for $λ > 1$.
Comment: For $λ = 1$ isn't $d_λ = \operatorname{id}$, so $Γ_λ = \{\operatorname{id}\}$ and $H/Γ_λ = H$? Edit: Oh, I think I misinterpreted your paragraph beginning with "Let's discard …". My bad, nevermind. … No, I didn't? You claim $\{z ∈ H;; |z| < 1\}$ to be a fundamental domain. This isn't true?
Comment: I think, you think $〈d_λ〉 = \{d_{kλ};\; k ∈ ℤ\}$, but it really is $\{d_{λ^k};\; k ∈ ℤ\}$. Note that $d_λ ∘ d_λ = d_{λ^2}$.
Comment: Yes the case $\lambda=1$ is trivial and $H/\Gamma = H$ then. By _discarding_ it, I meant that I now suppose $\lambda \neq 1$. Then every $z_0 \in H$ as a equivalent one in $\{z \in H : |z| < 1\}$ as $(\lambda^{-k}z_0)_{k \geq 0}$ or $(\lambda^{k}z_0)_{k \geq 0}$ converge to $0$ in $\mathbb C$. Right ? (Actually, every neighborhood of $0$ in $\mathbb C$ intersected with $H$ is a fundamental domain.)
Comment: Oh sorry, I just meant a set $U$ such that $p(U) = H/\Gamma$ (with $p$ the projection $H \to H/\Gamma$). But I just realize that it does not show that $H/\Gamma$ is not compact. However, it seems to be true because of the fundamental group being isomorphic to $\mathbb Z$.
Comment: The quotient is in fact not compact. It's $S^1 × (0,π)$.
Comment: Yes, ok, I see it now, thanks. Have you a hint about if it is biholomorphic to $\mathbb D^\ast$ ? (It is clearly homeomorphic to it.)
Comment: @Pece: I added some tags to your question to draw more users' attention. If you don't like that please feel free to roll back.
Answer: Without loss of generality, assume that $\lambda>1$. Then $\mathbb{H}/\Gamma$ is biholomorphic to the annulus
$$A(\lambda):=\{z\in\mathbb{C}\mid e^{-\frac{2\pi^2}{\log\lambda}}<|z|<1\}.$$
To see this, let us fix a branch of the logarithm function on $\mathbb{H}$ as follows:
$$\log(re^{i\theta})=\log r+i\theta,\quad~\forall r>0,~ \theta\in(0,\pi)~.$$
Define
$$f:\mathbb{H}\to \mathbb{C},\quad z\mapsto e^{\frac{2\pi i\log z}{\log \lambda}}.$$
By definition, $f$ is holomorphic. It is easy to verify that $f(\mathbb{H})=A(\lambda)$ and  $f:\mathbb{H}\to A(\lambda)$ is a covering map with deck transformation group $\Gamma$. Since $\mathbb{H}$ is simply connected, the conclusion follows.

Remark: On the one hand, the generator $d_\lambda\in Aut(\mathbb{H})$ of $\Gamma$   is hyperbolic. When considered as an element in $PSL(2,\mathbb{R})=SL(2,\mathbb{R})/\{\pm I\}$, the conjugate class of $d_\lambda$ is uniquely determined by $(\mathrm{tr}~d_\lambda)^2$. On the other hand, up to biholomorphic equivalence, a hyperbolic Riemann surface with fundamental group $\mathbb{Z}$ is uniquely determined by its modulus. For $\mathbb{H}/\langle d_\lambda\rangle\cong A(\lambda)$, there is a $1$-$1$ correspondence between $(\mathrm{tr}~d_\lambda)^2$ and the modulus of  $A(\lambda)$.
Comment: @Pece: You are welcome. Please be noted that the generator of $\Gamma$ in your comment is called [parabolic](http://en.wikipedia.org/wiki/M%C3%B6bius_transformation#Parabolic_transforms), but the one in your question is called [heperbolic](http://en.wikipedia.org/wiki/M%C3%B6bius_transformation#Hyperbolic_transforms). These are two different types of Möbius transformations with different geometric features.
Comment: Thanks, it seems to solve the question. Knowing the covering map $H \to \mathbb D^\ast, \, z \mapsto e^{2i\pi z}$ (for the case $\Gamma = \{z \mapsto z+k : k \in \mathbb Z\}$), I was trying to get something similar but invariant under the described $\Gamma$ without success. Your $f$ does the job !
Comment: @Pece: For further reference, I added a remark in my answer.
Answer: Partial answer:
Let $f \colon H → ℂ^1 × (0,π), z ↦ (e^{2πi·\log_λ |z|},\operatorname{Arg}(z))$, where $ℂ^1$ is the unit circle.
This map is surjective, open, continuous, and $f(z) = f(z') ⇔ Γ_λ z = Γ_λ z'$, because:

Any $(e^{2πiα},θ)$ in $ℂ^1 × (0,π)$ is hit by $λ^α·e^{2πiθ} ∈ H$.
It's a composition and product of open and continuous maps.
$∃k ∈ ℤ:\, \log_λ |z|  = \log_λ |z'| + k ⇔ |z| = λ^k|z'|$, so:
$f(z) = f(z') ⇔ \big(\operatorname{Arg}(z) = \operatorname{Arg}(z') ∧ ∃k ∈ ℤ:\, \log_λ |z|  = \log_λ |z| + k\big) ⇔ ∃k∈ℤ:\, z = d_{λ^k}z'$.

This implies that topologically $H/Γ \cong ℂ^1 × (0,π)$.
Comment: Also, one easily has $ℂ^1 × (0,π) \cong π D^*$, but I don't know if one can combine these maps to get an isomorphism of Riemann surfaces.


where is the Qt designer app loaded on my system?

Question: I loaded QtPy5 and QtPy5-tools successfully using pip on VSCode. But I cant for the life of me find it on my system.
Is it an .exe program?
where should I be looking please and what is it called
TIA
Comment: "successfully using pip on VSCode." Then it installs to the same place that `pip` installs everything else. It could be that there are multiple versions of Python on your system, in which case there can be multiple `pip`s; you will need to make sure of which one VS Code used (it will correspond to the Python that VS Code is using).
Answer: you just hold ctrl key and move your cursor on the QtPy5 and then click it it should take you the the file location of the QtPy5. i think this should work.


How do I combine a standalone c application into a c++ one?

Question: I was working on a C++ app (call it recorder.cpp) that includes some C++ libraries from elsewhere (which have to use c++14, so I am stuck on that front).  Currently my app is working, but it is just doing configuration based off of the external libraries and command line arguments.
There is a separate C app (call it receiver.c) that works independently that I basically want to combine with recorder.  I think the easy way would be to copy and paste all of receiver into recorder, but that seems a bit redundant (not to mention if I make mods to receiver in the future, I will need to then make the same changes in recorder).  So I was trying to figure out if there is a way to link them so that I can call receiver from the recorder app.  I know that I can't just call receiver's main(), but I wasn't sure if there was a way to build receiver so that it acts more like a library yet still can be built as its standalone app.
Comment: Most operating systems have ways of executing arbitrary programs.
Comment: @ryyker Yes the text inside the main body seems to indicate it, which then seems conflicts with the title.
Comment: @Someprogrammerdude - I believe the question is more about including `C` source in `c++` code, not running a compiled executable.
Comment: @Someprogrammerdude - Yeah, I guess I wasn't very clear.  I would think that the more elegant solution would be the "linking" version, but maybe the direct call is the way to go. I need to research ryyker's answer some more.
Comment: If linking `receiver` and `recorder` into a single executable, note that you can't have two `main` functions in the same executable, so you will have to work around that somehow if you need to call `receiver`'s `main` function from `recorder`, for example by renaming `receiver`'s `main` function using a preprocessor macro.
Comment: Since you are really talking source code, have you considered just removing the main() function and including the rest of the `C` code as part of the `C++ compile?
Comment: @ryyker After playing with this some, reading on the net and all the comments/answer (and my unclear issue), I think that this might be the easiest approach. I guess we should probably close the question. Thanks to all though.
Answer: "...I was trying to figure out if there is a way to link them so that I can call receiver from the recorder app."
Yes - But the simpler, more direct way is to copy the reciever.c code (minus its main() function) in with the C++ code. This would require that there is no syntax in the C code that would violate C++ rules. (eg. casting the return of malloc() for example is required in C++, but is not recommended in C.)  But because most C syntax is completely C++ compatible, there should be little or no modifications necessary.  Now all your code is together, and can be simply compiled as C++.
The linking approach however, would require compiling all of the functions of your stand-alone program (again, leaving out the main() function into a library.  eg a DLL or shared library.  That library can be linked using  extern "C" { ... } within theC++ header file to surround the C function prototypes that are defined in the C library file. Those functions in the surround will be compiled with C linkage rather than C++.  A brief example:
    // C++ code
    extern "C" void f(int); // one way
    extern "C" {    // another way
        int g(double);
        double h();
    };
    void code(int i, double d)
    {
        f(i);
        int ii = g(d);
        double dd = h();
        // ...
    }

Reproduced from here...
Note, included in link is this statement: "...In addition, you'll need to read the rest of this section to find out how to make your C functions callable by C++ and/or your C++ functions callable by C."
EDIT to add information from comments:
Regarding creating a library.  The library could then be used by both programs and not maintained in two places. This would complicate versioning and there could be future issues if the 2 programs diverge in the future. Also note that using a static rather than shared library is also possible. These approaches have different versioning implications as future changes happen.  (from @Avi Berger)
...Or, if your intent is to have a common *.c file so changes made for one app are easily included in the other, you don't make a library but simply link in the .o file.  (from @Goswin von Brederlow)
Comment: Better to compile the C code as a separate source module. Most C++ IDEs and makefiles should allow this. Then use `extern "C"` to get access to the C functions from the C++. If that is what the OP actually wants.
Comment: Or you don't make a library but simply link in the .o file. I think the OPs main point was to have a common *.c file so changes made for one app are easily included in the other.
Comment: But that is for calling a function, not the whole application right?
Comment: @ryyker You can, but it doesn't compile the code as C it compiles it as C++, which might make a difference. Only the function signatures are "C" style.
Comment: @GemTaylor - If that is what is needed, yes.  But text in OP seems to indicate otherwise.
Comment: @toozie21 - _But that is for calling a function,_ Yes, when using `extern "C" { ... }`, it will include what ever function declarations included in the curly braces.  So anything inside will be declared some to be of "C" linkage, rather than "C++"
Comment: @ryyker OK, but I think I am missing something. I had skimmed through your link before I posted that comment because it still didn't seem to cover the scenario. I realize that I seem to be unintentionally asking un-clear questions. I understand what you are describing, but if I do ```extern "C" {int main(int argc, char *argv)};```, I unclear how ```recorder``` will know the difference between its out main() and ```receiver```'s <> I wrote this the same time as Ian's comment in my original question, his comment is exactly my concern.
Comment: @toozie21- Please see edits to clarify .  Sorry for the unclear language.  Keep in mind the most common way this is used is to surround library function decalrations in a `C++` header file that you what to compile with `C` linkage rather than `C++`.
Comment: You might explicitly note that the library could then be used by both programs and not maintained in two places. This would complicate versioning and there could be future issues if the 2 programs diverge in the future. Also note that using a static rather than shared library is also possible. These approaches have different versioning implications as future changes happen.
Comment: @AviBerger - That is a good point, I have quoted you in the answer.
Comment: @GoswinvonBrederlow - Also a good point, have quoted you in the answer.
Comment: Another note. The C app should probably provide a .h file. And you can't have `extern "C" {}` in C code. The .h file should use `#ifdef __cplusplus`.
Comment: @GoswinvonBrederlow - generally I would expect that the `C` function prototypes needed would be added (copied from the original) to the C++ header, surrounded with the `extern "C"` modification.  That is how I have always done it.  This is simpler.  There are many variations possible.  The basic question _can it be done_ has been answered sufficiently. I think.
Answer: Just compile the object files recorder.o and receiver.o in the usual way.  Make sure they don't both have a main() function: either #ifdef it out conditionally, or (better) compile it in its own object file for each program (e.g. recorder_main.cpp and receiver_main.c).
With this latter approach, the Makefile is quite simple, as we can let Make use its built-in rules to make the object files correctly.  All we have to do is tell it how to link:
receiver: receiver_main.o receiver.o
        $(LINK.o) $^ $(LDLIBS) -o $@

recorder: recorder_main.o recorder.o receiver.o
        $(LINK.cc) $^ $(LDLIBS) -o $@

Notice that we need to link recorder with the C++ linker (that understands name mangling) rather than the C linker.
If you want separate source directories, that's easily managed using a VPATH in the Makefile.


Every compact manifold with fundamental group $ \mathbb{Z} $ is a mapping torus

Question: Suppose that $ M $ is the mapping torus of some homeomorphism of a manifold $ F $. Then $ M $ is a fiber bundle with fiber $ F $ and base space $ S^1 $
$$
F \to M \to S^1
$$
So if $ F $ is connected and simply connected then by LES homotopy we have
$$
\pi_1(M) \cong \pi_1(S^1) \cong \mathbb{Z}
$$
Let $ M $ be a compact $ n $ dimensional manifold with fundamental group $ \pi_1(M) \cong \mathbb{Z} $. Is it true that $ M $ must be the mapping torus of a compact connected simply connected $ n-1 $ dimensional manifold?
My thoughts so far:

True for $ n=1 $ because $ S^1 $ is a mapping torus for the point.
True for $ n=2 $ because there are no compact simply connected 1 manifolds so there are no compact 2 manifolds with fundamental group $ \mathbb{Z} $
True for $ n=3 $ since the only compact simply connected 2 manifold is the sphere $ S^2 $ and indeed the only 3 manifolds with fundamental group $ \mathbb{Z} $ are the trivial mapping torus $ S^2 \times S^1 $ and the mapping torus of the antipodal map (these are the only two possible mapping tori for $ S^2 $). For example see What closed 3-manifolds have fundamental group $\Bbb Z$?

I expect this already fails for $ n=4 $ and almost certainly fails for generic $ n $. But I figured it couldn't hurt to ask.
Comment: Of course not, already in dimension 4: Use a nontrivial connected sum of your favorite simply connected 4-manifild with your favorite mapping torus of the 3-sphere.
Answer: Let $F$ be a path-connected topological space and $\phi : F \to F$ a homeomorphism. Denote the mapping torus of $\phi$ by $M$ so that we have a fiber bundle $F \to M \to S^1$. Explicitly, $M = F\times[0, 1]/\sim$ where $(x, 0) \sim (\phi(x), 1)$. From the long exact sequence in homotopy, there is a short exact sequence $$0 \to \pi_1(F) \to \pi_1(M) \to \pi_1(S^1) \to 0.$$ The covering space of $M$ corresponding to the image of $\pi_1(F)$ in $\pi_1(M)$ is homeomorphic to $F\times\mathbb{R}$. This follows from the fact that $M$ can be constructed as the quotient of $F\times\mathbb{R}$ by the $\mathbb{Z}$-action generated by $(x, t) \mapsto (\phi(x), t + 1)$. In particular, the universal cover of $M$ is homeomorphic to $\widetilde{F}\times\mathbb{R}$ where $\widetilde{F}$ is the universal cover of $F$.
Suppose now that $F$ is a closed $(n-1)$-manifold, so that $M$ is a closed $n$-manifold. If $\pi_1(M) \cong \mathbb{Z}$, then $\pi_1(F) = 0$ by the short exact sequence above. As suggested by Moishe Kohan, let $N = M \# X$ where $X$ is a closed simply connected $n$-manifold, then $\widetilde{N}$, the universal cover of $N$, is homeomorphic to the connected sum of $\widetilde{F}\times\mathbb{R} = F\times\mathbb{R}$ and countably many copies of $X$. If $H_k(X; \mathbb{Z}) \neq 0$ for some $0 < k < n$, then it follows from Mayer-Vietoris that $H_k(\widetilde{N}; \mathbb{Z}) \cong H_k(\widetilde{F}; \mathbb{Z})\oplus\bigoplus_{i\in\mathbb{Z}}H_k(X)$; in particular, $H_k(\widetilde{N}; \mathbb{Z})$ is not finitely generated. As $\pi_1(N) \cong \pi_1(M) \cong \mathbb{Z}$, if $N$ were a mapping torus, the fiber $F'$ would be a closed simply connected manifold, so $\widetilde{N}$ would be homeomorphic to $\widetilde{F'}\times\mathbb{R} = F'\times\mathbb{R}$ which has finitely generated homology. Therefore $N$ is not a mapping torus. Note, if $H_k(X; \mathbb{Z}) = 0$ for all $0 < k < n$, then $X$ is a simply connected homology sphere and hence homeomorphic to $S^n$, in which case $N$ is homeomorphic to $M$ (which is a mapping torus).
I believe that the hypothesis $\pi_1(M) \cong \mathbb{Z}$ is unnecessary, but the proof above only extends to the case where $\pi_1(M)$ is an extension of $\mathbb{Z}$ by a finite group, i.e. $F$ has finite fundamental group.
Comment: Very nice.  I agree with Moishe's that this is an obvious place to look for counterexamples, but I didn't really that *all* non-trivial (ie., $X$ is not homeomorphic to $S^n$) examples became a counterexamples!
Answer: Just posting this edit as an answer instead since there is nothing else to say here. All credit to Moishe Kohan:
I see. Thanks Moishe Kohan. I guess this is a good general lesson that too much of my intuition about topology is from dimension $ n \leq 3 $ in those dimensions (almost) everything can be determined from fundamental group. In dimension 2 and 1 manifolds are homeomorphic if and only if they have same fundamental group. This is almost true for dimension 3 as well. For example given $ \pi_1 $ for an orientable 3 manifold we can find all the homology and cohomology up to 3. Moreover, in dimensions 3 and under the only compact connected simply connected manifold is the sphere. So we can expect information about the fundamental group to be able to tell us very strong things about a manifold. But in dimension 4 and up there are lots of things other than the sphere that are compact connected simply connected (for example $ K_3 $ surface) and taking connected sum with any of those will give a manifold with same fundamental group but otherwise a totally different topology. So knowing only that a manifold is compact and has $ \pi_1 \cong \mathbb{Z} $ we should not expect to be able to show anything as strong as that it must be a mapping torus (at least not in dimension 4 and up).
Comment: Do you know why Moishe Kohan's construction gives examples of manifolds with fundamental group $\mathbb{Z}$ which are not a mapping tori? If so, you should include an explanation in your answer.
Comment: @MichaelAlbanese To be honest no. My best idea is take something simple like $ M=S^3 \times S^1 \#\mathbb{C}P^2 $ and show that it can't be mapping torus of any 3 manifold $ N $ bc LES homotopy would imply that all $ \pi_n(M) \cong \pi_n(N) $ for all $ n \geq 2 $. And then use some fact like every 3 manifold $ N $ has higher homotopy groups with property XYZ to show a contradiction. I texted all that to my friend Keith ( he's a real topologist just posted his first preprint here! https://arxiv.org/abs/2201.071760 ) and I think he's going to come post an actually good answer
Comment: If not, I can post an answer.
Comment: @MichaelAlbanese That would be lovely go for it!


Testing the goodness-of-fit of a random distribution to a parametric distribution

Question: I have a problem with a goodness-of-fit question.. I have this question I need to answer but I have no idea how:
Why do we need to test the goodness-of-fit of a distribution of a random phenomenon to a parametric distribution (one where the distribution is known)?
I had the observations of a random variable of a completely random phenomenon, and I tested whether it fits the gamma distribution with a chi-square test. However, I have no idea how to explain why I needed to do that...
Could anyone give me a hint, please?
Comment: Could it just be a compulsion you have, like some people obsessively wash their hands a lot?  But seriously, give *us* a hint why you felt you needed to.  It's either because knowing the population distribution would be interesting in itself or because a gamma distribution is an necessary assumption for some further analysis.
Comment: No, I'm working on some homework and there is this question..
Comment: What was the homework problem exactly? To do the fitting or to explain why? And what is a "completely random phenomenon"? Different random phenomena will match different distributions (e.g. rolling one die - uniform distribution)
Comment: The homework problem was finding the distribution of the magnitude of earthquakes. I performed a few statistical tests on distribution approximations (a goodness-of-fit for gamma) - (all of which were rejected), and then there was a question that asked why would we approximate the distribution of a random phenomenon with a known distribution.
Answer: Hints:
(a) Sometimes the population distribution is of interest in itself - the data-generating mechanism gives insight into the phenomenon behind the data.  The gamma distribution is a nice example - read up on it, paying attention to its relation with the exponential distribution.
(b) When you're modelling, carrying out hypothesis tests, or whatever, there are often distributional assumptions which while not of primary interest are necessary for the validity of parameter estimates or p-values. The gamma distribution is often used in survival/reliability analysis - check that out.
Comment: Thanks, that's what I thought but I wasn't sure..


.htaccess rewrite rule does not match first occurrence

Question: URL Format:
www.example.com/categ-id-title.html
www.example.com/news-1234-something-happened-in-2015-and-blabla.html

I tried to use a rewriteRule in .htaccess file, but it matches the second occurrence (-2015-) and not the first, the one I need (-1234-).
rewriteRule ^(.*)-([0-9]+)-(.*).html index.php?page=news&categ=$1&id=$2&title=$3 [L]

How could I force Apache to get the first occurence?
Answer: You can use:
rewriteRule ^(.*?)-([0-9]+)-(.*)\.html index.php?page=news&categ=$1&id=$2&title=$3 [L]

Answer: It is because .* is oto greedy, you can use this regex:
RewriteRule ^([^-]*)-([0-9]+)-(.*)\.html$ index.php?page=news&categ=$1&id=$2&title=$3 [L,QSA]


Jquery toggle show/hide fields

Question: Hi I would like to offer a toggle show/hide for some fields that are not mandatory. Is there is a modules for this or would it be a case of using a template and jquery.
Comment: jQuery will well for this:

(function($) {
  $(document).ready(function() {
    $('#select1').change(function() {
      switch ($(this).val()) {
        case '1':
          $('#field2').hide();
          break;
        default:
          $('#field2').show();
          break;
      }
    });
  });
}) (jQuery);
You can also try Conditional Field module but it is in development.
Comment: why you put shyghar answer as accepted answer? his answer  have not any mention of jquery.
Comment: the person who added the jquery answer, did it whilst I was reading the other answers, and then deleted it after I marked the answer.
Answer: You can put the not mandatory field in a group installing Field Group.
The group have a 'collapsible' option.
Answer: You can Put your fields toghether with Field Group Module ,and after it you can show/hide it(field groups) by custom jquery code.

Jquery toggle show/hide fields


Django rest Ecommerce category and product offers

Question: I'm trying to acheive catgeory and product offers in my project and am unable to come up with a solution. Like if i give offer to a category all products price in category should get the offer and for products its individual.
class Category(models.Model):
    category_name = models.CharField(max_length=15, unique=True)
    slug = models.SlugField(max_length=100, unique=True)

    class Meta:
        verbose_name_plural = "Category"

class Products(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    product_name = models.CharField(max_length=50, unique=True)
    slug = models.SlugField(max_length=100, unique=True)
    description = models.TextField(max_length=500)
    price = models.IntegerField()
    images = models.ImageField(upload_to="photos/products")
    images_two = models.ImageField(upload_to="photos/products")
    images_three = models.ImageField(upload_to="photos/products")
    stock = models.IntegerField()
    is_available = models.BooleanField(default=True)
    created_date = models.DateTimeField(auto_now_add=True)
    modified_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = "Products"

    def __str__(self):
        return self.product_name

class CategoryOffer(models.Model):
    category = models.OneToOneField(Category, on_delete=models.CASCADE, related_name='cat_offer')
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.category.category_name

class ProductOffer(models.Model):
    product = models.OneToOneField(Products, on_delete=models.CASCADE, related_name='pro_offer')
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
        validators=[MinValueValidator(1), MaxValueValidator(100)]
    )
    is_active = models.BooleanField(default=False)

    def __str__(self):
        return self.product.product_name

So above are my models. I don't know how to implement, thought of many ways but it keeps leading to errors.
Answer: You are using separate models for Categoryoffer and Productoffer. Make an Offer model with the following field:
class Offer:
    name = models.CharField()
    valid_from = models.DateTimeField()
    valid_to = models.DateTimeField()
    discount = models.IntegerField(
               validators=[
                   MinValueValidator(1),
                   MaxValueValidator(100)
               ])
    is_active = models.BooleanField(default=False)

Now use the foreign key in your category and product models:
class Product:
    offer = models.ForeignKey(Offer)

Comment: So if the offer will be FK, shouldn't that be mandatory to enter everytime i add a product?
Comment: Refer to this for giving foreign key null: https://stackoverflow.com/questions/16589069/foreignkey-does-not-allow-null-values


How to reuse code

Question: So this is my reminder app screen shot, as you can see it has a + button and also a button. When the + button is cliked, a dialog with editText will be displayed.

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add_task:
                mClickedPosition = -1;
                final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                View promptView = getActivity().getLayoutInflater().inflate(R.layout.dialog_with_edittext, null);
                Button cancel = (Button) promptView.findViewById(R.id.cancelBtn);
                Button save = (Button) promptView.findViewById(R.id.okBtn);
                task = (EditText) promptView.findViewById(R.id.task);
                time = (EditText) promptView.findViewById(R.id.time);
                date = (EditText) promptView.findViewById(R.id.date);
                final AlertDialog alert = builder.create();
                date.setOnClickListener(this);

                time.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        Fragment fragDialog = getActivity().getSupportFragmentManager().findFragmentByTag("TimePicker");
                        if (fragDialog == null) { // Fragment not added
                            FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                            tp.show(ft, "TimePicker");
                        } else {
                            // already active
                        }
                    }
                });

                cancel.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        alert.dismiss();
                    }
                });

                save.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        String addTask = task.getText().toString();
                        String time1 = time.getText().toString();
                        String date1 = date.getText().toString();
                        if ((time1.trim().equals(""))|| (date1.trim().equals("") )|| (addTask.trim().equals(""))) {
                            Toast.makeText(getActivity(), " Not Completed", Toast.LENGTH_SHORT).show();
                        }
                        else {
                            if (adapter != null) {
                                if (mClickedPosition == -1) {
                                    adapter.add(iD, addTask, time1, date1);
                                    insertTask(addTask, time1, date1);
                                    listview.setAdapter(adapter);
                                    alert.dismiss();
                                    check();
                                    retrieveList(name);
                                }
                            }

                            Calendar alarm = Calendar.getInstance();
                            Calendar copy = (Calendar) alarm.clone();
                            alarm.set(Calendar.YEAR, year1);
                            alarm.set(Calendar.MONTH, month1);
                            alarm.set(Calendar.DAY_OF_MONTH, day1);
                            alarm.set(Calendar.HOUR_OF_DAY, hour1);
                            alarm.set(Calendar.MINUTE, min1);
                            int result = alarm.compareTo(copy);

                            if(result < 0) {
                                alarm.add(Calendar.DATE, 1);
                            }
                            else
                            {
                                Intent myIntent = new Intent(getActivity(), MyReceiver.class);
                                pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
                                AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
                                alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
                            }
                        }
                    }
                });

                alert.setView(promptView);
                alert.show();
                return true;

If the button is clicked, it will open dialog exactly same as the + button. My question now is, is there a way I can reuse the code so the code will look a bit shorter,  or I have to copy the code and paste to button onClick ?
Show you my full code of the activity. As you can see, most of the code are the same (+button, button and also the listView click)
http://pastebin.com/HEKcmVK3
Comment: What about using DialogFragment?  If you use it you can call it from both buttons
Answer: You need to do it by create a custom dialog class and write the view method.
And then in both + and button click, create an instance of that class and show it.
Comment: check my post again
Answer: You can create a method of this part of code and then just call the method inside the onclicklistener
String addTask = task.getText().toString();
String time1 = time.getText().toString();
String date1 = date.getText().toString();
if ((time1.trim().equals(""))|| (date1.trim().equals("") )|| (addTask.trim().equals(""))) {
    Toast.makeText(getActivity(), " Not Completed", Toast.LENGTH_SHORT).show();
}
else {
    if (adapter != null) {
        if (mClickedPosition == -1) {
            adapter.add(iD, addTask, time1, date1);
            insertTask(addTask, time1, date1);
            listview.setAdapter(adapter);
            alert.dismiss();
            check();
            retrieveList(name);
        }
    }

    Calendar alarm = Calendar.getInstance();
    Calendar copy = (Calendar) alarm.clone();
    alarm.set(Calendar.YEAR, year1);
    alarm.set(Calendar.MONTH, month1);
    alarm.set(Calendar.DAY_OF_MONTH, day1);
    alarm.set(Calendar.HOUR_OF_DAY, hour1);
    alarm.set(Calendar.MINUTE, min1);
    int result = alarm.compareTo(copy);

    if(result < 0) {
        alarm.add(Calendar.DATE, 1);
    }
    else
    {
        Intent myIntent = new Intent(getActivity(), MyReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(getActivity().ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, alarm.getTimeInMillis(), pendingIntent);
    }
}

Comment: But how about the dialog ?

How to reuse code


How can I reduce inode utilization on an ext4 filesystem?

Question: Summary of My Need
We put a large amount of files on a filesystem for analysis at a later time. We can't control how many files we're going to have, and this one box needs access to all of them.
Unchangeable Limitations

I can't change the inode limit. It's ext4, and it's the default 4 billionish
There will always be a lot of files. The question isn't how to reduce the number of files; it's how to circumvent the 4Bn inode limit.
I can't use network storage. This box lives in a data center and due to the staggering amount of existing data throughput, network storage is not an option.

My Ideas

I could mount a file as a loopback device in the location where we're placing these files.

Pro: Simple to implement
Con: Another layer of complexity, but a pretty thin one.

XFS. No inode limit.

Pro: This obviously just erases the problem.
Con: Not sure how much flexibility I'll have in making this change to a production system.

My Question
What are some other stragies for circumventing this hard limitation? Are there other benefits/drawbacks to the approaches I've mentioned?
Comment: Can you just create multiple filesystems instead of having one big filesystem that is filled to the max?
Answer: I would suggest that you use a network server with a filesystem designed to handle what you need. The first thing that comes to mind would be something that supports zfs (freenas and nexenta, though the free version of the latter has some limitations) or if you can afford it you can buy something like netapp.
I am less familiar with UFS available on freebsd etc., but heard that would work too.
Comment: Thank you, but that won't work. I failed to mention that this box is in a data center and that, for a couple of reasons, network storage is not an option. I have updated the question.
Comment: you can try btrfs if neither zfs nor ufs is supported in your server, if you cannot use network storage.
Answer: Info we're missing...

Distribution and version of Linux.
Disk layout (disk bays, RAID controller, etc.).

ext4 doesn't sound like it does what you want. So don't use it...
XFS should handle your situation well. It's in the Linux kernel, but deployment depends heavily on your disk flexibility. There are also some XFS tunables that will help with your load... Out of the box, it won't run particularly well. You'll want the right filesystem creation and mount options. The rest depends on your distro, whether you're using a controller, and your particular workload.
Answer: I guess you answered your own question, the XFS option seems to be the best one (i guess you even get a performance boost).
The more complex part should be, how to convert EXT3/4 into XFS?
If your storage is not a unique physical RAID VD (and you didn't make the fs directy on  the BlockDevice - mkfs.ext4 /dev/sdb) then I might suggest you into partitioning your fs tree into smaller blocks and mount them accordingly, configuring your software to write to both locations simultaneosly, and splitting the writes if possible.
Ex.

/alotofsmallfiles/part1 -> /dev/ext4fs1
/alotofsmallfiles/part2 -> /dev/ext4fs2

If splitting the writes is not possible from the application, you could create a cron which moves the files from the ext4 partition into the new XFS every n minutes
Answer: Additional options:

Create filesystems on-demand as you need them. Partition with LVM instead of attaching your filesystems directly to the MBR. You can mount a FS anywhere in your tree, so you can add a new filesystem whenever and wherever you need it. Also, LVM can span portions of multiple disks if you want, meaning physical medium boundaries are less meaningful.
Loopback FSes are not a terrible idea, but really why wouldn't you use LVM instead? All the advantages, none of the disadvantages.
If you're just archiving files (i.e not random-access) then saving them directly into a .tar.gz file is not a bad idea. I've also seen systems where files get "staged" temporarily to an SSD while the structure is getting built, then get dumped to a tar.gz on a spinning drive for long-term storage.
XFS is not a bad option, though it has its own difficulties as well. It's not quite as forgiving of unclean shutdowns, for example. Not that you would expect data loss, but it does sometimes require more hands-on intervention.

Of all these, automatically pushing files into .tar.gz archives is my favorite. It saves you space and inodes, and is just plain tidy. Large numbers of small files make filsystems much less performant than expected.


htaccess files redirects images and css file

Question: I am using .htacess file to redirect my pages with this script:
*#domain/page/about
RewriteRule ^page/(.*)/(.*)?$  detail.php?tag=$1 [NC]
RewriteRule ^page/(.*)?$  detail.php?tag=$1 [NC]*

#domain/about
RewriteRule ^(.*)?$  detail.php?tag=$1 [NC]

The script is working fine but when I use:
#domain/about
RewriteRule ^(.*)?$  detail.php?tag=$1 [NC]

all my images, jscripts, and css files are disabled.
I know its due to the above script but can I tell the .htaccess file to ignore .css, .jpg files from redirection or put same where they are?
Answer: Add this line before your RewriteRule:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?!index\.php/?)(.*)$  detail.php?tag=$1 [NC,QSA,L]

This line will prevent redirection for css, js and image files.
Also remember to add L flag in your RewriteRule to mark it as Last rule.
Comment: thanks it worked but now my index file also redirected to detail.php.
Comment: Well that problem of index.php redirecting existed even before my suggestion. However pls try updated code in my answer.


How to apply opacity to just a portion of the image?

Question: I've got a slideshow on the homepage which consists of an image and with text in front of it, in the bottom half of the image. I would like to apply opacity to the lower part of the image. Is there a way to do this using css?
Answer: What I would have done is to add a new div or span element with the same background as the page, then absolute position it between the image and the text using z-index. How the CSS looks depends on your page layout and html structure, but note that all elements needs a position value for z-index to work.
Answer: You need to use the image with an absolutely positioned div:
Check here for the demo
SO Answer


Logging into Drupal from a non-Drupal site

Question: I would like to create an interface on a non-Drupal site that will allow me to login to my Drupal site?
How can I accomplish this, either with custom code or with an existing Drupal module?
Comment: @Aboodred1  Doesn't the form build ID prevent this from working?
Comment: Quick solution: Go to Drupal login page `user/login` and save the page as html and then copy login form (open form tag to close form tag) then paste it into php file.
Comment: Where you are going to use that login page?
Comment: @Bala I have that page in another site which is created with core php and mysql and i want t link login page with my drupal site login so that user can login thorough site on my drupal site.
Comment: @Aboodred1 can elaborate the steps. i din get it properly.
Comment: @MPD I forgot about build ID, so yet it will prevent the from working.
Comment: @sneha.kamble forget about my suggestion. Is it important for you to get an error message on none Drupal login from if user is invalid?
Comment: check this http://stackoverflow.com/questions/11274342/drupal-7-with-multiple-login-sources
Comment: also this http://drupal.stackexchange.com/questions/2800/external-site-authentication
Answer: Use Token authentication

Token Authentication provides a token for use in the URL to authenticate users to your site. It only works on paths configured in the settings page.
Originally this module was intended to offer simple authentication for RSS feeds to allow feed readers to pull customized content listings. You can now use it to provide a simple browsing experience of any Drupal content.

You would need to code a bit behind the scene - namely inject new token to proper table on successful off-site login, but it should be possible.
But maybe for your case opposite approach would be better? You can add custom submit handler to Drupal's login form to get arbitrary PHP code executed.
Answer: My solution to your issue; is to read/get Drupal login page as HTML using file_get_contents PHP function or cURL. Then parse through the HTML string and extract login form with its fields and submit button, using DomDocument.
Add the following code to your none Drupal login page/block:
$url = 'http://example.com/user/login';

$html = file_get_contents($url);

$dom = new DOMDocument();

// to support HTML5 doctype
libxml_use_internal_errors(true);

$dom->loadHTML($html);

libxml_use_internal_errors(false);

// get Drupal login form
$login = $dom->getElementById('user-login');

// reset action attribute to absolute URL
$login->setAttribute('action', $url);

// save form node
$form = $login->ownerDocument->saveHTML($login);

print $form;

Note: Drupal messages will only appear on Drupal side in case of successful login or invalid login.
Comment: Thanks for this solution. I tried the whole code in login.php which I have created out side drupal but after adding this code when I clicked on login of external site it goes to login.php and blank screen.  Should I do something else too. Please guide me.
Comment: @sneha.kamble please view source of rendered HTML, and check if login form contain `action="http://example.com/user/login"`
Comment: I just used the code upto                                   $url = 'http://example.com/user/login';
$html = file_get_contents($url);                                 print $html;                                                                        I am getting entered  Username and pwd with $_POST. Then I am writing a javascript to add these values to respective fields n login form of drupal and then using trigger function to click submit so form redirects to drupal site. may be it's not best solution.If you have some better way please let me know so that my code will be unbreakable. thanks.
Comment: please check above comment and let me know your thoughts.
Comment: @sneha.kamble well, its not enough to use part of the code and leave the rest. the problem with printing `$html` is that **action** attribute will contain the wrong **URL**. So you need to set the right action to make it work for you. Let me know if you more clarification.


Como obter resultado da query separado por colunas?

Question: Preciso fazer uma consulta na dbpedia e a partir dessa consulta retornar nome, gênero e outras informações de um determinado cantor. Eu estou conseguindo fazer isso, porém meu código retorna a tupla toda, queria poder separar as informações por coluna. Alguém pode me ajudar?
Segue o código:
<?php
    require_once('sparqllib.php');
    $db = sparql_connect('http://dbpedia.org/sparql');
    $query = "  PREFIX owl: <http://www.w3.org/2002/07/owl#>
                PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
                PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
                PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
                PREFIX foaf: <http://xmlns.com/foaf/0.1/>
                PREFIX dc: <http://purl.org/dc/elements/1.1/>
                PREFIX : <http://dbpedia.org/resource/>
                PREFIX dbpedia2: <http://dbpedia.org/property/>
                PREFIX dbpedia: <http://dbpedia.org/>
                PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
                PREFIX owl: <http://dbpedia.org/ontology/>
                PREFIX rsc: <http://dbpedia.org/resource/>
                    SELECT ?name ?hometown ?origin ?genre ?bandMember ?currentMembers ?associatedMusicalArtist
                    WHERE {
                      rsc:Arctic_Monkeys dbpedia2:name ?name.
                      rsc:Arctic_Monkeys owl:hometown ?hometown.
                      rsc:Arctic_Monkeys dbpedia2:origin ?origin .
                      rsc:Arctic_Monkeys dbpedia2:currentMembers ?currentMembers .
                      rsc:Arctic_Monkeys owl:genre ?genre .
                      rsc:Arctic_Monkeys owl:bandMember ?bandMember .
                      rsc:Arctic_Monkeys owl:associatedMusicalArtist ?associatedMusicalArtist .

                    FILTER ((LANG(?name) = 'en') AND (LANG(?origin) = 'en')).
                    }";

    $result = sparql_query($query);
    $fields = sparql_field_array($result);
    while($row = sparql_fetch_array($result))
    {
      foreach($fields as $field)
      {
        print"$row[$field] \n";
      }
    }
?>

Comment: Se refere a isso?

echo $row['name']." ( ".$row['origin']." ) ";
Comment: Isso mesmo Dalton! Porém fiz o teste trocando "print"$row[$field] \n";" por "print"$row['name'] \n";" e não funcionou... =/
deu o erro "Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING"
Comment: experimente assim: `print $row[$field]."\n";` (com ou sem o ``, dependendo do resultado desejado). Alternativamente, assim: `print $field.': '.$row[$field]."\n";`
Answer: Basta printar a coluna por seu respectivo índice.
print ( $row['name']."\n".$row['origin'] );

Não sei no Linux, mas no Windows para o \n quebrar a linha, precisa-se da função nl2br.
Ficando:
print nl2br( ( $row['name']."\n".$row['origin'] ) );

Answer: Que tal tentar com o Freebase.com?
{
"id": null,
"name": "Arctic Monkeys",
"type": "/music/artist"
}
O Freebase também usa dados da Wikipedia e todas requisições são em JSON, assim é fácil pedir qualquer informação específica.
Comment: Caso o resultado do DBPedia seja um "array"=>"associativo" basta adicionar foreach($fields as $key=>$value)
Comment: desculpe gaucho, mas não entendi a solução... poderia dar esse exemplo utilizando o campo name que é retornado da query? obrigado!


Visual Studio 2010 - How to enable prompt to delete file from disk when removed from project?

Question: In Visual Studio 2005, when you remove a file from a C++ project (by right-clicking in the Solution Explorer and selecting "Remove"), it asks you whether you just want to delete the reference, or also delete the file itself from disk.
In Visual Studio 2010, this prompt seems to have disappeared (or I have accidentally turned it off). This means that every time I delete a file in the Solution Explorer, I have to immediately hunt it down and delete it with Windows Explorer (otherwise I'll forget and it will stay around forever). How do I get the prompt back?
I found some documentation (http://msdn.microsoft.com/en-us/library/0ebzhwsk%28v=vs.100%29.aspx) explaining the difference between "Remove" and "Delete", and that "Delete" doesn't exist for C++ projects (but no reason is given). Maybe it's really just not possible? If so, what an annoying regression.
Comment: If the documentation clearly says it doesn't exist for C++ projects, what exactly is your question? If you're asking why they made that decision, no one here knows. This reads more like a complaint than an actual question.
Comment: huh, when I press the Del key, or right click a file and select "Remove" in a VC++ project, I'm prompted if I want to Remove or Delete the file...
Comment: @Ken White: Even from reading that documentation, I'm not sure if the entire ability is missing, or if you just can't get to it that way. In VS2005, there was no "Delete" option either, but the functionality was still there.
Answer: You get the remove or delete file dialog only if the selected file is stored in the project folder. If the file is stored outside of the project folder the file reference is removed without dialog.
This behaviour is still the same for e.g. VS2013. I created a user voice request to change this behaviour here. IMHO your file hierarchy should not make any difference.
You can vote for the change here:
http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9146353-remove-delete-dialog-should-show-up-when-deleting
Comment: Hmmm. Is the project folder the folder containing the project file? Yeah none of my source files are in there (the code is cross-platform; I have multiple different project files in a separate directory). Voted!
Comment: @Karu We created an Visual Studio extension to fix this weird behaviour. You can download it [here](https://gallery.msdn.microsoft.com/ebc2b8d7-9f1b-4e9d-88f7-daf924e422ec).
Answer: Assuming one is using Sourcegear Vault as the source control system, you can enable the prompt by going to Tools -> Options -> Source Control -> Integration Options -> and check on "Show warning before deleting items from source control"


How to use style for background image in cloudinary tags?

Question: I am using angular2.
I want to use the the style="backgroound-image : url("the url from the cloudinary")"
page.html

<cl-image public-id = xyz.jpg>

<cl-image>

Comment: See: https://stackoverflow.com/questions/37575368/angular2-dynamic-background-images
Answer: You can achieve this with URL manipulation, e.g. in your css/scss file use:

background-image: url('path-to-cloudinary-image')


How to publish link programatically?

Question: I am creating Job portal and in that job portal When I create a Job post using admin and save that job as draft instead of posting it to all and for that draft one link is get created and I want to make that job draft link to be accessible to all users including guest.
following is the code for creating draft :
case 'draft':
        $new_node = node_load($job_node_nid,null,true);
        $new_node->status = 0;
        node_save($new_node);
        $_SESSION['bf_job_creation'] = array('step'=>1);
        header('Location: ' . url('my-account'));
        break;

 This above code creates job draft but link to access that draft I just want to make that link to be accessible to all by writing code.

I have tried following code to make link accessible but not succeed :
case 'draft':
    $new_node = node_load($job_node_nid,null,true);
    $new_node->status = 0;
        $new_node->field_job_status = array(array('value'=>'published'));//added this
    node_save($new_node);
    $_SESSION['bf_job_creation'] = array('step'=>1);
    header('Location: ' . url('my-account'));

break;
how to make the link to job draft public??
Answer: your problem is $new_node->status = 0;
This is setting the node to 'unpublished'.
either change the permissions to allow the users to see it or set $new_node->status = 1;
To create a link use the l() function eg. l('link text', 'node/'.$node->id);. http://api.drupal.org/api/drupal/includes!common.inc/function/l/7

How to publish link programatically?


Can I use IdUDPClient to send M-SEARCH request?

Question: There are few uPNP devices in my network.  I am trying to send M-SEARCH request to the network and hope receiving some responses from it.  This is what I am trying:
var sIP, sOut: string;
    iPort: Word;
    S: TStringBuilder;
begin
  S := TStringBuilder.Create;
  try
    S.Append('M-SEARCH * HTTP/1.1').AppendLine
     .Append('HOST: 18.104.22.168:1900').AppendLine
     .Append('MAN: "ssdp:discover"').AppendLine
     .Append('MX: 10').AppendLine
     .Append('ST: ssdp:all').AppendLine;

    IdUDPClient1.ReceiveTimeout := 3000;
    IdUDPClient1.Broadcast(S.ToString, 1900, '188.8.131.52');
    sOut := IdUDPClient1.ReceiveString(sIP, iPort);
    Memo1.Lines.Add(sIP);
    Memo1.Lines.Add(IntToStr(iPort));
    Memo1.Lines.Add(sOut);
  finally
    S.Free;
  end;
end;

I receive nothing from the UDP client.  I use Wireshark to monitor network traffic and no message was send out from my host.
Any ideas?  Thank you.
I found the answer finally:
uses
  System.SysUtils, IdUDPClient, IdStack;

var S: TStringBuilder;
    U: TIdUDPClient;
    iPeerPort: Word;
    sPeerIP, sResponse: string;
begin
  U := TIdUDPClient.Create(nil);
  S := TStringBuilder.Create;
  try
    S.Append('M-SEARCH * HTTP/1.1').AppendLine
     .Append('HOST: 18.104.22.168:1900').AppendLine
     .Append('MAN: "ssdp:discover"').AppendLine
     .Append('MX: 3').AppendLine
     .Append('ST: ssdp:all').AppendLine
     .AppendLine;

    U.BoundIP := GStack.LocalAddress;
    U.Send('126.96.36.199', 1900, S.ToString);

    U.ReceiveTimeout := 1000;
    repeat
      sResponse := U.ReceiveString(sPeerIP, iPeerPort);
      if iPeerPort <> 0 then begin
        WriteLn(Format('%s:%d', [sPeerIP, iPeerPort]));
        WriteLn(sResponse);
      end;
    until iPeerPort = 0;
    ReadLn;
  finally
    S.Free;
    U.Free;
  end;
end.

Answer: Call AppendLine() twice at the end of the string builder.  HTTP request headers are terminated by two CRLF pairs, but you are only appending one pair, so you are sending an incomplete request.
Comment: I add a new AppendLine() to stringbuilder object, but I didn't receive any response too.  I also didn't notice the request send out from my host when monitor the traffic via WireShark.
Comment: Are you sure that `188.8.131.52` is the correct broadcast IP for your LAN?  What local IP and subnet is assigned to your client's PC?
Comment: If I broadcast to 18.104.22.168, I can see the traffic sent out from my host.  But broadcast to 188.8.131.52, no traffic was detected.
Comment: I am not sure if 126.96.36.199 is the address I should broadcast.  I am trying to send the m-search packet to 126.96.36.199 in order to receive some replies of available uPNP devices in my network.  How to do it with IdUDPClient?  Should I broadcast or send?
Comment: I found out the problem.  I should set BoundIP to my adapter's IP.  The uPNP Device Host Service doesn't listen to 0.0.0.0.  It listen to host's adapter's IP only.
Answer: Quick and Dirty solution using TIdUDPServer (Indy 9).
Drop the TIdUDPServer component on the form, and using Object Inspector set Bindings to your local IP eg. 10.1.0.78:0, set BroadcastEnabled and Active to true. Drop a TMemo and TButton on the form.
Complete the OnClick and UDPRead Events as follows:
uses IdSocketHandle;
...
procedure TForm1.Button1Click(Sender: TObject);
begin
  IdUDPServer1.Send('188.8.131.52', 1900, 'M-SEARCH * HTTP/1.1' + #13#10 +
     'HOST: 188.8.131.52:1900' + #13#10 +
     'MAN: "ssdp:discover"'+ #13#10 +
     'MX: 3'+ #13#10 +
     'ST: ssdp:all'+ #13#10 +
     #13#10);
end;

procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);
var
   data: string;
begin

   setlength(data, Adata.Size - AData.Position); //No fragmentation :)
   AData.ReadBuffer(data[1], length(data));

   memo1.Lines.Add('Read: ' + inttostr(AData.Position) + ' / ' + inttostr(AData.Size) + ' PeerIP: ' + ABinding.PeerIP);
   memo1.Lines.Add(data);
end;

Save, Run and Bob's your uncle.
Answer: For multicast M-SEARCH, the message format is defined below. Values between * * are placeholders for actual values.
M-SEARCH * HTTP/1.1
HOST: 22.214.171.124:1900
MAN: "ssdp:discover"
MX: *seconds to delay response*
ST: *search target*
USER-AGENT: *OS/version UPnP/1.1 product/version*

So you need to fix ReceiveTimeout to
U.ReceiveTimeout := 3000;

It should be at least equal to delay in your request (MX:3) 3 sec = 3000 milliseconds


I try to access a route from my controller and it returns a 404 error instead of returning the entity in a JSON with POSTMAN

Question: I try to access a route from my controller and it returns a 404 error instead of returning the entity in a JSON with POSTMAN
This is my controller
<code>package com.main.CitaMedica.Controller;

import com.main.CitaMedica.DTO.CitaDTO;
import com.main.CitaMedica.DTO.MedicoDTO;
import com.main.CitaMedica.DTO.PacienteDTO;
import com.main.CitaMedica.Service.CitaService;
import com.main.CitaMedica.Service.MedicoService;
import com.main.CitaMedica.Service.PacienteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/citas")
public class CitaController {
    @Autowired CitaService citaService;
    @Autowired MedicoService medicoService;
    @Autowired PacienteService pacienteService;

    @GetMapping("mostrarTodos")
    public ResponseEntity<CitaDTO> showCitas(){
        List<CitaDTO> citas = citaService.findAll();
        return new ResponseEntity(citas, HttpStatus.OK);
    }

    @GetMapping("mostrarUno/{citaID}")
    public ResponseEntity<CitaDTO> showCita(@PathVariable("citaID") int citaID){
        CitaDTO cita = citaService.findById(citaID);
        return new ResponseEntity(cita,HttpStatus.OK);
    }

    /*
    @GetMapping("mostrar/porFecha/{fecha}")
    public ResponseEntity<Cita> showCitaFechaHora(@PathVariable("fecha")Date fecha){
        List<Cita> cita = citaService.findByFechaHora(fecha);
        return new ResponseEntity(cita,HttpStatus.OK);
    }
     */

    @PostMapping("create")
    public ResponseEntity<CitaDTO> crearCita(){
        MedicoDTO medico = medicoService.findById(5);
        PacienteDTO paciente = pacienteService.findById(3);
        CitaDTO cita = new CitaDTO();
        cita.setMedico(medico);
        cita.setPaciente(paciente);
        cita.setFechaHora(new Date());
        cita.setMotivoCita("Prueba");
        citaService.save(cita);
        return new ResponseEntity(HttpStatus.OK);
    }

    @PutMapping("update/{citaID}")
    public ResponseEntity<CitaDTO> actualizarCita(@PathVariable("citaID") int citaID){
        CitaDTO cita = citaService.findById(citaID);
        cita.setMotivoCita("Enfermedad");
        citaService.save(cita);
        return new ResponseEntity(HttpStatus.OK);
    }

    @DeleteMapping("delete/{citaID}")
    public ResponseEntity<CitaDTO> delete(@PathVariable("citaID") int citaID){
        citaService.delete(citaID);
        return new ResponseEntity(HttpStatus.OK);
    }
}
</code>
And this is the error that POSTMAN gives me when I try to access that route and I have the server started by port 8090
<code>{
    "timestamp": "2023-02-06T17:00:50.592+00:00",
    "status": 404,
    "error": "Not Found",
    "message": "No message available",
    "path": "/citas/mostrarTodos"
}
</code>
Before it worked for me and it returned all the data when I did not have DTO and MapperStructure but since I have implemented it now in all the routes it gives me that
Ask me for any information
Comment: Please provide a [mcve].
Comment: @Unmitigated It didn't work for me :(
Comment: @SotiriosDelimanolis I used this example -> ´´´@GetMapping("mostrarTodos")
     public ResponseEntity showCitas(){
         List citas = CitasService.findAll();
         return new ResponseEntity(appointments, HttpStatus.OK);
     }´´´
Comment: Please reread the link in my comment and provide what's described there.
Comment: @SotiriosDelimanolis Cuando accedo a esta ruta "/citas/mostrarTodos" en POSTMAN me sale el error 404 que mencioné anteriormente, cuando antes si me funcionaba. Todo los controladores me funcionaban hasta que intenté usar DTOS y mappers y ahora me devuelve el error 404
Answer: I solved my problem by adding @Mapper(componentModel="spring") in all mappers it was my mistake


Multiple Regression: Variation Explained

Question: I'm stuck on a homework problem and I'm hoping you all might be able to help me out. I'd be very appreciative!
We were given this data set: Data. I ran a regression in Minitab with GPA as the response and IQ and Self-Concept as the predictors. I've answered a number of questions correctly with this regression, but I can't figure out how to interpret the data to answer the following two questions:

What percent of the variation in GPA is explained by IQ?
Additional amount of variation explained due to the addition of Self-Concept to the model?

This is what I got from Minitab:

Is this enough information to discern the answer to these questions? If so, how do I interpret this information to find the percent of variation explained by each predictor?
Comment: You have been given enough information there to answer the questions. See of the discussion of sequential sums of squares [here](https://onlinecourses.science.psu.edu/stat501/node/69), and note how proportion of variation explained relates to regression sums of squares [here](http://en.wikipedia.org/wiki/Explained_sum_of_squares)
Answer: You will want to calculate the Coefficient of Determination (wiki link: http://en.wikipedia.org/wiki/Coefficient_of_determination) which is the fraction of variance explained by your regression divided by the total variance in the data. So if you have r^2 = 1 then 100% of the variance is explained by your model.
To calculate this value you will want to take the Sum of Squares for your regression (in your case 221.58) and then divide it by the Total Sum of Squares (in your case this is 339.43).
So to address your first question you should run a regression using only the IQ variable and get the Sum of Squares for the regression and from that you can calculate the fraction of variance you've explained with your model. I have not used Minitab before but I suspect that this will be equivalent to the Seq SS for the IQ variable (or 143.7)
For your second question you just need to figure out (from your output) what the explained variation is (i.e., 221.58/339.43 or ~65.3%).
I hope that helps.
Comment: Be sure to read the subsection on Adjusted-$R^{2}$, which bears on regression models with more than one predictor: https://en.wikipedia.org/wiki/Coefficient_of_determination#Adjusted_R2


What family is used in glm for Continuous predictor vs Continuous outcome

Question: I am going to use the glm to estimate nutrient concentration as a function of river flow. My nutrient concentration are not normally distributed and variance is not constant. So, I would like try GLM but not sure what family I should use. Data are continuous, positive and greater than zero. I would appreciate if anyone could correct my code and let me know if I am missing anything:
<code>model2=glm(TDPConcSam~SamDayFlow,Sample.lm, family=)
</code>
Answer: The form of the predictor is irrelevant to the choice of family which describes the conditional distribution of the response.
There are a number of families on might use for a continuous positive random variable.
I'd probably start with considering a Gamma family (variance proportional to mean squared), possibly with a log-link (your own subject matter knowledge should form a better basis on which to choose a link though).
There's also Inverse Gaussian (variance proportional to mean cubed) in most implementations of GLMs, and in some packages you can use the Tweedie family (power variance function -- which includes those earlier two as special cases).
Another alternative that's sometimes used with concentrations is the lognormal; with positive data one might take logs and then fit a (possibly linear) least squares regression model (since the assumed conditional distribution would be normal after taking logs).
Comment: FWIW, such data are only strictly positive because we don't have machines/methods sensitive enough to detect low values of the nutrient in question. Technically, I suppose, a zero is possible, but in any case we're not going to be able to distinguish among values in the range 0, $c$ where $c$ is the detection limit of the method in question. That said, I've had good experiences using a Gamma family for GLMs with such data,
Comment: Of course, if lower detection limits became an issue, one could incorporate censoring into the model.


Open and closed sets in topology

Question: I recently came across the following example which was really surprising:
Let $X= [1,2] \cup [3,4]$? Here $[1,2]$ is both open and closed and same holds fo $[3,4]$. But how is it possible to determine whether the given subset is open or closed just from the above given $X$. Don't we need more information?
Comment: The only additional information needed is that $X$ is being given the topology that it inherits as a subspace of $\Bbb R$ with the usual Euclidean topology.
Comment: @BrianM.Scott: Under that condition, wouldn't $ [1,2]$ be closed? I am a little confused
Comment: It's both: it's open because it's the intersection with $X$ of the open set $\left(0,\frac52\right)$ in $\Bbb R$, and it's closed because its complement is open in $X$, being $X\cap\left(\frac52,5\right)$, for instance.
Comment: The unfortunate part about that choice of terminology: unlike a door, a set can be open, closed, both, or neither.
Comment: @BrianM.Scott: I see. For the first part, you have used the fact that finite intersection of open set is open and similar reasoning for its complement to be open. Am I understanding it correctly?
Comment: No, I'm just using the definition of subspace topology. If $Y$ is a topological space, and $X$ is a subset of $Y$, a set $U\subseteq X$ is open in the subspace topology on $X$ if and only if there is some open set $V$ in $Y$ such that $U=V\cap X$. (Note that there may be many such sets $V$.)
Answer: Given a set $X$, in order to say whether $A \subseteq X$ is open, closed, both, or neither we need to know the topology on $X$. For your example, $X = [1, 2]\cup[3,4]$. You haven't specified the topology, but given your comments, it seems you are considering the subspace topology on $X$.
Given a topological space $(Z, \tau_Z)$, and $Y \subseteq Z$, the subspace topology on $Y$ is $\tau_Y = \{U\cap Y \mid U \in \tau_Z\}$. In your situation, $X$ is a subset of $\mathbb{R}$ which we usually regard as having the topology induced by the metric $d(x, y) = |x-y|$. As Brian has already pointed out in the comments, with this topology, $[1,2]$ and $[3,4]$ are both open and closed.
Note: We could obtain the same topology on $X$ by using the induced metric.

Open and closed sets in topology


Can you create on the fly references to JCheckBox objects?

Question: I am not sure how to ask this. The program I am working on is done, but it seems like it has excessive code. Here is part of the code:
chkDef1 = new JCheckBox

if (chkDef1.isSelected()) {
            actual = chkDef1.getText();
        }
else if (chkDef2.isSelected()) {
            actual = chkDef2.getText();
        }
else if (chkDef3.isSelected()) {
            actual = chkDef3.getText();
        }
else {
            actual = chkDef4.getText();
        }

There are other areas where there is a lot of duplicate code with the chkDef1 - 4 checkboxes. What I would like to do is use a loop in the areas where the code is duplicated and then just use 1 assignment statement.
I've tried :
    if(('chkDef' + counter).isSelected())
I've also tried assigning "'chkDef' + counter" to a String variable and then adding isSelected. Unfortunately I keep getting error messages.
I am a novice programmer so I do not know if what I want to do is possible or what it is called. If it is possible an explanation of how would be appreciated.
Answer: Simply create a list of checkboxes and iterate through it.
ArrayList<JCheckBox> checkboxes  = new ArrayList<JCheckBox>();
//Init your checkboxes array.

for(JCheckbox chkbox :checkboxes)
{
  if(chkbox.isSelected())
   {
    actual = chkbox.getText() ; break;
  }
}

Although,  there could be a JCheckbox group that does what you want.
Looks like you can use ButtonGroup and get the elements to iterate through it.
Comment: +1 for the button group (although I'd recommend `JRadioButton` or `JToggledButton` for button groups from a useability perspective)
Comment: Thanks for the help. I do have them as part of a button group. I'll start with the array as I understand how that works and then work on using the button group.
Answer: You could create an array that contains all the check boxes and then loop through the array...
JCheckBox[] boxes = new JCheckBox[] {chkDef1,chkDef2,chkDef3,chkDef4}
for (JCheckBox box : boxes) {
    if (box.isSelected()) {
        actual = box.getText();
        break; // We don't want to loop unnecessarily
    }
}

Equally, you could create a simple method that takes a variable number of arguments...
public String getCheckedItem(JCheckBox... boxes) {
    String actual = null;
    for (JCheckBox box : boxes) {
        if (box.isSelected()) {
            actual = box.getText();
            break; // We don't want to loop unnecessarily
        }
    }
    return actual;
}

And call it like...
String actual = getCheckItem(chkDef1, chkDef2, chkDef3, chkDef4);

Personally, I'd return the check box, but that's up to you
If you're only interested in maintaining a single selected check box (ie not allowing multiple check boxes to be selected) then you should seriously consider using JRadioButtons and ButtonGroup instead.
Otherwise you could collect ALL the selected checked boxes...
public JCheckBox[] getCheckedItem(JCheckBox... boxes) {
    List<JCheckBox> selected = new ArrayList<JCheckBox>(boxes.length);
    for (JCheckBox box : boxes) {
        if (box.isSelected()) {
            selected.add(box);
        }
    }
    return selected.toArray(new JCheckBox[selected.size]);
}


Homogeneous second-order linear ODE with constant coefficients

Question: Okay, so how can you prove that $ = C_1 \cos  + C_2 \sin $ is the general solution of $'' + (^2)  = 0$, $ \neq 0$
Anyone willing to explain???
Any help will be much appreciated!
Comment: Hello, welcome to math.stackexchange. Please improve your question by explaining your thoughts on the problem, and/or showing the work you have done. Also consider taking a more descriptive title.
Comment: What does "a2y" mean?
Comment: @Timbuc I edited
Comment: @Pedro Sorry I'm so lost, i need some explanation :(
Comment: That these functions are solutions is a simple question of checking them. That they are a general solution (that is, there are no others) is more a matter of analysis than of linear algebra. After all if one takes the same equations on a domain with multiple connected components, there will be other solutions. Hence I have re-tagged the question, removing `vector-spaces` and adding `real-analysis`.
Answer: I'll sketch the uniqueness:
Note first that, as it is a linear differential equation, its solutions are a vector space $S$ over $\mathbf R$ (this means any linear combination of solutions is egain a solution.
Next, you can map $S$ into $\mathbf R^2$ by mapping a solution $y$ to $(y(0),y'(0)$ (the initial conditions). This map is clearly linear.To prove the uniqueness, all we have to do is to prove it is an isomorphism, i.e; it is both injective and surjective. We'll denote it $\varphi$.
Indeed, if it is bijective, suppose you have a solution $y\,$; you can find a solution $C_1 \cos ax+C_2\sin ax$ that satisfies the same initial conditions as $y(x)$ for some coefficients $C_1, C_2$ by solving a linear system of equations (this also prove the surjectivity of the mapping $y(x)\mapsto (y(0),y'(0))$. Hence by uniqueness,
$$y(x)=C_1 \cos ax+C_2\sin ax.$$
Proof of injectivity
As $\varphi$ is linear, it is enough to prove $\ker \varphi=\bigl\{0\bigr\}$. So let $y$ be a solution such that $y(0)=y'(0)=0$.
Lemma. For any solution of the equation $y''+a^2y=0$, the expression $a^2y^2+y'^2$ is constant.
Indeed let's differentiate: $$(a^2y^2+y'^2)'=2a^2yy'+2y'y''=2(a^2yy'+y'(-a^2y))=0.$$
By Rolle's theorem, $a^2y^2+y'^2$ is constant.
$$***$$
Let's apply this lemma to the present situation: we have
$$a^2y(x)^2+y'(x)^2=a^2y(0)^2+y'(0)^2=0.$$
A sum of squares can be zero only if each square is zero. Hence $y(x)=y'(x)=0$.
Comment: You misplaced a closing parenthesis in the equation before "Rolle's theorem".
Comment: Ot  I forgot to remove a spurious $2$ :o) Thank you for pointing the typo!
Answer: This might be easier than you think.
First, if you let $ = C_1 \cos ax + C_2 \sin ax$, does this function solve the differential equation $y'' + a^2y = 0$? To show that it does, you need to differentiate $y$ with respect to $x$ twice, and plug the result into the differential equation instead of $y''$. Also, plug the expression for $y$ into the equation at the place, where it says "$y$". When doing this, do you get $0$? If you do, you have shown that $y$ solves the equation.
Also, how do you differentiate $y$ twice? You need to do both terms of $y$, but if you take for instance the first term $C_1\cos ax$, then this term differentiated once becomes $-aC_1\sin ax$ (you need to differentiate it again, of course).
Now, if you show that $y$ solves the equation, then there's this result called "uniqueness of solutions" that says that there can be no more solutions to the differential equations! This means that $y$ is the general solution.
The reason for this is that you have two arbitrary constants $C_1$, and $C_2$ in the expression for $y$, and your equation has order $2$.
I hope this helps.


Integration: Branch cuts

Question: Can someone show me how to calculate this integral using branch cuts ?
$$\int_0^{\infty}\Big(\frac{x}{1-x}\Big)^{\frac{1}{3}}\frac{1}{1+x^2}dx$$
Comment: By changing the upper integration limit to $1$ we have $I=\dfrac\pi{\sqrt[3]4}~\bigg(1-\dfrac1{\sqrt3}\bigg)$, as @JackD'Aurizio already wrote. As for the remainder, from $1$ to $\infty$, the best way of writing it is in terms of the [hypergeometric function](http://en.wikipedia.org/wiki/Hypergeometric_function) $-\dfrac32\cdot~_3F_2\bigg(~\bigg\{1~,~1~,~\dfrac12\bigg\}~;~ \bigg\{\dfrac43~,~\dfrac56\bigg\}~;-1\bigg)$
Answer: Let
$$f(z)=\frac{|z|^{1/3}e^{i\varphi_1/3}|z-1|^{-1/3}e^{-i\varphi_2/3}}{1+z^2}$$
where $\varphi_1=\arg{z}$, $\varphi_2=\arg(z-1)$, $0\le\varphi_1,\varphi_2\le2\pi$. Integrating $f(z)$ over a dumbbell contour, we get
\begin{align}
\int_\gamma f(z)\ dz
&=\int^1_0\frac{x^{1/3}e^{i(0)/3}(1-x)^{-1/3}e^{-i(\pi)/3}}{1+x^2}dx+\int^0_1\frac{x^{1/3}e^{i(2\pi)/3}(1-x)^{-1/3}e^{-i(\pi)/3}}{1+x^2}dx\\
&=-i\sqrt{3}\int^1_0\frac{x^{1/3}(1-x)^{-1/3}}{1+x^2}dx\\
&=2\pi i\left(\sum_\pm\operatorname*{Res}_{z=\pm i}f(z)-\color{grey}{\operatorname*{Res}_{z=0}\frac{(1-z)^{-1/3}}{1+z^2}}\right)\\
&=2\pi i\left(\frac{e^{\pi i/6}\times2^{-1/6}\times e^{-\pi i/4}-e^{\pi i/2}\times2^{-1/6}\times e^{-5\pi i/12}}{2i}\right)\\
&=-i\frac{\pi}{\sqrt[3]{4}}\left(\sqrt{3}-1\right)
\end{align}
which implies
$$\int^1_0\frac{x^{1/3}(1-x)^{-1/3}}{1+x^2}=\frac{\pi}{\sqrt[3]{4}}\left(1-\frac{1}{\sqrt{3}}\right)$$
For the remaining integral, one can apply the substitution $x\mapsto 1-x^3$ to get
\begin{align}
\int^1_0\frac{(x-1)^{-1/3}}{1+x^2}
&=-\int^1_0\frac{3x}{(x^3-1)^2+1}dx\\
&=-\sum_{\omega\in S}\frac{1}{2(\omega^4-\omega)}\int^1_0\frac{x-\sigma+it}{(x-\sigma)^2+t^2}dx\\
&=-\sum_{\omega\in S}\frac{1}{2(\omega^4-\omega)}\left[\frac{1}{2}\ln\left((x-\sigma)^2+t^2\right)+i\arctan\left(\frac{x-\sigma}{t}\right)\right]^1_0\\
&=-\sum_{\omega\in S}\frac{\ln\left(\frac{(1-\sigma)^2+t^2}{\sigma^2+t^2}\right)+2i\left(\arctan\left(\frac{1-\sigma}{t}\right)+\arctan\left(\frac{\sigma}{t}\right)\right)}{4(\omega^4-\omega)}
\end{align}
where $\omega=\sigma+it$, $\sigma\in\mathbb{R}$ and $$S=\left\{\sqrt[6]{2}e^{\pi i/12},\sqrt[6]{2}e^{7\pi i/12},\sqrt[6]{2}e^{3\pi i/4},\sqrt[6]{2}e^{5\pi i/4},\sqrt[6]{2}e^{17\pi i/12},\sqrt[6]{2}e^{23\pi i/12}\right\}$$
Writing out the $6$ terms manually then using Mathematica to simplify, we find that the sum (which is equivalent to a hypergeometric function as pointed out by Lucian) evaluates to
\begin{align}
\frac{3}{2}{}_3\mathrm{F}_2\left(\left.\begin{matrix}1,1,\frac{1}{2}\\\frac{4}{3},\frac{5}{6}\end{matrix}\right|-1\right)
=&\ \frac{\pi\sqrt[3]{2}}{12}(3+\sqrt{3})+\frac{\ln{2}}{3\sqrt[3]{4}}+\frac{\ln(\sqrt[3]{2}-1)}{4\sqrt[3]{4}}-\frac{\ln(2+\sqrt[3]{4}+\sqrt[3]{16})}{2\sqrt[3]{4}}\\
&+\frac{\sqrt{3}}{2\sqrt[3]{4}}\operatorname{artanh}\left(\sqrt{\frac{3}{5-\sqrt[3]{4}}}\right)+\frac{\sqrt{3}-1}{2\sqrt[3]{4}}\arctan\left(\frac{\sqrt{3}+\sqrt[3]{16}-1}{\sqrt{3}+1}\right)\\
&-\frac{\sqrt{3}+1}{2\sqrt[3]{4}}\arctan\left(\frac{\sqrt{3}-\sqrt[3]{16}+1}{\sqrt{3}-1}\right)-\frac{\arctan(1+\sqrt[3]{2})}{\sqrt[3]{4}}
\end{align}
Therefore,
\begin{align}
\int^\infty_0\frac{x^{1/3}(1-x)^{-1/3}}{1+x^2}dx
=&\ -\frac{\pi\sqrt[3]{2}}{12}(3+\sqrt{3})-\frac{\ln{2}}{3\sqrt[3]{4}}-\frac{\ln(\sqrt[3]{2}-1)}{4\sqrt[3]{4}}+\frac{\ln(2+\sqrt[3]{4}+\sqrt[3]{16})}{2\sqrt[3]{4}}\\
&-\frac{\sqrt{3}}{2\sqrt[3]{4}}\operatorname{artanh}\left(\sqrt{\frac{3}{5-\sqrt[3]{4}}}\right)-\frac{\sqrt{3}-1}{2\sqrt[3]{4}}\arctan\left(\frac{\sqrt{3}+\sqrt[3]{16}-1}{\sqrt{3}+1}\right)\\
&+\frac{\sqrt{3}+1}{2\sqrt[3]{4}}\arctan\left(\frac{\sqrt{3}-\sqrt[3]{16}+1}{\sqrt{3}-1}\right)+\frac{\arctan(1+\sqrt[3]{2})}{\sqrt[3]{4}}\\
&+\frac{\pi}{\sqrt[3]{4}}\left(1-\frac{1}{\sqrt{3}}\right)
\end{align}
Comment: For the power of contour integration (+1).
Answer: Using the simple substitution $x\mapsto \tan(x)$, we get that
$$\int_0^{\infty}\Big(\frac{x}{1-x}\Big)^{\frac{1}{3}}\frac{1}{1+x^2}dx=\int_0^{\pi/2}\Big(\frac{\tan(x)}{1-\tan(x)}\Big)^{\frac{1}{3}} \ dx$$
where the last integral can be computed by Mathematica as shown below.
$$\frac{1}{48 \sqrt[3]{2}}\Re\left(\sqrt{3} \log (4) \sqrt[3]{-1-i}-24 i \log \left(-\sqrt[3]{-\frac{1}{2}-\frac{i}{2}}\right) \sqrt[3]{-1-i}+12 i \log \left(-(-1)^{2/3} \sqrt[3]{-\frac{1}{2}-\frac{i}{2}}\right) \sqrt[3]{-1-i}+12 \sqrt{3} \log \left(-(-1)^{2/3} \sqrt[3]{-\frac{1}{2}-\frac{i}{2}}\right) \sqrt[3]{-1-i}+24 i \log \left(\sqrt[3]{-2}-\sqrt[3]{-1-i}\right) \sqrt[3]{-1-i}-12 i \log \left(\sqrt[3]{-2}-(-1)^{2/3} \sqrt[3]{-1-i}\right) \sqrt[3]{-1-i}-12 \sqrt{3} \log \left(\sqrt[3]{-2}-(-1)^{2/3} \sqrt[3]{-1-i}\right) \sqrt[3]{-1-i}-12 i \log \left(\sqrt[3]{1+i}+\sqrt[3]{-2}\right) \sqrt[3]{-1-i}+12 \sqrt{3} \log \left(\sqrt[3]{1+i}+\sqrt[3]{-2}\right) \sqrt[3]{-1-i}+\left(-1-i \sqrt{3}\right) \pi  \sqrt[3]{-1-i}+\left(-2 i \sqrt[3]{-1-i}-8 i \sqrt[3]{-1+i}+8 \sqrt{3} \sqrt[3]{-1+i}\right) \log (2)-12 i \sqrt[3]{-1+i} \log \left(\sqrt[3]{-1+i} \sqrt[3]{-\frac{1}{2}}\right)+12 \sqrt{3} \sqrt[3]{-1+i} \log \left(\sqrt[3]{-1+i} \sqrt[3]{-\frac{1}{2}}\right)+24 \sqrt[3]{-1+i} i \log \left(-\sqrt[3]{-\frac{1}{2}+\frac{i}{2}}\right)-12 i \sqrt[3]{-1+i} \log \left(-(-1)^{2/3} \sqrt[3]{-\frac{1}{2}+\frac{i}{2}}\right)-12 \sqrt[3]{-1+i} \sqrt{3} \log \left(-(-1)^{2/3} \sqrt[3]{-\frac{1}{2}+\frac{i}{2}}\right)+12 \sqrt[3]{-1+i} i \log \left(\sqrt[3]{-1} \left(2^{2/3} \sqrt[3]{-1+i}+2\right)\right)-12 \sqrt[3]{-1+i} \sqrt{3} \log \left(\sqrt[3]{-1} \left(2^{2/3} \sqrt[3]{-1+i}+2\right)\right)-24 i \sqrt[3]{-1+i} \log \left(\sqrt[3]{-2}-\sqrt[3]{-1+i}\right)+12 \sqrt{3} \sqrt[3]{-1+i} \log \left(\sqrt[3]{-2}-(-1)^{2/3} \sqrt[3]{-1+i}\right)+12 \sqrt[3]{-1+i} i \log \left(\sqrt[3]{-2}-(-1)^{2/3} \sqrt[3]{-1+i}\right)\right)$$
Comment: This answer is *probably* wrong, for the following reason: For *negative* values of *n* and *odd* values of *k*, both *Maple* and *Mathematica* consider $\sqrt[\large^k]n$ to be the complex quantity which forms the smallest positive angle with the positive horizontal semi-axis $(Ox$. E.g., $\sqrt[^3]{-1}=\dfrac{1+i\sqrt3}2$ as opposed to $-1$.
Comment: @Lucian I took this form of answer from Mathematica and numerically things seem correct.
Comment: The numerical result is about $-0.2561547115267227729.$ Is this what you get ?
Comment: @Lucian I get $\approx 1.382763392139544$.

Integration: Branch cuts


Validar vários formulários de uma só vez - Simulado

Question: Estou criando um site de simulados e estou com dificuldade em corrigí-lo, pois não sei como validar inúmeros formulários de uma vez.
O que acontece:

Tenho perguntas que são selecionadas de forma aleatória pelo banco de dados;
Essas perguntas ficam dentro de um formulário com suas alternativas;
Quero corrigí-las (saindo da página ou não) ao clicar em apenas um submit - O simulado possui 10 questões ao todo.

Obs: Tentei usar $_SESSION[] e funcionou, mas apenas com um exemplo.
Espero que tenha passado minha ideia, segue um trecho de código:

<?php echo"$materia";?>

      <?php
        $sql="select * from questoes where id_materia=$disciplina order by rand() limit 10";
        $resultado=mysqli_query($conexao,$sql);

        while ($vetor=mysqli_fetch_row($resultado)):

          $_SESSION["id_questao"] = $vetor[0];
          $id=$vetor[0];
          $pergunta = $vetor[1];
          $imagem = $vetor[2];
          $A = $vetor[3];
          $B = $vetor[4];
          $C = $vetor[5];
          $D = $vetor[6];
          $E = $vetor[7];
          $_SESSION["resposta"] = $vetor[8];
          $resposta=$vetor[8];
      ?>

        <form method="POST" action="VALIDAR_SIMULADO.PHP" name="codigo"  >

            <fieldset >
              <legend value="<?php echo'$id'; ?>">Cod. <?php echo"$id"; ?></legend>
              <p style="margin-top: -2px;margin-bottom: 8px;"  value="<?php echo'$id'; ?>"> <?php echo"$pergunta"; ?>

A) <input type="radio" name="alternativa" value="A"> <?php echo"$A"; ?>

B) <input type="radio" name="alternativa" value="B"> <?php echo"$B"; ?>

C) <input type="radio" name="alternativa" value="C"> <?php echo"$C"; ?>

D) <input type="radio" name="alternativa" value="D"> <?php echo"$D"; ?>

E) <input type="radio" name="alternativa" value="E"> <?php echo"$E"; ?>

            </fieldset>

      <?php endwhile; ?>

      <input type="submit" name="corrigir" value="Corrigir">
      </form>

Comment: O que deveria ser este `p` com a propriedade `value` dentro do `fieldset`?
Answer: Primeiro, você não precisa se múltiplos formulários em sua página. Apenas um dá conta do recado. A única alteração que precisa fazer para isso é diferenciar os campos entre as questões. Você pode definir os value dos input como listas, definido o índice da lista. Por exemplo:
<form action="validar_simulado.php" method="post">

  <?php $i = 0; ?>

  <?php while($vetor = mysqli_fetch_row($resultado)): ?>

    <?php list($id, $pergunta, $imagem, $a, $b, $c, $d, $e, $resposta) = $vetor; ?>

    <fieldset>
      <legend>Questão <?= $i; ?></legend>

<?= $pergunta; ?>

      <input type="hidden" name="id[<?= $i; ?>]" value="<?= $id; ?>">
      <input type="radio" name="alternativa[<?= $i; ?>]" value="a" checked> <?= $a; ?>
      <input type="radio" name="alternativa[<?= $i; ?>]" value="b"> <?= $b; ?>
      <input type="radio" name="alternativa[<?= $i; ?>]" value="c"> <?= $c; ?>
      <input type="radio" name="alternativa[<?= $i; ?>]" value="d"> <?= $d; ?>
      <input type="radio" name="alternativa[<?= $i; ?>]" value="e"> <?= $e; ?>
    </fieldset>

    <?php i++; ?>

  <?php endwhile; ?>

  <input type="submit" name="corrigir" value="Corrigir">
</form>

Este código gerará um HTML semelhante à:

Código CSS foi apenas para mão deixar o resultado tão feio e o JavaScript é para executar algo quando pressionado o botão.

$(() => {

  $("input[type='submit']").on('click', () => {
    console.log("Questão 1: " + $('input[name="alternativa[0]"]:checked').val());
    console.log("Questão 2: " + $('input[name="alternativa[1]"]:checked').val());
  });

});
fieldset {
  margin-bottom: 10px;
  border-radius: 10px;
}

fieldset p {
  font-weight: bold;
}

fieldset legend {
  border: 1px solid black;
  border-radius: 10px;
  padding: 5px;
  box-shadow: 2px 2px grey;
}

<form action="validar_simulado.php" method="post">
  <fieldset>
    <legend>Questão 1</legend>

Lorem ipsum dolor sit amet, consectetur adipiscing elit?

    <input type="hidden" name="id[0]" value="5">
    <input type="radio" name="alternativa[0]" value="a" checked> A
    <input type="radio" name="alternativa[0]" value="b"> B
    <input type="radio" name="alternativa[0]" value="c"> C
    <input type="radio" name="alternativa[0]" value="d"> D
    <input type="radio" name="alternativa[0]" value="e"> E
  </fieldset>
  <fieldset>
    <legend>Questão 2</legend>

Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a?

    <input type="hidden" name="id[1]" value="32">
    <input type="radio" name="alternativa[1]" value="a" checked> A
    <input type="radio" name="alternativa[1]" value="b"> B
    <input type="radio" name="alternativa[1]" value="c"> C
    <input type="radio" name="alternativa[1]" value="d"> D
    <input type="radio" name="alternativa[1]" value="e"> E
  </fieldset>
  ...
  <input type="submit" name="corrigir" value="Corrigir">
</form>

Perceba que com JavaScript já é possível recuperar todas as respostas, mas o mas fácil a se implementar é corrigí-las no PHP. Da maneira que está, o PHP receberá dois arrays via POST: $_POST['id'] e $_POST['alternativa']. O array id armazena os id das questões no banco de dados e servirá para corrigir efetivamente as questões. O array alternativa armazena as respostas dadas.
array id:
Array
(
    [0] => 5
    [1] => 32
)

Os valores 5 e 32 são hipotéticos e representam os id das questões que foram selecionadas do banco aleatoriamente.
array alternativa:
Array
(
    [0] => a
    [1] => c
    [2] => b
    [3] => a
    [4] => a
    [5] => d
    [6] => b
    [7] => c
    [8] => e
    [9] => c
)

Os valores também são hipotéticos e representam as respostas dadas às perguntas.
Agora basta você selecionar do banco de dados as questões cujo id pertence ao vetor id, algo parecido com:
"SELECT * FROM questoes WHERE id IN {$id}"

E iterar sobre o resultado, verificando se a resposta presente no vetor alternativa é igual ao valor presente na coluna resposta.
Comment: onde eu boto o :

        $(() => {

  $("input[type='submit']").on('click', () => {
    console.log("Questão 1: " + $('input[name="alternativa[0]"]:checked').val());
    console.log("Questão 2: " + $('input[name="alternativa[1]"]:checked').val());
  });

});
Comment: Vide nota (destacada com fundo amarelo). Este código JavaScript não é necessário para a solução, apenas existe para deixar o exemplo aqui verificável.
Comment: Entendi, mas ainda não estou conseguindo corrigir...
estou usando este comando: "select * from questoes  WHERE id_questao=$id and resposta=$resposta". Porém não dá certo. Teria como me esclarecer melhor como corrigi-las?
Comment: você poderia me exemplificar como ficaria a correção delas?
Comment: Já consegui fazer conforme me explicou, muito obrigado!