text:
Q: What is the actual meaning of the density operator? I am not able to understand the definition of the density operator. I know that if $V$ is a vector space and if I have $k$ states belonging to this vector space, say $|\psi_{i}\rangle$ for $1\le i\le k$, and the probability of the system being in $|\psi_{i}\rangle$ is $p_i$, then the density operator for the system is given by
$$\rho=\sum_{i=1}^{i=k}p_i|\psi_i\rangle\langle\psi_i |. $$
Now what I am unable to understand is

*

*Does this mean the system is in exactly one of the $|\psi_i\rangle$ states and we don't
know in which state it is in and we just know the probability?

*Or it is in a superposition of these $k$ states with probabilities being interpreted as weights?

A: Check the form of your density operator it should be something like
$$\rho=\sum_i p_i |\psi_i\rangle\langle\psi_i|$$
I find the most intuitive way to think of the density matrix as follows.
Consider an experimenter in his
lab who has a "machine" which produces the quantum state $|\psi\rangle$ but the machine doesn't work perfectly and produces some other states which we don't want. Then to carry out predictions about these states we need something which captures our ignorance of the states which we have i.e we could not use state vectors as we do not have pure states but an ensemble or mixture of states. The density matrix is then what we use. Your suggestion 1.
As an aside the density operator can also describe pure states.
Your suggestion number two is incorrect as superpositions and ensembles are physically quite different things.
Consider the pure state
$$|\psi\rangle=\sum_i \sqrt{p_i}\ |\psi_i\rangle$$
Note that the weights are the square root of the probability which relates to the born rule.

A: What is new in this answer w.r.t to the other answers. I introduce the density operator by inserting the identity  $1 = \sum \vert i\rangle \langle i \vert$ in the average, similarly to how one can use the $\operatorname{tr} \langle A \rangle = \langle A \rangle$ trick to do the same thing.
Conceptual comments. The density matrix comes whenever your system is part of a bigger system and interacts with it. Since you can't model the total, you average out the effect of the other system on yours. This is equivalent to taking a "marginal distribution/state". It can be interpreted as the system being in one pure state or another with different probabilities.

The mathematical details
Suppose that we have a system which we divide in a subsystem and an environment. We know a basis for the subsystem, $\vert {\phi_i} \rangle$, and for the environment, $\vert {\xi_j} \rangle$. I assume them to be orthonormal. Then a generic state is:
$$ \vert {\psi} \rangle = \sum_{ij} c_{ij} \vert {\phi_i} \rangle \otimes \vert {\xi_j} \rangle  $$
Suppose we want to perform a measurement on our subsystem only, meaning we have an operator $O$ which only acts on $\vert {\phi_i} \rangle$:
$$ (O\otimes {1}) (\vert {\phi_i} \rangle \otimes \vert{\xi_j}) \rangle \equiv (O\vert {\phi_i})\rangle \otimes \vert {\xi_j} \rangle  $$
Its expected value is given by
\begin{align*}
 \langle O \rangle = \langle {\psi} \vert  O \vert {\psi} \rangle
\end{align*}
We don't know the total state $\vert \psi \rangle$, but we do know is the possible states of our subsystem, $\lbrace \vert \phi_m \rangle\rbrace$. What is the best we can do knowing only this?
We can use the full expression of $ \vert {\psi} \rangle$ and try to "hide" the things we don't know how to calculate, like the expressions involving $\vert {\xi_j} \rangle$. We can use that the inner product of tensor products is $(\langle \phi_i \vert \otimes \langle \xi_j \vert)(\vert  \phi_k \rangle \otimes \vert \xi_l \rangle)=\langle \phi_i \vert \phi_k \rangle \langle \xi_j \vert \xi_l \rangle$ (or alternatively, one can think of the tensor product being defined such that this is true by construction).
\begin{align*}
 \langle O \rangle  = \langle {\psi} \vert  O \vert {\psi} \rangle = &    \sum_{ij} \sum_{kl}c_{kl} c_{ij}^*   (\langle \phi_i \vert \otimes \langle \xi_j \vert) (  O \otimes 1 ) (\vert  \phi_k \rangle \otimes \vert \xi_l \rangle) \\
 =&  \sum_{ij} \sum_{kl} c_{kl}c_{ij}^*   \langle \phi_i \vert O \vert  \phi_k \rangle \langle \xi_j \vert \xi_l \rangle \\
 =&  \sum_{ik}  \left(\sum_{m}  c_{km}c_{im}^* \right)  \langle \phi_i \vert O \vert  \phi_k \rangle \\
 =&  \sum_{ik}  p_{ki}  \langle \phi_i \vert O \vert  \phi_k \rangle
\end{align*}
So basically so far this is it, because $p_{ki}$ gives us all the information we need to compute the average value; $p_{ki}$ is the marginal distribution of $c_{ij}^* c_{kl}$ (by "marginal" we mean we integrate out or sum the probability over the degrees of freedom of the environment).
Since it has two indices we could think of it as the element of a matrix, and that matrix is easy to construct, we just insert the identity $1=\sum_m \vert \phi_m \rangle \langle \phi_m \vert$ and get the density matrix $\rho$ by using the commutativity of scalars (we can move them around in the product):
\begin{align*}
 \sum_{ik}  p_{ik}  \langle \phi_i \vert O \vert  \phi_k \rangle = &  \sum_{ik}  p_{ik}  \langle \phi_i \vert \sum_m \vert \phi_m \rangle \langle \phi_m \vert O \vert  \phi_k \rangle \\
= &  \sum_{ik} \sum_m p_{ik} \langle \phi_m \vert O \vert  \phi_k \rangle \langle \phi_i \vert \phi_m \rangle  \\
= &  \sum_m  \langle \phi_m \vert O \left(\sum_{ik} p_{ik} \vert  \phi_k \rangle \langle \phi_i \vert\right) \vert \phi_m \rangle = \sum_m  \langle \phi_m \vert O \rho \vert \phi_m \rangle \equiv \operatorname{tr} O \rho
\end{align*}
where $\rho=\sum_{ik} p_{ki} \vert  \phi_k \rangle \langle \phi_i \vert$.

More comments
We have reduced the computation of the global average to calculating averages over the states of our subsystem of a new object, $O\rho$. The object $\rho$ has hidden in it both the state of our subsystem and the average effect of the environment. I will make a few further comments about how one can think about $\rho$ and the mathematical justification.
First of all, it is easy to prove (see any textbook or Wikipedia) that $\rho^\dagger = \rho$, therefore there exists an orthonormal basis in which $\rho$ is diagonal:
$$ \rho = \sum_\lambda p_\lambda \vert \lambda \rangle \langle \lambda \vert \quad \sum p_\lambda = 1 $$
What is the significance of the states $\vert \lambda \rangle$? They represent the most "classical-like" states. This is so because they are orthonormal states, $\langle \lambda \vert \lambda^{'} \rangle=\delta_{\lambda \lambda^{'}}$, there are no correlations between them. They are as mutually exclusive as you can get, meaning that if you know your system is in state $\vert \lambda \rangle$, then automatically it cannot be in $\vert \lambda^{'} \rangle$ if $\lambda^{'}\neq \lambda$ because the projection onto it is zero.
Consider a two level system $\lbrace \vert 0 \rangle, \vert 1 \rangle \rbrace$. Then if you are in state $\vert 0 \rangle$, you know you cannot be in $\vert 1 \rangle$, but you have $50\%$ of being in any of the two diagonal states, therefore the system isn't "classical-like" regarding diagonal states. Also, if you are assured all your particles are in one of these states ($\vert 0 \rangle$ or $\vert 1 \rangle$), you can measure without collapsing provided you have an observable with $\lbrace \vert 0 \rangle, \vert 1 \rangle \rbrace$ as eigenstates.
Such an observable always exists because we can just build it ourselves, we only need it to have the same eigenstates as the density matrix, $\lbrace \vert \lambda \rangle \rbrace$:
$$ M = \sum_\lambda m_\lambda \vert \lambda \rangle \langle \lambda \vert $$ (It measures 0 on everything which is outside $\text{span}\lbrace \vert \lambda \rangle \rbrace$).
The usefulnes of this observable is that we can use it to prepare the mixed state! We measure a random $\vert \psi \rangle$. After measuring, we know the state $\vert \lambda \rangle$ to which it collapsed. We will take $N$ measurements of $N$ different states and after a measurement we will keep the state or discard it according to whether our ratio of states is the one prescribed by the density matrix, $p_\lambda = N_\lambda / N$ where $N_\lambda$ is the number of states in state $\vert \lambda \rangle$. If we now measure $M$, then the average value will be
$$ \langle M \rangle = \sum \frac{N_\lambda}{N} \langle \lambda \vert M \vert \lambda \rangle = \sum p_\lambda m_\lambda $$
and we see that this is a classical average over $p_\lambda$ of the distribution $m_\lambda$. It can be shown that this equals $\text{tr}M\rho$.
As a curiosity, Von Neumann uses the idea of $M$ in his book "Mathematical Foundations of Quantum Mechanics" as a way to implement a filter which separates quantum systems in a way that doesn't collapse them. If you have particles in two different quantum states and all mixed in a box, you can physically separate the particles with a moving wall which acts as a filter only if the possible states of the particles are orthogonal. In that case you can find a measurement which can distinguish between the two states without collapsing them, thus allowing you to create a filter which lets or lets not pass a certain kind of particle, letting you separate the quantum systems.
So to sum up, the first introduction was a top down approach, where we got the density matrix by averaging out the environment, arriving at the fact that mathematically the result is like having an average over pure states. The second approach is taking that "average over pure states" as reality and considering ensembles of pure states. Then, if we have $N$ systems and $N_\lambda$ in state $\vert \lambda \rangle$, then averaging an observable over the $N$ systems gives the same result as a mixed state given by $\rho$.

A: Firstly, what is a state?
A state gives you the complete description of a system. Let's label the state of a system $\lvert \psi \rangle$. This is a normalised state vector which belongs in the vector space of states. Keep in mind that we are talking about the full state; I haven't decomposed it into basis states, and I will not. This is not what the density matrix is all about.
The state vector description is a powerful one, but it is not the most general. There are some quantum experiments for which no single state vector can give a complete description. These are experiments that have additional randomness or uncertainty, which might mean that either state $\lvert \psi_1⟩$ or $\lvert \psi_2⟩$ is prepared. These additional randomness or uncertainties arise from imperfect devices used in experiments, which inevitably introduce this classical randomness, or they could arise from correlations of states due to quantum entanglement.
In this case, then, it is convenient to introduce the density matrix formalism. Since in quantum mechanics all we calculate are expectation values, how would you go about calculating the expectation value of an experiment where in addition to having intrinsic quantum mechanical randomness you also have this classical randomness arising from imperfections in your experiment?
Recall that $$Tr(\lvert\phi_1\rangle\langle\phi_2\rvert)=Tr(\lvert\phi_1\rangle\otimes\langle\phi_2\rvert)=\langle\phi_1\mid\phi_2\rangle,$$ and $$\hat{O}\circ(\lvert\phi_1\rangle\langle\phi_2\rvert)=(\hat{O}\lvert\phi_1\rangle)\otimes\langle\phi_2\rvert$$
Now, using the linearity of the trace, we can compute the expectation value as:
$$ \langle \hat{O} \rangle = p_1\langle \psi_1 \lvert \hat{O} \lvert \psi_1 \rangle + p_2\langle \psi_2 \lvert \hat{O} \lvert \psi_2 \rangle$$
$${} = p_1Tr(\hat{O} \lvert \psi_1 \rangle \langle \psi_1 \lvert) + p_2Tr(\hat{O} \lvert \psi_2 \rangle \langle \psi_2 \lvert) $$
$${} =Tr(\hat{O} (p_1 \lvert \psi_1 \rangle \langle \psi_1 \lvert) + p_2 \lvert \psi_2 \rangle \langle \psi_2 \lvert)) = Tr(\hat{O} \rho)$$
where $p_1$ and $p_2$ are the corresponding classical probabilities of each state being prepared, and $\rho$ is what we call the density matrix (aka density operator): it contains all the information needed to calculate any expectation value for the experiment.
So your suggestion 1 is correct, but suggestion 2 is not, as this is not a superposition. The system is definitely in one state; we just don't know which one due to a classical probability.

A: The density operator of a quantum system summarises the expectation values of the observables of that system alone. If you have two systems $S_1$ and $S_2$ that are entangled with one another, then there is no pure Schrodinger picture state for either of the entangled systems. However, there are observables of $S_1$ (or $S_2$) and those observables have expectation values. The standard way of writing expectation values in terms of the pure state is given by $\langle\psi|\hat{A}|\psi\rangle$ for some arbitrary observable $\hat{A}$, but this can also be written as $\text{tr}(|\psi\rangle\langle\psi|\hat{A})$. So then the question is whether there is an operator on the Hilbert space of $S_1$ alone that would give you the right expectation values using the second formula. It turns out that the correct choice is given by the partial trace since the partial trace is the only choice consistent with the Born rule, see "Quantum Computation and Quantum Information" by M.A. Nielsen, I.L. Chuang, p. 107.
You ask:

Does this mean the system is in exactly one of the $|\psi_i\rangle$ states and we don't know in which state it is in and we just know the probabilities?

No. If $S_1$ and $S_2$ can be manipulated jointly in a coherent process then they can undergo quantum interference. During quantum interference, the square magnitude of probability amplitudes do not in general obey the calculus of probabilities, see

*

*Machines, Logic and Quantum Physics. D. Deutsch et al. Bull. Symb. Log. 6 no. 3, 265 (2000), arXiv:math/9911150.

Your next question is:

Or it is in a superposition of these k states with probabilities being interpreted as weights?

This is also wrong because the density matrix of a system is an instrumental description of what you would get by doing measurements on that system alone. There is not necessarily anything wrong with using such a description if you know its limitations.
I should also add that, contrary to some of the answers above, the density matrix of a system in general does not provide a complete description of the system. A complete description of a system will include information about what systems it is entangled with and how it is entangled, which is not given by the system's density matrix. Such information is given by a system's Heisenberg picture observables, see:

*

*Information Flow in Entangled Quantum Systems. D. Deutsch and P. Hayden. Proc. R. Soc. Lond. A 456 no.1999, 1759 (2000), arXiv:quant-ph/9906007.


text:
Q: Errors displaying buffered image I have recently been following a tutorial on how to make a 2D game in java. I know all the concepts and I am using the video as a guide line so that I can get everything setup and then start pumping all of my ideas and content into the skeleton.
I was following this(http://www.youtube.com/watch?v=VE7ezYCTPe4) tutorial when I ran into a problem. About 28 minutes into the video I type this code:
public void render() {
    BufferStrategy bs = getBufferStrategy();
    if(bs == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    g.setColor(Color.BLACK);
    g.fillRect(0, 0, getWidth(), getHeight());

    g.dispose();
    bs.show();
}

This was all fine until I tried to run it. He runs it in the video and it works just fine, but when I run it I get an error:

Exception in thread "Thread-2" java.lang.IllegalStateException: Component must have a valid peer at java.awt.Component$FlipBufferStrategy.createBuffers(Unknown Source) at java.awt.Component$FlipBufferStrategy.(Unknown Source)
      at java.awt.Component$FlipSubRegionBufferStrategy.(Unknown Source)
      at java.awt.Component.createBufferStrategy(Unknown Source)
      at java.awt.Canvas.createBufferStrategy(Unknown Source)
      at java.awt.Component.createBufferStrategy(Unknown Source)
      at java.awt.Canvas.createBufferStrategy(Unknown Source)
      at com.kaperly.game.Game.render(Game.java:102)
      at com.kaperly.game.Game.run(Game.java:83)
      at java.lang.Thread.run(Unknown Source)

I would really like to continue the video and be on my way to making my first fully functional game (All other game attempts never made it to functional stages.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to record a Qt5 application window with minimal to zero CPU overhead on Windows or Linux? I'm writing a real-time volume rendering application that runs purely on the CPU. It's quite fast but nevertheless the more CPU power the better for interactivity - basically, I'm designing it to use CPU resources to the maximum. I need to record a demo of the application. Now in the past I've used OBS studio on Linux to record a walkthrough for an RTS game, and I recall that there definitely was some CPU overhead. This is unacceptable for my volume renderer demo.
That said, the question is:
Given a desktop machine with an NVIDIA GTX 1060 6 Gb GPU, is it possible to record a purely Qt5 application that does not output into directx or opengl using the said GPU as the encoder with 0 CPU overhead? Do I need to modify the source maybe to leverage some library that would allow me to copy the framebuffer and encode on the fly using the GPU only?
Edit:
To make it more clear. Primarily, I'm interested in an application that I can launch an record the window of my program, not in a library that I can use my own project as a programmer (i.e. via its API). But, if there is a way  to solve the problem in the latter way, that will be fine too.

A: In the end, the only zero-overhead solution seems to be to use the HDMI output to connect to an external recording device, such as a laptop or a dedicated video capture box, and then use the "duplicate screen" mode.


text:
Q: weird action on AJAX form submitting stuck half a day on a part of my code on localhost, part of submit form with uploading file, i simulated my codes in jsfiddle to show you how it works:
var params = $('#add-form').serializeArray();

  $.each(params, function(i, val) {
    form.append(val.name, val.value);
  });

  if (files != null) {
    $.each(files, function(key, value) {
      form.append(key, value);
    });

JSFiddle
Problem:
If user chooses a file it works fine and submit successfully but if does not select a file it won't submit to db, I'm pretty sure there are no conditions in my PHP code to prevent submitting without file and also pretty sure no problem with my PHP it worked with serialize and that and at that time there was no file uploading, after i switch to DataForm this problem occurred.
This part of PHP get file and process it:
$safename = mysqli_real_escape_string($connection, $_POST["name"]);

if($_FILES){
uploadVid($nameVid, $adsid, $userid);
}

If need more information/code to solve this problem please tell me to update the question.
Thanks in advance
Edit: Network result:
Request URL:http://example.com/index.php?post
Request Method:POST
Status Code:200 OK
Remote Address:x.x.x.x:xxx
Referrer Policy:no-referrer-when-downgrade


text:
Q: How to control output voltage on a Buck Converter I'm fairly new to electronics and I have copied the Buck Converter (LM2678) in the picture attached to convert 24V to 5V. After trying it I have actually converted 24V to 9V and my question is if I have done something wrong or if the schematic is wrong? The output voltage is apparently controlled with the two resistors at Vout although I can't seem to figure out how that works, so if anyone could explain that to me I would also really appreciate it, as it would help me troubleshoot!

A: There is an error amplifier in the regulator that controlls the pulse width of the signal
 that turns the output mosfet on and off.  The datasheet should tell you what that is.  You use the resistors divider so that  voltage fedback to the control loop is the "error voltage"  when the voltage is at the output level you are trying to achieve.

A: maybe the problem is that you are testing it with no load. place a 100 ohm resistor at the output and verify if the voltage is ok. if this is not the problem maybe you have a ground problem because of long wires or other assembly troubles. verify if the voltage between feedback and ground is about 1.25 V if it is different try to find why.


text:
Q: Solving an exponential equation for yield curve rates I'm preparing for an exam and one of the topics is pricing bonds where bootstrapping a yield curve is used. Among other things, it involves solving exponential equations which is a recurring problem. A sample equation may look like this:
$$
106.065 = \frac{6.25}{e^{(0.0177 + 0.25r)\times{0.88}}} + \frac{106.25}{e^{(-0.0059 + 1.25r)\times{1.88}}}
$$
or
$$
106.065 = \frac{6.25}{(1.0177 + 0.25r)^{0.88}} + \frac{106.25}{(0.9941 + 1.25r)^{1.88}}
$$
You can notice that both of these are the same thing, but the first one uses the continous compounding and the second one uses the ordinary yearly compound interest.
Can I solve any of those on paper or at least approximate the value of $r$?

A: You know that these equations will not show explicit solutions and numerical methods should be used.
The simplest would be Newton method which, starting from a "reasonable" guess $r_0$ will update it according to $$r_{n+1}=r_n-\frac{f(r_n)}{f'(r_n)}$$ We know that $r$ is small; so let us start at $r_0=0$.
For the first equation, the successive iterates would be $$r_1=0.029640$$ $$r_2=0.030716$$ $$r_3=0.030718$$ which is the solution for five significant figures.
For the second equation, the successive iterates would be $$r_1=0.029485$$ $$r_2=0.031144$$ $$r_3=0.031150$$ which is the solution for five significant figures.
Another way for a better estimate is to approximate the function by its simplest Pade approximant; built at $r=0$ this will give $r\approx 0.030705$ for the first equation and $r\approx 0.031140$ for the second equation.
Doing this on paper could be something hard; a good calculator should do it and any software so (Excel could be the easiest solution).
Since the procedures I described require derivatives (and, for these cases, they are awful) I suggest you compute them by finite differences. This will make life easier.
Edit
The first equation is much more simple than it looks. After some rearrangements, it write $$a = b e^{-\alpha r}+ c e^{-\beta r}$$ and the approximate solution given by the simplest Pade approximant is $$r=\frac{2 (-a+b+c) (\alpha  b+\beta  c)}{\alpha ^2 b (a+b-c)+\beta ^2 c (a-b+c)+4
   \alpha  \beta b c}$$ For the case considered $$a=106.065$$ $$b=\frac{6.25}{e^{0.0177\times 0.88}}\approx 6.153404241$$ $$c=\frac{106.25}{e^{-0.0059\times 1.88}}\approx 107.4350853$$ $$\alpha=0.25\times0.88=0.22$$ $$\beta=1.25\times 1.88=2.35$$ Applying the last formula, the result is $r\approx 0.0307045 $.


text:
Q: Two classes have the same XML type name - Spring Boot I have 2 different dependencies which have the same package and same set of classes due to which I get the exception below while I run the application using Spring Boot. The build is successful using gradle.
Two classes have the same XML type name "{http://xml.welcome.com/types}ExceptionType".
Use @XmlType.name and @XmlType.namespace to assign different names to them.

I am not able to change the XMlType.Name because these are jar files provided to us by different vendors. I can exclude any of these jars altogether because apart from this conflicting package , both these jars have other packages that I make use of.
What is the approach that I need to follow here? Is there a way to exclude a package from being imported while adding dependency or is there a different approach that I need to follow?
EDIT:
I have 2 dependencies , one is spring boot style dependency which has includes multiple jars to my project. xyz-soap-types is one of the jar files which has a package common.types. I want this jar to be included in the project. I have another jar file which is a SOAP webservice client library. The client jar files has 4 different packages and one of them is common.types. I want to use all the packages except common.types from this jar.


text:
Q: Restore file that was overriden with rsync I accidentaly overrode a file while transfering some data with rsync -avz.
Is is possible to restore it? I looked at Photorec but it seems to be looking through the whole drive, which in my case is 1 TB and according to the latest estimate will take over 13hours (and this is constantly increasing) to just scan and I have no idea what I will be presented with afterwards.


text:
Q: 12-Hour Clock Displaying 00 hours, when incremented after 12. 24-Hour Clock ignoring increment limitation beyond 23. How can I fix this issue? #define _CRT_SECURE_NO_WARNINGS //Suppresses warnings that will block the complier.
#include <iostream>
#include <iomanip>
#include <string>
#include <Windows.h>
#include <conio.h>
using namespace std;

#pragma warning (disable : 4996) //Disables an error due to a deprecated variable localtime.
time_t t = time(NULL);
tm* timePrt = localtime(&t);

int hours = timePrt->tm_hour;
int minutes = timePrt->tm_min;
int seconds = timePrt->tm_sec;
string timestr;

int TwelveHourClock() { //Twelve hour clock function.
    int hrs = hours;
    if (hours > 12)
    {
        hrs = hours % 12;
        timestr = "PM";
    }
    else
    {
        timestr = "AM";
    }
    return hrs;
}

void TwentyFourClock() {//Twenty four clock function.

    if (seconds > 59) {
        seconds = 0;
        minutes += 1;
    }
    if (minutes > 59) {
        minutes = 0;
        hours += 1;
    }
    if (hours > 23) {
        hours = 0;
        minutes = 0;
        seconds = 0;
    }
}

// formats the time to transform variables on the clock into a string for display

string Formatting(int time) {
    string format = "0";
    if (time >= 0 && time <= 9) {
        format.append(to_string(time));
    }
    else {
        format = to_string(time);
    }
    return format;
}

void Display() {//For displaying the clocks.

    TwelveHourClock();

    int hour12 = TwelveHourClock();

    string Hour12;
    string Hour24;

    string min;
    string sec;

    Hour24 = Formatting(hours);
    Hour12 = Formatting(hour12);

    min = Formatting(minutes);
    sec = Formatting(seconds);

    cout << setw(60) << string(26, '*') << setw(30) << string(26, '*') << endl;
    cout << setw(60) << "*     12-Hour Clock      *" << setw(30) << "*     24-Hour Clock      *" << endl;
    cout << setw(41) << "*      " << Hour12 << ":" << min << ":" << sec << " " << "         *" << setw(13) << "*        " << Hour24 << ":" << min << ":" << sec << " " << "       *" << endl;
    cout << setw(60) << string(26, '*') << setw(30) << string(26, '*') << endl;

    cout << setw(75) << string(26, '*') << endl;
    cout << setw(75) << "*   1 - Add One Hour     *" << endl;
    cout << setw(75) << "*   2 - Add One Minute   *" << endl;
    cout << setw(75) << "*   3 - Add One Second   *" << endl;
    cout << setw(75) << "*   4 - Exit             *" << endl;
    cout << setw(75) << string(26, '*') << endl;

    cout << "Enter a menu option: ";
}
void Clear() { //Clears the screen.
    system("cls");
}

int main() {
    int userInput = 0;
    int f = 0; //Flag

    while (userInput != 4) {

        while (!kbhit() && f == 0) {

            Clear();
            Display();
            seconds++;
            Sleep(1000);
            main();

        }

        cin >> userInput;

        switch (userInput) {
        case 1:
            hours = hours + 1;
            minutes = minutes - 1;
            seconds = seconds - 1;

        case 2:
            minutes = minutes + 1;
            seconds = seconds - 1;

        case 3:
            seconds = seconds + 1;

        }

    }

    exit(0);
}

Trying to get the program to display local time on both 12-hour and 24-hour clocks and allow the user to increment the time and adjust the hours according to the appropriate clock format. Everything is running smoothly, except when the user increments the time past the 12-hour limit (for the 12-hour clock) the hours display 00 instead of 01. Also, the 24-hour clock never stops incrementing the hours, as it should display 00 hours after incremented from 23 hours, instead it continues to 24,25,26 and so on.


text:
Q: SO dates calculation and formatting What script SO uses for dates displaying? Because it seems to be pretty nice formatting and logical showing.

A: I am not sure what StackOverflow use. But one of the most common timestamp representaion is the one done by twitter which displays timestamp as a moment ago, 30 seconds ago, x minutes ago, yesterday, 10:30 PM Apr 12, 2010 etc. And it updates the timestamp every five seconds without hitting the server.
If you are interested you may look into John Resig's Pretty Date JS API. It's just awesome. Works with/without JQuery.
We tweaked it a bit to exactly match Twitter pattern. And it is awesome.

The website mentioned gives good example, but if you so want a working version, put the following script in address bar of any web-page. (you may want to tweak parameters passed to prettyDate function
  javascript:var i,s,ss=['http://ejohn.org/files/pretty.js'];for(i=0;i!=ss.length;i++){s=document.createElement('script');s.src=ss[i];document.body.appendChild(s);}alert("PrettyDate: "+(prettyDate("2011-03-13T03:24:17Z")?prettyDate("2011-03-13T03:24:17Z"):"03:24 AM Mar 13, 2011"));

A: I think it's based on the answers to this question on Stack Overflow asked by Jeff Atwood - most of the answers are in c# but there is a PHP implementation too


text:
Q: Is it possible to reboot both rooted & unrooted android device Programmatically? In my android application, I wanna restart my android device on button click. But its working in rooted Phone,but not in un rooted phone.
try {
               Runtime.getRuntime().exec(new String[]{"su","-c","reboot now"}));

                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

Is it possible to reboot both rooted & unrooted android devices?

A: Unless something has changed recently you cannot reboot a non-rooted phone programatically, from a regular application.
You can do it if the application is signed by the system firmware key (which a regular application won't be).
If you do go the rooted device route, then be aware that the runtime exec function has some characteristics that mean it may not always behave as you expect.
Rather than learning this the hard way there is an excellent summary here: http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html


text:
Q: Uploading phone's contact on server in Android I am uploading my phone's contacts on the server in the background on button click. I am using volley for this purpose. The code is working fine for 500 contacts, but while uploading 1500 contacts the JSON gets breaked and it shows error 500. Any help on how to acheive this?
Thanks in advance.

A: You can write JSON into the file and after that load data with InputStream from file onto the server side.


text:
Q: webpack execute module in global scope Is there any way to have webpack execute module in the global scope? Specifically, my use case is the following library:
https://github.com/AzureAD/azure-activedirectory-library-for-js/blob/master/lib/adal.js
where there is the following code:
var AuthenticationContext;
if (typeof module !== 'undefined' && module.exports) {
    module.exports.inject = function (conf) {
        return new AuthenticationContext(conf);
    };
}

As you can see the module is exporting an injection function (not sure why they don't just export the class). I am able to construct a new AuthenticationContext object successfully using the using the injection function. However, some of the functionality in this library relies on a global AuthenticationContext class and it errors out when window.AuthenticationContext === undefined. I would like to bundle this module with webpack but somehow, I need to ensure that AuthenticationContext will be available in the global scope. Is there any way to do that?
I have read about the ProvidePlugin but, as I understand the ProvidePlugin just takes an exported value and attaches it to the global scope. In this case I need to ensure that a non-exported value will be available in the global scope.
The most obvious solution is just to execute this module in the global scope. However, I would like this module to be part of the bundle. How can I accomplish this?
Thanks in advance.

A: I think I solved this with the following code:
import {inject} from 'adal-angular/lib/adal.js';
import config from './auth-config';

export default class Authenticator {
    constructor() {
        this.authContext = inject(config);
        window.AuthenticationContext = this.authContext.constructor;
    }
}

basically, I am exposing the constructor manually.


text:
Q: facebook chat using asmack on android with the new access token I have a FB chat client developed for Android. I've been using facebook android-sdk to obtain the access token from a user. Using asmack, user was logged into the chat. Token was in the form: 226409362971500|3b29bc82baa7901a9baca042.4-72793766|9eb417f06fc376897222938295a0dd0c The code I used was:
XMPPConnection xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("DIGEST-MD5", SASLDigestMD5Mechanism.class);
SASLAuthentication.supportSASLMechanism("DIGEST-MD5", 0);
xmpp.connect();
xmpp.login("226409362971500", "3b29bc82baa7901a9fbaca042.4-72793766|9eb417f06fc376897222938295a0dd0c", "Application");

Now it seems that Facebook has changed the token format. I have tried logging in with the old token, but I always get XMPPException. I've tried logging in with the new access token:
xmpp.login(token, "Application"),
but still no luck.
Any idea how to solve this?

A: After a bit of research (php example on the official FB documentation is really good), I came to a following conclusion:
 1. xmpp connection must use ssl
 2. in a response, session_key must be replaced with access_token
In short:
ConnectionConfiguration config = new ConnectionConfiguration("chat.facebook.com", 5222);
config.setSASLAuthenticationEnabled(true);
config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
XMPPConnection xmpp = new XMPPConnection(config);
SASLAuthentication.registerSASLMechanism("X-FACEBOOK-PLATFORM",SASLXFacebookPlatformMechanism.class);
SASLAuthentication.supportSASLMechanism("X-FACEBOOK-PLATFORM", 0);
xmpp.connect();
xmpp.login(appSecret, accessToken, "Application");

SASLXFacebookPlatformMechanism is my class which extends from org.jivesoftware.smack.sasl.SASLMechanism


text:
Q: How do you use addResourcepath() in R Shiny? I'm struggling to understand how to use the addResourcePath() function from R shiny (https://shiny.rstudio.com/reference/shiny/latest/resourcePaths.html), even despite this apparent solution to someone with a similar question How do I porperly use addResourcePath?
I want to refer to a folder containing several javascript files to be used in my shiny app, but I don't understand what the 'prefix' is supposed to be, nor how to get the 'directory path'. How does one use addResourcePath to give R Shiny access to files in a particular folder?

A: Here is a basic explanation in simple words.
Assuming you want to add the file myScript.js located in c:/javascript_files. The simplest solution would be to copy myScript.js to a www subdirectory where your app is located. Anything located in www can be accessed by the UI of your app by using the prefix /.
For this example to add your script to the UI you can use
tags$head(tags$script(src="myScript.js")))
The HTML code generated by Shiny is going to be
<script src="myScript.js"></script>
Your browser is going to interpret it as http://your_site/myScript.js. Here the prefix is just /.
But in the case you want to keep your JS code in the original location (c:/javascript_files), you need to make it accessible to the UI (front-end) of your app. Since you can not use a URL like http://your_site/c:/javascript_files/myScript.js, you need to create a "virtual" subdirectory that is mapping your local directory to a URL directory, that is actually the prefix parameter in addResourcePath().
For this example, lets use as prefix jscode. The expression:
addResourcePath("jscode", "c:/javascript_files")
is going to create a "virtual" directory named jscode to be used in the URL of your app for the local directory c:/javascript_files.
The expression:
tags$head(tags$script(src="jscode/myScript.js")))
is going to be translated to HTML as
<script src="jscode/myScript.js"></script>
which is going to be interpreted by the browser as http://your_site/jscode/myScript.js.
If you had a subdirectory like c:/javascript_files/code_a, you don't need to add it, you can reference it in the same way like:
<script src="jscode/code_a/myScript.js"></script>
The Shiny code to add the myScript.js file will be:
library(shiny)

addResourcePath("jscode", "c:/javascript_files")

ui <- fluidPage(
  tags$head(tags$script(src = "jscode/myScript.js"))
)

server <- function(input, output, session) {
}

shinyApp(ui, server)


text:
Q: How to debug GUI part in Phonegap application? I am writing a very simple Phonegap application on android.  The problem is how to automatically test the GUI part of it. QUnit looks like a good choice to test only Javascript but it needs jquery library to support testing user actions, according to the Cookbook. Is it appropriate to include JQuery library in Phonegap application for testing purpose?
Here is an simple scenario. I have an input field in the application. And I want to test it to see if it could accept value. How should I do with it in Phonegap? Or is there other choice to test the GUI part of Phonegap application?
I also found this question about Selenium but I am trying to find other possible ways to do it.

A: Cordova (formerly Phonegap), by itself (basically), nothing have to do with javascript, it just a tool to wrap your html/js/css code in android WebView element. Cordova has methods to access device internals via cordova provided JS calls.
Well, you can unit-test your application even in chrome desktop browser. Also, if you want, you can include any JS libraries to be used in App. If you have any questions- just write comment


text:
Q: Gnuplot: undefined/missing datapoints and plotting style 'with image' I have to create a color-map, and the plotting style "with image" does exactly what I want. (plot the exact value of z at the position x,y, so using pm3d is not an option for me)
The problem is, there are undefined points in my datafile.  For example, the function represents a mass ratio and therefore negative z-values have no physical meaning and I want to omit them. Or some z-values are even "NaN".
Example Datafile:
1.0   1.0    1.5
1.0   2.0    1.7
1.0   3.0    1.9
2.0   1.0    1.6
2.0   2.0    1.8
2.0   3.0    2.0
3.0   1.0    1.7
3.0   2.0    1.9
3.0   3.0   -1.0

So I don't want to plot the value -1 at the position (3,3) but leave the pixel at (3,3) blank.
I tried this:
plot './test.dat' u 1:2:($3>0 ? $3 : 1/0) with image

but it doesn't work.  It says:

warning: Number of pixels cannot be factored into integers matching grid. N = 8  K = 3

set datafile missing "NaN"

in the case that the -1.0 is replaced by "NaN" doesn't work either.
the only alternative I found is:
set pointsize 10
plot './test.dat' u 1:2:($3>0 ? $3 : 1/0) palette pt 5

but then I have to adjust the pointsize, x- and y-range and plot size for every plot manually, so that there are no spaces or overlapping of the datapoints.  (See this question.)
So to cut a long story short: is there any way to use the "with image" plotting style with undefined/missing data points and leaving this points white?

A: I haven't found a way to make gnuplot handle NaN nicely in this case.  It sets it to 1 for me, which seems odd but may be a feature of how 'plot ... with image' handles missing data.
There is one trick you can use if you only want to eliminate negative numbers:
#!/usr/bin/env gnuplot

set terminal png
set output 'test.png'

filter(x) = (x > 0) ? x : 1/0
philter(x) = (x > 0) ? x : 0

# just in case
set zero 1e-20

# make points set to zero be white
set palette defined (0 1.0 1.0 1.0, \
                 1e-19 0.0 0.0 1.0, \
                     1 1.0 0.0 0.0)

# get min/max for setting color range
stats 'test.dat' u (filter($3)) nooutput

# set color range so minimum value is not plotted as white
set cbrange [STATS_min*(1-1e-6):STATS_max]

plot './test.dat' u 1:2:(philter($3)) with image

On your datafile it produces this plot:

It's not quite ideal since there is that white bit at the bottom of the color bar and it doesn't handle NaN.  The reason it's impossible to get rid of the white bit is that when setting the palette, the numbers used are just autoscaled to fit whatever the colorbar is, and there are a discrete number of slots in the palette (256?).  So, the first slot in the palette will always show the value for the start of the palette (white), regardless of whether the next color in the palette shows up 1e-19 of the way through the scale.

A: Just for the records, the solution would have been as simple as this: replace 1/0 by NaN.
With gnuplot 4.6.0 (March 2012), 1/0 will give the message
warning: Number of pixels cannot be factored into integers matching grid. N = 8  K = 3
and will plot nothing, however, NaN seems to work fine.
With gnuplot>=5.0 both versions, 1/0 and NaN, will give the desired result.
Data: SO14235928.dat
1.0   1.0    1.5
1.0   2.0    1.7
1.0   3.0    1.9
2.0   1.0    1.6
2.0   2.0    1.8
2.0   3.0    2.0
3.0   1.0    1.7
3.0   2.0    1.9
3.0   3.0   -1.0

Script: (works for gnuplot>=4.6.0, March 2012)
### plot with image with blanked values
reset

FILE = "SO14235928.dat"

set size ratio -1
plot FILE u 1:2:($3>0 ? $3 : NaN) w image notitle
### end of script

Result: (created with gnuplot 4.6.0)


text:
Q: Divide all values in dataframe by the minimum value A simple dataframe:
df1 <- data.frame(
  gene = c("PKB", "PKB_1", "PKB_2", "ESR", "ESR_1", "MKB", "PKC", "PKC_1"),
  b = c(1.8,2,3,NA,5,6,NA,NA),
  c = c(9,10,11,NA,NA,12,13,NA))

I am looking to divide all values in the df by the minimum value in the df, while keeping all columns as such. It is OK to remove rows where all values are NA.
How can I do this, preferably using dplyr?

A: You can try a dplyr. Changed the 1 to 3 to better illustrate what is happening.
df1 <- data.frame(
  gene = c("PKB", "PKB_1", "PKB_2", "ESR", "ESR_1", "MKB", "PKC", "PKC_1"),
  b = c(3,2,3,NA,5,6,NA,NA),
  c = c(9,10,11,NA,NA,12,13,NA))

library(dplyr)

df1 %>%
  mutate(min=min(b,c, na.rm = T)) %>%
  mutate_at(vars(b:c), funs(min=./min))
   gene  b  c min b_min c_min
1   PKB  3  9   2   1.5   4.5
2 PKB_1  2 10   2   1.0   5.0
3 PKB_2  3 11   2   1.5   5.5
4   ESR NA NA   2    NA    NA
5 ESR_1  5 NA   2   2.5    NA
6   MKB  6 12   2   3.0   6.0
7   PKC NA 13   2    NA   6.5
8 PKC_1 NA NA   2    NA    NA

In base R you can try
df[-1] <- df1[-1]/min(df1[-1], na.rm = T)

A: Does this do the trick?
 df1 %>%
 mutate(b = b/min(c(df1$b,df1$c),na.rm=T), c = c/min(c(df1$b,df1$c),na.rm=T))

A: df1 %>%
  filter(!rowSums(is.na(.)) == 2) %>%
  mutate(minval = min(b,c, na.rm = T)) %>%
  mutate_at(vars(b,c), funs(./minval)) %>%
  select(-minval)

  gene        b        c
1   PKB 1.000000 5.000000
2 PKB_1 1.111111 5.555556
3 PKB_2 1.666667 6.111111
4 ESR_1 2.777778       NA
5   MKB 3.333333 6.666667
6   PKC       NA 7.222222

Or with purrr and dplyr with 2 less lines:
df1 %>%
  filter(!rowSums(is.na(.)) == 2) %>%
  mutate_at(vars(b,c), funs(./min(df1[ ,map_lgl(df1, is.numeric)], na.rm = T)))

   gene        b        c
1   PKB 1.000000 5.000000
2 PKB_1 1.111111 5.555556
3 PKB_2 1.666667 6.111111
4 ESR_1 2.777778       NA
5   MKB 3.333333 6.666667
6   PKC       NA 7.222222

A: Presumably using only numerical column s:
df%>%group_by(gene) %>summarise(unique (gene),"ColB" = b/min(df$b,na.rm=TRUE),"ColC"= c/min(df$c, na.rm=TRUE))

Can avoid renaming / making new columns by removing names "ColB", "ColC"


text:
Q: Meteor Put Collections Data in Divs AddCategory.js
i want to display category on this page using function mydata().
data is printing in console .i want to bind all categories in divs using mydata() function.
import { Layout, Menu, Breadcrumb, Icon, Form, Input, Button} from 'antd';
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;
import React from "react";
import { Link, Router, Route, IndexRoute, browserHistory } from "react-router";
import { createForm } from 'rc-form';
import { Category } from "../../../imports/collections/category-db";

const FormItem = Form.Item;

function hasErrors(fieldsError) {
  return Object.keys(fieldsError).some(field => fieldsError[field]);
}

 class AddCategory extends React.Component {

  componentDidMount() {
    // To disabled submit button at the beginning.
    this.props.form.validateFields();
  }
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        console.log('Received values of form: ', values);
           const category_name =values.categoryName;
           Meteor.subscribe('category');
           Meteor.call('categoryInsert',category_name);
           alert('category added cheers !');
      }
    });
  }
   state = {
    collapsed: false,
  };
  toggle = () => {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }

    mydata(){
       Meteor.subscribe('category');
      var categories = Category.find({}).fetch();
      categories.forEach(function(cat){
        console.log(cat.category_title);
      });
    }

  render() {
    const { getFieldDecorator, getFieldsError, getFieldError, isFieldTouched } = this.props.form;

    // Only show error after a field is touched.
    const userNameError = isFieldTouched('userName') && getFieldError('userName');

    return (
      <Layout>
        <Sider
          trigger={null}
          collapsible
          collapsed={this.state.collapsed}
        >

          <Menu theme="dark" mode="inline" defaultSelectedKeys={['1']}>
            <Menu.Item key="1">
             <Link to="/users-admin"> <Icon type="user" />
               USERS </Link>
            </Menu.Item>
            <Menu.Item key="2">
              <Link to="/category-admin">
              <Icon type="video-camera" />
              Category
              </Link>
            </Menu.Item>
            <Menu.Item key="3">
              <Icon type="mail" />
              Blogs 3
            </Menu.Item>
            <Menu.Item key="4">
              <Icon type="mail" />
              Jobs 4
            </Menu.Item>
          </Menu>
        </Sider>
        <Layout>

            <Icon
              className="trigger"
              type={this.state.collapsed ? 'menu-unfold' : 'menu-fold'}
              onClick={this.toggle}
            />

          <Content style={{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 720 }}>
            <Form layout="inline" onSubmit={this.handleSubmit}>
        <FormItem
          validateStatus={userNameError ? 'error' : ''}
          help={userNameError || ''}
        >
          {getFieldDecorator('categoryName', {
            rules: [{ required: true, message: 'Please input your username!' }],
          })(
            <Input prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Category tile" />
          )}
        </FormItem>

        <FormItem>
          <Button
            type="primary"
            htmlType="submit"
            disabled={hasErrors(getFieldsError())}
          >
            Log in
          </Button>
        </FormItem>
      </Form>
              {this.mydata()}
          </Content>
        </Layout>
      </Layout>
    );
  }
}

export default createForm()(AddCategory);
Please suggest.

A: You just need to return an array of JSX div entries with individual 'key' attribute from your mydata() function, such as:
mydata(){
   const data = [];
   Meteor.subscribe('category');
   var categories = Category.find({}).fetch();
   categories.forEach(function(cat, index){
     console.log(cat.category_title);
     data.push(<div key={`data-${index}`}>{ cat.category_title }
);
   });
   return data;
}


text:
Q: AutoComplete Works in Chrome but not IE I am trying to setup a search box with autocomplete. This was written by a friend of mine but he couldn't get it to work in IE either. It works great in chrome. It needs to work in IE because the people who will be using it don't have Chrome.
Here is the code:

Any Ideas? I've been working on this for hours.

A: IE fails (and quite rightly so) on trailing commas in object literals.
Just after your Eric Prime object, you have a comma. Remove it, ie this...
{
    label: "Eric Prime",
    category: "Transformer"
}, ];

becomes this
{
    label: "Eric Prime",
    category: "Transformer"
}];

Update
You also have another trailing comma here...
$j("#SearchResult").Complete({
    delay: 0,
    source: data,
    appendTo: '#menu-container', // <-- here
});


text:
Q: UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath: Exception i actually dont see my error:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"Cell";

  FriendTableViewCell *cell = (FriendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
      cell = [[[FriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
      [[NSBundle mainBundle] loadNibNamed:@"FriendTableViewCell" owner:self options:nil];
      cell = friendCell;
  }
  cell.lblNickname.text =  @"Tester";
  return cell;
}

What am i doing wrong? I checked all twice.. but dont see the error.
Thanks for your help!

A: You're returning friendCell, and it's very likely nil.
Your code looks fine, so make sure you have your Interface Builder file set up right.  In FriendTableViewCell.xib, be sure the File's Owner is your table view controller and that you correctly set the cell to be an outlet to friendCell (which I assume is a UITableViewCell).

A: For me, it worked doing this:
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

UPDATE
Place the above code in the following method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Just put it BEFORE editing the tableViewCell

A: You are creating a FriendTableViewCell and then ignoring it and setting it equal to (presumably) an instance variable named friendCell.
I assume that you expect friendCell to be set when calling the loadNibNamed method.  It apparently is not being set.
So you've got two problems with this code.  First, don't allocate a cell twice.
cell = [[[FriendTableViewCell ....
[[NSBundle mainBundle .....
cell = friendCell;

Obviously, the creation of a new cell and assigning it to cell is useless if you are overwriting it with the second call to assignment to cell.
Second, friendCell is probably nil.  Make sure the NIB is set up correctly and has the outlets pointing to the right places.

A: I know this is an old post now but, I have just encountered this error, I found it very strange as the app was in testing so no fresh builds for a few days and it did this, all I did was reboot the phone and it solved it.

A: I found that this problem came when trying to create my UITableViewCell before initialising my table view:
Here registering the class before creating the tableView will cause the error, placing it after will fix the error.
[tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:bCellIdentifier];

tableView = [[UITableView alloc] initWithFrame:CGRectZero];
tableView.delegate = self;
tableView.dataSource = self;

[self addSubview:tableView];

tableView.keepInsets.equal = KeepRequired(0);

A: Look here: Loading TableViewCell from NIB
This is Apple's document for this exact subject.
//This is assuming you have tvCell in your .h file as a property and IBOutlet
//like so:
TableViewController.h
@property(nonatomic,retain) IBOutlet UITableViewCell *tvCell;
//Data Source Method...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {

    [[NSBundle mainBundle] loadNibNamed:@"TVCell" owner:self options:nil];

    cell = tvCell;

    self.tvCell = nil;

use the loadNibNamed:owner:options method to load a cell in a nib.  Set the cell instance to your nib object, then set the nib object to nil.
Read the rest of the documentation that I've linked to know how to access subviews inside your cell.

A: Do not forget to set cell identifier in Interface Builder.

A: Use This ,
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellID];

I saved few more hours with just this lines.

A: Make sure your reuse identifier in your NIB / Storyboard file for your prototype cell matches whatever you called CellIdentifier
 static NSString *CellIdentifier = @"Cell";


text:
Q: Comparing tuple values inside list of lists? I have a list as follows:
mylist=[[(1, 1)], [(1, 1), (1, 2)], [(1, 1), (1, 2), (1, 3)], [(1, 1), (1, 2), (1, 4)]]

Now, what I want is every element of this list is compared with all the other elements and if that element is the subset of the elements it is compared with, it should be popped. For example, [(1, 1)] is the subset of [(1, 1), (1, 2)] then [(1, 1)] should be popped from the list. Similarly, [(1, 1), (1, 2)] is the subset of [(1, 1), (1, 2), (1, 3)] then it should be popped also.
And in this case, we get the output as follows:
[[(1, 1), (1, 2), (1, 3)], [(1, 1), (1, 2), (1, 4)]]

I tried searching for all the possible answers but none was aimed at this particular case.
So far I have tried the following method but of little use:
for i, e in enumerate(mylist):
mylist[i] = tuple(e)
mylist = list(set(mylist))

A: You need to remove any list from mylist where all the tuples in the list are present in another list in mylist. This is most easily done by assigning to a new list:
newlist = []
for i, lst in enumerate(mylist):
    if not any(all(t in l for t in lst) for l in mylist[:i] + mylist[i+1:]):
        newlist.append(lst)

Or as a list comprehension:
newlist = [lst for i, lst in enumerate(mylist) if not any(all(t in l for t in lst) for l in mylist[:i] + mylist[i+1:])]

In both cases, for your sample data the output is:
[
 [(1, 1), (1, 2), (1, 3)],
 [(1, 1), (1, 2), (1, 4)]
]

For larger lists this might become slow, in which case you can speed it up by first mapping the entries in mylist to sets:
mylist=[[(1, 1), (1, 2)], [(1, 1), (1, 2), (1, 3)], [(1, 1), (1, 2), (1, 4)], [(1, 1)]]
mylist=list(map(set, (tuple(l) for l in mylist)))
newlist = [list(lst) for i, lst in enumerate(mylist) if not any(lst.issubset(l) for l in mylist[:i] + mylist[i+1:])]

A: You can use frozenset.issubset and do the comparaison like this example:
Thanks to @Nick suggestion, this is a more elaborated example:
mylist=[[(1, 1)], [(1, 1), (1, 2)], [(1, 1), (1, 2), (1, 3)], [(1, 1),
(1, 2), (1, 4)]]
out = []

for k, elm in enumerate(mylist):
   for elm2 in mylist[:k] + mylist[k + 1:]:
       if frozenset(elm).issubset(elm2):
           break
   else:
       out.append(elm)

print(out)

Output:
[[(1, 1), (1, 2), (1, 3)], [(1, 1), (1, 2), (1, 4)]]

A: Neither solutions from @Nick and @ChihebNexus are efficient.
The answer from @Nick requires a time complexity of O(m ^ 2 x n ^ 2), while @ChihebNexus's answer requires a time complexity of O(m ^ 2 x n), where m is the length of the input list and n is the average length of the sub-lists.
For an approach that requires just a time complexity of O(m x n), you can create a dict that maps each tuple item to a set of the sub-lists the item appears in, keeping in mind that these sub-lists need to be converted to tuples first to become hashable and be added to a set:
mapping = {}
for lst in mylist:
    for item in lst:
        mapping.setdefault(item, set()).add(tuple(lst))

so that with your sample input, mapping becomes:
{(1, 1): {((1, 1),),
          ((1, 1), (1, 2)),
          ((1, 1), (1, 2), (1, 3)),
          ((1, 1), (1, 2), (1, 4))},
 (1, 2): {((1, 1), (1, 2), (1, 3)), ((1, 1), (1, 2)), ((1, 1), (1, 2), (1, 4))},
 (1, 3): {((1, 1), (1, 2), (1, 3))},
 (1, 4): {((1, 1), (1, 2), (1, 4))}}

And then with the mappings of items to their belonging sub-lists built, we can then iterate through the sub-lists again, and take the intersection of the sets of sub-lists that the items in the current sub-list map to, in order to find the sub-lists that contain all the items in the current sub-list. If there are more than one of such qualifying sub-lists, it means that the current sub-list is a subset of the other qualifying sub-lists, and that we can remove the current sub-list from the result by removing it from all the sets its items map to. The sub-lists that survive this process will be the ones we want in the output, which we can obtain by aggregating the sets with a union operation:
for lst in mylist:
    if len(set.intersection(*map(mapping.get, lst))) > 1:
        t = tuple(lst)
        for item in lst:
            mapping[item].remove(t)
print(set.union(*mapping.values()))

This outputs:
{((1, 1), (1, 2), (1, 3)), ((1, 1), (1, 2), (1, 4))}

You can convert it to a list of lists if you really want the exact data types in the question:
list(map(list, set.union(*mapping.values())))

which returns:
[[(1, 1), (1, 2), (1, 3)], [(1, 1), (1, 2), (1, 4)]]


text:
Q: Some issues acessing asset files in production mode I am using Ruby on Rails 4.1.1 and on my local machine I have the following image:
# Directory: MyApp/app/assets/images/
logo.png

I upload MyApp using the Capistrano gem and all seems to work as expected. However when I try to access my website through the browser at the following URLs
1) http://www.myapp.org/logo.png
2) http://www.myapp.org/assets/logo.png
3) http://www.myapp.org/images/logo.png
4) http://www.myapp.org/assets/images/logo.png

then I get an error page:
The page you were looking for doesn't exist.
You may have mistyped the address or the page may have moved.

In the log file I get:
1) ActionController::RoutingError (No route matches [GET] "/logo.png"):
2) ActionController::RoutingError (No route matches [GET] "/assets/logo.png"):
3) ActionController::RoutingError (No route matches [GET] "/images/logo.png"):
4) ActionController::RoutingError (No route matches [GET] "/assets/images/logo.png"):

  actionpack (4.1.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (4.1.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.1.1) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.1.1) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.1.1) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.1.1) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.1.1) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.1.1) lib/active_support/cache/strategy/local_cache_middleware.rb:26:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.1.1) lib/rails/engine.rb:514:in `call'
  railties (4.1.1) lib/rails/application.rb:144:in `call'
  railties (4.1.1) lib/rails/railtie.rb:194:in `public_send'
  railties (4.1.1) lib/rails/railtie.rb:194:in `method_missing'
  /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.45/lib/phusion_passenger/rack/thread_handler_extension.rb:74:in `process_request'
  /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.45/lib/phusion_passenger/request_handler/thread_handler.rb:141:in `accept_and_process_next_request'
  /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.45/lib/phusion_passenger/request_handler/thread_handler.rb:109:in `main_loop'
  /usr/local/rvm/gems/ruby-2.1.1/gems/passenger-4.0.45/lib/phusion_passenger/request_handler.rb:448:in `block (3 levels) in start_threads'

What is the problem and how can I solve it?

*

*In my local machine (development mode) I do not have problems.

*My remote machine runs Ubuntu 12.04 LTS, Phusion Passenger 4.0.45,
Apache 2.2.22.

A: All assets that are compiled in Production have a fingerprint ID appended to the file name.  Therefore, in production, logo.png does not technically exist anymore.  What should exist now is logo-SOME_FINGERPRINT_ID.png.  See more info here:
http://guides.rubyonrails.org/asset_pipeline.html#what-is-fingerprinting-and-why-should-i-care-questionmark
Also, if you wish to serve just the static image, you will need to put it in the images dir of the public folder.  You will then need to tell Apache or Nginx to serve static assets from that location.
EDIT:  To link to an image in your Asset Pipeline -
link_to(LINK_TEXT_OR_IMAGE_TAG_HELPER, image_path(IMAGE_NAME))

Asset Url Helper


text:
Q: Will Windows 2008 or Windows 7 interfere with a network of Windows 2003 servers Our network is currently comprised of Windows 2003 servers and Windows XP workstations.  Within the next few months, our PC deployment group plans to start rolling out workstations with Windows 7.  In addition, one of our vendors just sent us an e-mail stating that their next version of the software due out in the next few months will require Windows 2008 and no longer support Windows 2003.
Now, our system administrator is telling us that Windows 7 and Windows 2008 will interfere with our network because our main servers (Active Directory, DNS, etc) are Windows 2003 servers.  They will force master browser elections and so on...
Is he correct?  Will they interfere?  I would have thought this would be a larger issue if this was indeed the case.  Links to any documentation regarding this matter would be appreciated.

A: In one way, introducing Windows 2008 and Windows 7 will interfere with master browser elections in NetBIOS.  That being said, this is not an issue for many different reasons.
First, you need to know that master browser selection is based on domain controller status and Windows version (this is where 2008 comes in to play).  The PDC emulator will always win master elections no matter what OS level they are at.  For broadcast domains where the PDC emulator role is not running, domain controllers will try to become the master.  Finally, if no DC is available then the highest Windows version will win the election.
With that being said, very few applications rely on NetBIOS these days.  Almost all Microsoft applications and third party applications will resolve through DNS, not NetBIOS.
Additionally, anyone relying on NetBIOS will have WINS deployed on the network.  WINS removes the reliance on master browsers and allows NetBIOS to operate across subnets.  Windows clients configured with a WINS server will default to H-nodes which means they query WINS before doing a broadcast for name resolution.
Once that is all said and done, if you still needed NetBIOS, did not run WINS and had no domain controllers on a network, introducing Windows 2008 or Windows 7 would allow them to become master browsers on your network.  Even if that were the case, Windows 2008 and Windows 7 will happily act as master browsers without any negative effects.  If you still didn't want that to occur, then simply set the MaintainServerList and IsDomainMaster to No and False respectively.
http://technet.microsoft.com/en-us/library/cc959923.aspx
/me steps out of time machine...

A: Provided your new servers are only member servers and nothing fundamental to the operation of your domain, you won't have any nonsense at all. Speaking from experience, my first 2008 R2 file server went into my environment (which was totally 2003) without a hitch.
Even if you decided your new 2008 servers were going to start hosting Active Directory and all its associated stuff, it would cause you no more real grief than any other major change like this on 2003.
People knock Microsoft so often, but they really DO go to ridiculous lengths to ensure application compatibility. This is especially true of Microsoft software, but still a great deal of compatibility work goes into ensuring your legacy apps keep working too. After all, if stuff didn't work with newer versions of Windows, what's the point of upgrading at all?

A: Is your sysadmin stuck in 1996? He's worried about Master Browser elections in a Win2k3 AD? Ask him for specific documented problems - it's possible that you may have some serious legacy applications, but if that's the case you should have a WINS infrastructure and lock down the NetBIOS NodeType on the machines with GPOs (or maybe DHCP.)
Or he may be referring to something else when you say he said "...and so on..." ; like I said, press him for details and then research those details. Because in general, the scenario you describe is not a problem.

A: We have run pretty much all flavors of windows servers and clients in a 2003 level domain. No problems related to that at all. Separating our group from another we set up a separate 2008 domain and migrated 2003 R2 and 2008 servers to it. No issues there either. In my experience AD is one of the things that MS has got right.
Migrating AD from 2003 to 2008/2008 R2 is well documented and MS and sites all over has lots of articles and how-to's on that. I recommend you dig out some nice documentation and get up to date.

A: Master Browser only affect NetBIOS resolution, which should not be an issue in an Active Directory environment in the first place, as you should be relying on DNS instead of NetBIOS. If you do not trust DNS somehow, you should set up WINS server (maybe on the domain controller) and point all your computers to the WINS server via DHCP.
No matter what, you want to replace your master browsers with WINS server to cut down on vulnerabilities and network broadcast (bad security + bad network performance). My network has Windows 2003, Windows 2008, XP, Vista and 7, and we do not have any issues.


text:
Q: Special characters in flyway.conf password How are special characters (\,#,:,=) in flyway.conf handled? Do they have to be escaped as in a .properties, or do they have to be written down as literals?

A: They are not and it is a awful bug. workaround is to set flyway.password instead of using param -password


text:
Q: Is the span closed? Let X be a normed space. Let $v_1, v_2... v_n$ be vectors in X. When is $Span({v_1, v_2, ... v_n})$ closed?
This question is motivated by a question which I had on a problem sheet (this wasn't the exact topic of the question but a required assumption for the proof), which said a span of finite set of vectors from a Hamel Basis of a Banach Space is closed. I'm not sure why that is and I'm not sure in general when the Span is closed, thanks!

A: It always is. That span, endowed with the restricted norm, is a finite-dimensional normed space, and therefore it's bi-Lipschitz isomorphic to $\Bbb R^k$ for some $k\le n$. Therefore the restricted metric is complete. A subspace of a metric space for which the restricted metric is complete is necessarily closed.


text:
Q: Should simultaneously having multiple different SQLite Database Versions be considered harmful? I am breaking out each SQLite table's code (including initial construction of the table as well as operations on that table) into separate classes extending SQLiteOpenHelper.
In order to get these tables to be created (that is to say, to get the onCreate() method to be called), I have to increment the DATABASE_VERSION (see my own answer here for the details).
But with this methodology, I end up with different version numbers for each class/table - I had to set the DATABASE_VERSION value for the second table I created to 2, I will have to set the third one to 3, etc.
So I will end up with multiple different version values for the same DATABASE (*.db file). If they are all the same val, the onUpgrade() method does not get called, and thus, the onCreate() method is not called, and thus the new table is not created.
Is this "okay" - having a database with several different simultaneous version numbers?
The only other (reasonable) option I know of is to put all the DB code (covering multiple tables) into a single class that extends SQLiteOpenHelper - is doing so actually the preferred method? IOW, is my separation of the db code into several classes, one for each table, a help or a hindrance?
UPDATE
So this is my non-destructive way (by inserting "IF NOT EXISTS" into the DDL) to gradually add new tables, using, per CommonsWare's advice, just one class that extends SQLiteOpenHelper:
@Override
public void onCreate(SQLiteDatabase db) {
    String CONDITIONALLY_CREATE_VENDORS_TABLE = "CREATE TABLE IF NOT EXISTS " +
            TABLE_VENDORS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_VENDORID
            + " TEXT," + COLUMN_COMPANYNAME + " TEXT" + ")";
    db.execSQL(CONDITIONALLY_CREATE_VENDORS_TABLE);
    // add more tables as needed following the pattern above
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //db.execSQL("DROP TABLE IF EXISTS " + TABLE_VENDORS); <= Only need to DROP if the table's structure changes; so comment such a line out for the particular table in that case
    onCreate(db);
}

NOTE: Whenever I do add a new table, I have to "up" (increment) the DATABASE_VERSION value, so that onUpgrade()/onCreate() are called.

A:
I am breaking out each SQLite table's code (including initial construction of the table as well as operations on that table) into separate classes extending SQLiteOpenHelper

It is important, for thread safety among other reasons, to have a single instance of SQLiteDatabase that you use consistently. That in turn, will require you to have a single SQLiteOpenHelper class. The exception would be for totally independent database files (one SQLiteHelper per database), but that's not usually needed.

Is this "okay" - having a database with several different simultaneous version numbers?

That is not "okay" at all. The highest number wins.

The only other (reasonable) option I know of is to put all the DB code (covering multiple tables) into a single class that extends SQLiteOpenHelper - is doing so actually the preferred method? IOW, is my separation of the db code into several classes, one for each table, a help or a hindrance?

Breaking out "the db code into several classes, one for each table" is not necessarily a problem. What is a problem is having them be independent subclasses of SQLiteOpenHelper.
Let's say that you want these classes not merely to handle table creation and upgrades, but also other CRUD operations related to the table. Having a dedicated class for that is fine. However, the table creation and upgrade logic needs to be driven by a single SQLiteOpenHelper class. Simply have onCreate() and onUpgrade() on your SQLiteOpenHelper delegate the actual work to the per-table classes. This way, you get your code organization, without having multiple SQLiteOpenHelper classes.


text:
Q: Chromedriver for chrome version 65 I am working on py script with selenium for taking screenshot of web page from Chrome browser version 65. I cant find compatible Chromedriver for this chrome version 65 in official website.
I used chromedriver version for 71 (oldest available chromedriver)and it threw this error
  File "selenium\webdriver\chrome\webdriver.py", line 81, in __init__
  File "selenium\webdriver\remote\webdriver.py", line 157, in __init__
  File "selenium\webdriver\remote\webdriver.py", line 252, in start_session
  File "selenium\webdriver\remote\webdriver.py", line 321, in execute
  File "selenium\webdriver\remote\errorhandler.py", line 242, in check_response
selenium.common.exceptions.SessionNotCreatedException: Message: session not created: Chrome version must be between 71 and 75
  (Driver info: chromedriver=2.46.628402)

Where can i download driver for chrome version 65. Or any other option to fix this error. Please help. Thanks.

A: I believe you could try ChromeDriver 2.36, but it is outdated, and may not work. => https://chromedriver.storage.googleapis.com/index.html?path=2.36/. According to the notes, the ChromeDriver Supports Chrome v63-65.


text:
Q: Lazy load not working with filtrify and Isotope <script type="text/javascript">
$(function() {

    $("ul#container img").lazyload({
        event : "mouseover",
        effect : "fadeIn"
    });

    var container = $("#container");

   container.isotope({
        itemSelector : 'ul#container > li',
        layoutMode : 'masonry'
    });

  var ft =  $.filtrify("container", "placeHolder", {
        block    : "data-original",
        hide     : false,
        close    : true,
        callback : function ( query, match, mismatch ) {
          /*
        Extend jQuery with an "inview" selector to
        select elements that are in the visible
        part of the page (at least partiacialy)
    */
    $.extend($.expr[':'],{
        inview: function(el) {
            var e = $(el),
                w = $(window),
                wt = w.scrollTop(),
                wb = wt + w.height(),
                et = e.offset().top,
                eb = et + e.height();

            return ( (eb >= wt) && (et <= wb) );
        }
    });
     $("ul#container img").lazyload({
        event : "scroll filter",
        effect : "fadeIn"
    });
    $(match).find("img:inview").trigger("filter");
            container.isotope({ filter : $(match) });
            if ( mismatch.length ) $("div#reset").show();
            else $("div#reset").hide();
             }
    });
    $("div#reset span").click(function() {
        ft.reset();
    });

});
</script>

A: Had the same issue. Looked through the lazyload code. If "scroll" is anywhere in the event it ignores everything else.
Initially I did a page scroll trigger. But I had a css issue where the windows thinks the image was in it's original location. So it thought it was off the page. :(
I did notice however that lazyload will always run on event "appear".
So changing
$(match).find("img:inview").trigger("filter");

to
$(match).find("img:inview").trigger("appear");

will work. Though it will force all $(match) images to load even if they aren't visible.
Not best solution I know.  But...


text:
Q: Play framework does not see JRE I have just started to learn Play! Framework, but I got an error right at the beginning. Following the instructions I created a new project and wanted to run it, so I typed in:
play run ./app/first

It gave me the following result:
Error opening registry key 'Software\JavaSoft\Java Runtime Environment'
Error: could not find java.dll
Error: could not find Java SE Runtime Environment.

Of course there is a java.dll file in the Java directory.
I'd even obtained the newest java version, if I type in java -version, the result is:
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)

I am using Windows 7 x64. What causes the error and how could I resolve it?

A: As the message indicates there seem to be an error with the registry settings for the Java runtime.
If you set the environment variable JAVA_HOME to the path where you know the Java runtime to be installed in the same command window that you will run "play run" in using the command
set JAVA_HOME=c:\Program files\Java\jre6 (or wherever your Java runtime is installed)

You shold then be able to run Play in the current command window.
The easiest way to fix this issue permanently is to reinstall the JavaSE runtime using an installer downloaded from Oracle's download site


text:
Q: Verificar se utilizador existe Como posso em bash verificar se um utilizador existe, mas de forma a que o script funcione em múltiplos sistemas ?
Um exemplo limitado:
grep <username> /etc/passwd

Não funciona em sistemas que usam NIS ou LDAP para gerir os utilizadores.

A: O comando getent deverá funcionar neste caso.
getent passwd <usuario>

O comando getent exibe entradas de bancos de dados suportados pelo Service Switch libraries, que são configuradas no arquivo /etc/nsswitch.conf.
Uma outra alternativa que pode funcionar neste caso, é verificar se o ID do usuário é válido através do comando id, usando com a opção -u:
if id -u "usuario" > /dev/null 2>&1; then
        echo "Utilizador existe"
else
        echo "O utilizador especificado não existe"
fi


text:
Q: Placing conditional div tags in React JS render I'm new to react and I'm trying to put some div tags in the render block based on some conditions. I'm iterating through an array and I want to split the rendered data into blocks of 3, i.e.
array.map((data, index) => {
   if(index % 3 === 0) {

   }

Displaying index {i} , data is: {array[i]}

   if(index % 3 === 0) {

 //Close for topLayer

 //Close for container
   }
})

However this doesn't work out as it expects a closing div tag within the if condition. Is it possible to do something of this sort?
If there was no conditional logic, the only thing required would have been :
array.map((data, index) => {
   return(

Displaying index {i} , data is: {array[i]}

 //Close for topLayer

 //Close for container
   })
})

A: you have to return an element instead of just adding the div tag you need to do return

 in each if block and a default one if all conditions fails - alternatively you could use a ternary operator in that case you don't need to use the return statement

A: I suppose if you are trying to add a new block or something. Try like below which will give an idea.
export default function App() {
  const arrayData = ["1", "2", "3", "4", "5", "6"];

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      {arrayData.map((data, index) => {
        return (

                  Displaying index {index} , data is: {arrayData[index]}

                {(index + 1) % 3 === 0 ?
 : undefined}

        );
      })}

  );
}

Where a break-line will be added after every 3 chunks of data.


text:
Q: Prop is missing and the compiler does not complain I am trying to create Elevate App Bar as the following:
interface Props {
  children: React.ReactElement;
}

function ElevationScroll({ children }: Props) {
  const trigger = useScrollTrigger({
    disableHysteresis: true,
    threshold: 0
  });

  return React.cloneElement(children, {
    elevation: trigger ? 4 : 0
  });
}

export function ElevateAppBar(props: Props) {
  return (
    <React.Fragment>
      <CssBaseline />
      <ElevationScroll {...props}>
        <AppBar>
          <Toolbar>
            <Typography variant="h6">Scroll to Elevate App Bar</Typography>
          </Toolbar>
        </AppBar>
      </ElevationScroll>
      <Toolbar />
      <Container>
        <Box my={2}>
          {[...new Array(120)]
            .map(
              () => `Cras mattis consectetur purus sit amet fermentum.
Cras justo odio, dapibus ac facilisis in, egestas eget quam.
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Praesent commodo cursus magna, vel scelerisque nisl consectetur et.`
            )
            .join("\n")}
        </Box>
      </Container>
    </React.Fragment>
  );
}

the component is used in the index.tsx:
import React from "react";
import ReactDOM from "react-dom";
import { ElevateAppBar } from "./demo";

ReactDOM.render(<ElevateAppBar />, document.querySelector("#root"));

ElevateAppBar expects prop and I did not pass any. However I expect that the compiler will complain, but it does not. Why?
https://codesandbox.io/s/material-demo-forked-0r0of


text:
Q: Python Text Adventure Game Input Infinite Loop I am a beginner learning to code python by creating a text adventure game. I am using multiple resources and no tutorials. I have created the beginning scene where it asks you for your input, or a command to do something. My commands that interact with objects (the broom and the chair) work fine. I am having issues changing scenes, checking my inventory and looking at my surroundings. When I input these commands it simply requests my input again instead of displaying the inventory list, describing my surroundings (using the function cabinFrontPorchAction) and changing my location to the cliff and displaying information about the cliffs.
Here is my entire code with the portion I am having trouble with sectioned out  with #'s
# text game (similar to zork)
name = 1

location = "cabinFrontPorch"

loadWeight = 0

description = {
    "chair" : "It is a wooden chair there is really nothing special about it. Probably good for pondering lifes greatest questions.",
    "broom": "It is a wooden broom with old-fasioned straw bristles. It looks like a witch would love one of these bad boys!"
}

weightList ={
    "broom": 3,

}

inventory = [
  "",
]

cabinFrontPorch = [
  "chair",
  "broom",
]

heavy = [
    "chair",
    ]

goCommand = [
  "go north",
  "go south",
  "go east",
  "go west",
  "go up",
  "go down",
  "go northwest",
  "go northeast",
  "go southeast",
  "go southwest",
]

objectCommand = [
  "get",
  "drop",
  "push",
  "pull",
  "examine",
  "use",
  "attack"
]

def addWeight(x):
  global loadWeight;
  loadWeight = loadWeight + x;

def listItem(list):
  for item in list:
    print("There is also a " + item)

def objectAction(object, location, action):
    if object in inventory or object in location:
            if action == "get":
                if object not in inventory:
                    if loadWeight <= 10:
                        if object in heavy:
                            #Create heavy list
                            print("The " + object + "is too heavy to carry")
                        else:
                            inventory.append(object)
                            location.remove(object)
                            print("Taken.")
                            x = weightList[object]
                            addWeight(x)
                            print("Your are carrying " + str(loadWeight) + "/10 units of weight.")
                    else:
                        print("You have too much stuff in your hands")
                else:
                    print("You already have that in your hand")
            elif action == "push":
                if object not in inventory:
                    if object in pushable:
                        print("This object is pushable")
                    else:
                        print ("Why are you so intent on disturbing the " + object + "? It is just a " + object + "!")
                else:
                    print("You can't push this because it is in your inventory")
            elif action == "pull":
                if object not in inventory:
                    if object in pullable:
                        print("This object is pullable")
                    else:
                        print ("Why are you so intent on disturbing the " + object + "? It is just a " + object + "!")
                else:
                    print("You can't pull this because it is in your inventory")
            elif action == "examine":
                print(description[object])
                #write description dictionary
            elif action == "use":
                print("You sit down for a while taking this time to enjoy life and ponder the deeper philosophies if the world. You realize that there is an entire world out there that is yours for the taking but you also know that you aren't going to accomplish anything just sitting in a chair all day. It is with this that you realize you just wasted time by sitting in a chair.")
            elif action == "drop":
                if object in inventory:
                    print("Dropped.")
                    location.append(object)
                    inventory.remove(object)
                else:
                    print("You can't drop something that's not already in your inventory")
            elif action == "attack":
                print("I've seen some crazy stuff but I've never seen someone attack an " + object + "!")
    else:
        print("The " + object + " is not in this area.")

def intro():
  print("Welcome to Korz!")
  print("")
  print("In this world of interactive fiction you will")
  print("find lots of treasure, monsters and puzzles to")
  print("test the limits of your human mind")
  print("You will be able to LOOK at your surroundings")
  print("EXAMINE certain objects")
  print("USE objects")
  print("ATTACK monsters")
  print("OPEN and CLOSE doors")
  print("PUSH and PULL objects")
  print("GET and DROP items")
  print("You may view your inventory at anytime")
  print("And perhaps most importantly GO places")
  print("(UP DOWN NORTH SOUTH EAST WEST)")
  print("It is now up to you to use this virtual world")
  print("To explore all of the possibilities and to have")
  print("an amazing ADVENTURE")
  name = input("What is your NAME Adventurer? \n>>>")
  print ("Allright " + name +"! You are on your own from here! Have Fun!")
  cabinFrontPorchAction()

def cabinFrontPorchAction():
  location = "cabinFrontPorch";
  print("You are standing on the porch on the north side of a log cabin")
  print("To the north of the porch is a forest with lush evergreen trees")
  print("East of the cabin is a creek that runs north to south through the woods")
  print("West of the cabin are sheer cliffs that look out over a vast blue ocean")
  listItem(cabinFrontPorch)
  while location == "cabinFrontPorch":
    requestInputCFP()
###########################################
def requestInputCFP():
    action = input(">");
    action = action.lower();
    action = action.split();
    if action in goCommand:
        if action == "go south":
            print ("The door is locked shut. To go this direction unlock the door")
        elif action == "go west":
            cliff()
    elif action == "inventory":
        if not inventory:
            print("You are empty handed")
        else:
            print(inventory)
    elif action == "look":
        cabinFrontPorchAction();
    elif len(action) > 1:
        if action[1] == "broom":
            objectAction("broom" ,cabinFrontPorch, action[0])
        elif action[1] == "chair" or action[1] == "wooden":
            objectAction("chair" , cabinFrontPorch, action[0])

def cliff():
  location = "cliff";
  print("You come up to the edge of a sheer cliff just east of a vast blue ocean.")
  print("It would be impossible to get down to the beach this way.")
  print()
########################################################
intro()

A: I think it has to do with your action.split(). This command will split on spaces and returns an array: see the documentation on split(). In essence this is what happens:
Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> action = "go north"
>>> action = action.split()
>>> print (action)
['go', 'north']
>>> "go north" == action
False
>>>

As you can see the array is not equal to the "go north" comman,d and thus it is not in your list of valid commands.


text:
Q: filling a vector with a numberline from negative to positive in R I want to create a range of values with a +/- interval given a mid point. The mid point and intervals are variables and can change.
For example, if my mid point is 0 and my interval is 5, I want my vector to be comprised of
[-5,-4,-3,-2,-1,0,1,2,3,4,5]

If my mid point is 140 and interval is 5, the vector would be
[135,136,137,138,139,140,141,142,143,144,145]

I initially thought this would be easy to do in a single for loop. But I am totally stumped on how to do this in an elegant fashion in R
The only way I can think off is to calculate the negative and positive values separately and then join the elements to form a vector.

A: You could use this which uses the seq() function:
mid_int <- function(mid_point, interval) {
  seq(mid_point - interval, mid_point + interval, by = 1)
}

mid_int(0, 5)
 [1] -5 -4 -3 -2 -1  0  1  2  3  4  5

mid_int(140, 5)
 [1] 135 136 137 138 139 140 141 142 143 144 145


text:
Q: Spring Data JDBC - Clob column to String property in POJO not working I have an Oracle database with a table that has a DESCRIPTION column of type CLOB.
My POJO looks like this:
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

import org.springframework.data.relational.core.mapping.Column;
import org.springframework.data.relational.core.mapping.Table;
import org.springframework.data.annotation.Id;

import lombok.Data;

@Data
@Table("MY_ITEMS")
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyItem {

    @Column("ID") @Id Long id;
    @Column("DESCRIPTION") String description;
}

And my repository looks like this
import java.util.List;

import com.myapp.mymodel.MyItem;

import org.springframework.data.jdbc.repository.query.Query;
import org.springframework.data.repository.CrudRepository;

public interface MyItemsRepository extends CrudRepository<MyItem, Long> {

    // other methods deleted...

    @Query(
        "select m.ID"
            + ", m.DESCRIPTION"
        + " from MY_ITEM m "
    )
    List<MyItem> findMyItems();
}

When I call the repository method I get an error saying there is no converter for CLOB to String.
Any help is appreciated.

A: There's a very nice example here that solves the problem:
https://github.com/spring-projects/spring-data-examples/tree/master/jdbc/basics
The solution amounts to adding a configuration that registers a converter that can extract the CLOB data to the String property
import java.sql.Clob;
import java.sql.SQLException;
import java.util.Arrays;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.jdbc.core.convert.JdbcCustomConversions;
import org.springframework.data.jdbc.repository.config.AbstractJdbcConfiguration;
import org.springframework.data.jdbc.repository.config.EnableJdbcRepositories;
import org.springframework.data.relational.core.mapping.Embedded.Nullable;

@Configuration
@EnableJdbcRepositories
public class AggregateJdbcConfiguration extends AbstractJdbcConfiguration {

    @Override
    public JdbcCustomConversions jdbcCustomConversions() {

        return new JdbcCustomConversions(Arrays.asList(new Converter<Clob, String>() {

            @Nullable
            @Override
            public String convert(Clob clob) {

                try {

                    return Math.toIntExact(clob.length()) == 0 //
                            ? "" //
                            : clob.getSubString(1, Math.toIntExact(clob.length()));

                } catch (SQLException e) {
                    throw new IllegalStateException("Failed to convert CLOB to String.", e);
                }
            }
        }));
    }
}

Here are a few of my favorite videos on the subject
https://www.youtube.com/watch?v=EaHlancPA14&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=3&t=0s
https://www.youtube.com/watch?v=GOSW911Ox6s&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=4&t=59s
https://www.youtube.com/watch?v=AnIouYdwxo0&list=PLsC0nE-wJ1I4ra6KYXTPOXipdrJ_IdhaO&index=5&t=2730s
And a couple of blog posts
https://spring.io/blog/2018/09/24/spring-data-jdbc-references-and-aggregates
https://spring.io/blog/2018/09/17/introducing-spring-data-jdbc


text:
Q: Is there a better way of displaying 'Count' of records beside other columns in a select query? I have a table with below structure :
Test1(c_num  number ,c_first_name varchar2(50), c_last_name varchar2(50))

1)There is a normal index on c_num column.
2)The table has nearly 5 million records.
I have a procedure as you can see below. I want to display the Count(*) along with other columns.I want to know if there are better ways of doing this so that we can have better performance.
create or replace procedure get_members(o_result out sys_refcursor)
  is
begin

open o_result for
  select c_num,
         c_first_name,
         c_last_name,
         (select count(*) from test1) members_cnt -->Is there a better way instead of doing this?
  from test1;

end;

Thanks in advance

A: What you used there should not cause a problem, because it is a scalar subquery, meaning its result would be automatically cached, and as it has only 1 distinct value, even if test1 has 5 million rows, the inner query would not be executed 5 million times.
But you can use the analytic version of count:
select c_num,
       c_first_name,
       c_last_name,
       count(*) over () as members_cnt
from test1;


text:
Q: Getting info on a Kind inference bug in GHC Edward Kmett reported a bug in kind inference which is pretty annoying for his category library some time ago.
I can't tell if this has been solved or not in some later version of GHC. It seems to be present in 8.10.7 and 9.0.2.
{-# LANGUAGE PolyKinds #-}
class D a => C (f :: k) a
class C () a => D a

data W f (a :: k) where
  MkW :: W Maybe Int -> W f a

How to get information on this (like : will it be solved or not) ?

A: This does not answer the question that was asked ("when will the bug be fixed?"), but I think it might be useful to know that adding explicit kind signatures makes this compile with GHC 8.10.5 and GHC >= 9 (provided some extensions are enabled).
-- extensions for GHC 8.10.5
{-# LANGUAGE UndecidableInstances, ExplicitForAll,
    PolyKinds, UndecidableSuperClasses,
    StandaloneKindSignatures, MultiParamTypeClasses,
    FlexibleContexts #-}

import Data.Kind

type D :: Type -> Constraint
type C :: forall k. k -> Type -> Constraint

class D a => C (f :: k) a
class C () a => D (a :: *)


text:
Q: Pine: I have to convert this into pine v4 or v5 to publish on tradingview I have to convert this into pine v4 or v5 to publish on tradingview. Please suggest  what to modify/add.
enter code here

study(title="3 Moving Averages", shorttitle="50,100,200 MAs", overlay=true)
exponential = input(true, title="50,100,200 Exponential MA")

src = close

ma50 = exponential ? ema(src, 50) : sma(src, 50)
ma100 = exponential ? ema(src, 100) : sma(src, 100)
ma200 = exponential ? ema(src, 200) : sma(src, 200)
plot( ma50, color=fuchsia, style=line, title="MMA50", linewidth=1)
plot( ma100, color=green, style=line, title="MMA100", linewidth=1)
plot( ma200, color=orange, style=line, title="MMA200", linewidth=1)

A: //@version=5
indicator('Moving Averages', '50,100,200 MAs', true)
exponential = input(true, '50,100,200 Exponential MA')

src = input.source(close, "Source")

ma50 = exponential ? ta.ema(src, 50) : ta.sma(src, 50)
ma100 = exponential ? ta.ema(src, 100) : ta.sma(src, 100)
ma200 = exponential ? ta.ema(src, 200) : ta.sma(src, 200)
plot(ma50, color=color.new(color.fuchsia, 0), title='MMA50', linewidth=1)
plot(ma100, color=color.new(color.green, 0), title='MMA100', linewidth=1)
plot(ma200, color=color.new(color.orange, 0), title='MMA200', linewidth=1)

A: In pine editor, look for the 3 dots on the right (next to publish). You will see an option to auto convert.


text:
Q: Completed 200 OK in 652ms (Views: 50.9ms | ActiveRecord: 18.3ms) I'm trying to understand this line in the rails log
If my views only took 50.9ms why is it taking 652ms?
Thanks

A: If you're running your application in the development environment it has to reload a lot of your application's files on every request.  That would be my guess as to why it's taking so long.
You could try going into environments/development.rb and setting config.cache_classes = true to see what kind of effect this has on your render times, but remember to change this back to config.cache_classes = false and restart your server once you're done.


text:
Q: How to set the language in a html document via r markdown html I am using a .Rmd documment and rendering to html_document. The prefix of my tables come as "Table", however, I want it in my first language. As in pdf_document, I want to set the language of my report to portuguese, like this:
---
title: "Code"
author: "Guilherme"
date: "May 9, 2017"
lang: "pt-br"
output:
  html_document: default
---

Is there a way to do that?

A: If I knit:
---
title: "Code"
author: "Guilherme"
date: "May 9, 2017"
lang: "pt-br"
output:
  bookdown::html_document2
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r cars}
library(knitr)
kable(mtcars[1:5,2:3], caption = "Azul")
```

with a file called _bookdown.yml in the same directory with this content:
language:
  label:
    fig: "Figura "
    tab: "Tabela "

it produces the labeling correctly, as @Sébastian suggested in the comments

A: There is no way to do this with the htmlTable package because the "Table no" bit is hardcoded into this package (see the source code).
If you want localization, thus, you'll need to use another way to produce captions. An alternative is the captioner package.
```{r}
library(htmlTable)
library(captioner)

table_nums <- captioner(prefix = "Tabela") # from google translate :)

htmlTable(table(iris$Species,iris$Species),
          caption = table_nums("desc_iris", "Descriptive Measuraments of..."))
```