text:
Q: Uniqueness of quantum ladder for the harmonic oscillator Context:
Griffith's book on Quantum Mechanics (QM), in Section 2.3.1, tries to solve for the stationary states $\psi(x)$ of a harmonic oscillator by solving the Time-Independent Schrodinger Equation (TISE),
$$\frac{1}{2m}[p^{2}+(m\omega x)^{2}]\psi=E\psi,$$
using the method of ladder operators. The ladder operators' method starts from a postulated definition of $a_{+}$ and $a_{-}$ (eq. 2.47):
$$ a_{\pm}\equiv \frac{1}{\sqrt{2\hbar\omega m}} (\mp i p+m\omega x),$$
which then was shown to work in terms of factorizing the Hamiltonian $H=[p^{2}+(m\omega x)^{2}]/(2m)$, and thus used to raise/lower energy in discrete steps. The discussion comes to a head in p.46 and footnote 21, where it is concluded that "we can construct all the stationary states" by repeated application of this operator $a_{+}$ starting from the lowest energy level (rung) on the ladder, $E_{0}$, and that such ladder is unique because two ladders with the same step size ($\hbar \omega$) and common first rungs will completely overlap and therefore be identical.
However, from a logical point of you, there might be a little issue for the reader up to this point as it was not proven (or discussed) that such operators ($a_{+}$,$a_{-}$) and their ensuing ladder (with $\pm \hbar \omega$ step size) were the only possible ones that could represent the Hamiltonian (i.e. no uniqueness was discussed), and therefore one might start to imagine an example of another set of possible operators that produce steps of half the size of the ones discussed (so, $\hbar \omega/2$, instead of $\hbar \omega$), and produce a different ladder, that will still overlap with the original ladder, even for common bottom rung ($E_{0}$), but with twice the number of rungs. By extension, an infinite number of such ladders of step size equal to $\hbar \omega/n$, where $n$ is integer, might be imagined in this sense, and they would still not conflict each other.  Such uniqueness is not rigorously discussed.

The issue:
I think that the key to concluding that we only have one unique ladder is to:

*

*first prove that all operators would produce ladders with the same bottom rung;

*and then to show that the original operators ($a_{\pm}$) actually give the smallest energy step size (resolution) among all admissible operators/ladders (and thus be our only choice for operators, because other operators would be simply just integer multiples of them). But there is an issue here, as described below.

Point (1) is easy to prove: any new operators like $a^{2}_{-}$, $a^{2}_{+}$, or indeed any generalization thereof ($a^{m}_{-}$, $a^{m}_{+}$, for $m\in \mathbb{Z}$), share the same bottom rung with the original ladder operators ($a_{-}$ and $a_{+}$). I can prove this rigorously as follows: say that we have $m=2$, and we wish to find its lowest rung state (call it $\bar{\psi_{0}}$ for this case, to distinguish it from the original case $\psi_{0}$), then we find it by putting:
\begin{eqnarray}
a_{-}a_{-}\bar{\psi_{0}}&=&0 \nonumber\\
\Rightarrow a_{+}a_{-}(a_{-}\bar{\psi_{0}})&=&0 \nonumber\\
\Rightarrow (a_{-}a_{+}-1)(a_{-}\bar{\psi_{0}})&=&0 \nonumber\\
\Rightarrow a_{-}\bar{\psi_{0}}&=&a_{-}\underbrace{(a_{+}a_{-}\bar{\psi_{0}})}_{=(0)\bar{\psi_{0}}=0} \nonumber\\
\Rightarrow a_{-}\bar{\psi_{0}}&=& 0 \nonumber
\end{eqnarray}
\begin{equation}
\Rightarrow \boxed{\bar{\psi_{0}} \equiv \psi_{0}}, \nonumber
\end{equation}
which proves that all such ladders definitely share the same rung (I have used the fact that $a_{+}a_{-}\psi_{n}=n\psi_{n}$ in the above reduction to zero). Similar proofs can be done for higher $m$.
However, point (2) is proving to be more subtle and addresses the possibility of constructing new operators that are not of the form $a^{m}_{-}$, $a^{m}_{+}$, for $m\in \mathbb{Z}$. We note that the entire choice of operators $a_{-}$, $a_{+}$ as equal to: $(\text{constant})[\pm\hbar D + m\omega x]$, where $D\equiv\frac{d}{dx}$, was originally based simply on them producing a second-order derivative ($D^{2}\equiv\frac{d^{2}}{dx^{2}}$) when multiplied together, to match the Time-Independent Schrodinger Equation (TISE). Since TISE is second-order, the choice of $a_{\pm}$ was made to have each operator with a first-order derivative operator ($D$), which is a natural choice. Then it was proved that their product is of the form:
$$b_{-}b_{+}\ \ \ \varpropto \ \ \  \left[\underbrace{-\hbar D^{2}+(m\omega x)^{2}}_{=2 m H} + \text{some constant} \right],$$
(here I chose letter $b_{\pm}$ to generalize the discussion and to later distinguish it from the original operator $a_{\pm}$) which is later written in $H$ in the following form
$$ H= \hbar\omega\left( b_{-}b_{+} - \phi \right)\ \ \ ;\ \ \ H= \hbar\omega\left( b_{+}b_{-} + \phi \right),$$
where $\phi$ is some constant. And this will give us later
$$ \text{Commutator}[b_{-},b_{+}]=2\phi, $$
which later gives us the key conclusions that energy jumps in steps as
$$ \boxed{H(b_{-}\psi)=[E-(2\phi)\hbar\omega]\ \psi \ \ \ ;\ \ \ H(b_{+}\psi)=[E+(2\phi)\hbar\omega]\ \psi}. $$
Now, yes, clearly, if we choose operators $b_{\pm}$ like before to be some higher integer order of the original operators $a_{\pm}$ (such as $a^{m}_{\pm}$, with $m\in\mathbb{Z}$), then clearly they will have LARGER steps on the ladder, and therefore $a_{\pm}$ are the operators with the finest allowed resolution of steps (smallest allowed step). And since we have proved (above) that the first rung is shared by all such operators ($a^{m}_{\pm}$, with $m\in\mathbb{Z}$), then the original $a_{\pm}$ operators are unquestionably brilliant and unique. But, what if we chose operators $b_{\pm}$ that are not of the form $a^{m}_{\pm}$, with $m\in\mathbb{Z}$ ? What if I chose fractional derivatives, for example, such as $D^{1/2}$ or $D^{3/2}$ (which are also formal operators in applied mathematical analysis--- e.g. see wiki page), which when multiplied will still give second-order ($D^{2}$), and therefore may factorize $H$ and represent the TISE equation? In fact, their application to this problem might be especially convenient because we have the $x$ dependence of the form $x^{k}$, which lends itself relatively easily to fractional derivative operators.
Griffith's text doesn't discuss whether this is doable or not, and therefore leaves the door open to the reader's imagination (or unease) about uniqueness here. For example, what if we chose say:
$$ b_{-} \ \varpropto \ \ (\hbar D)^{1/2} + (m\omega x)^{3/2}\ \ \ ;\ \ \ b_{+} \ \varpropto\ \   - (\hbar D)^{3/2} + (m\omega x)^{1/2}$$
or some other similar definitions that, when multiplied, could lead us (with the help of Gamma function identities that usually result from fractional derivatives) again to the sought form of:
$$b_{-}b_{+}\ \ \ \varpropto \ \ \  \left[\underbrace{-\hbar D^{2}+(m\omega x)^{2}}_{= 2 m H} + \text{some constant} \right],$$
(assuming we could make wise algebraic choices to produce the constant in this expression), and we could then find
$$ H= \hbar\omega\left( b_{-}b_{+} - \phi \right)\ \ \ ; \ \ \  H= \hbar\omega\left( b_{+}b_{-} + \phi \right),$$
with some new $\phi$ that is less than $1/2$ (that is $\phi<0.5$), and therefore produce a new ladder with "legal" energy steps that are SMALLER than $\hbar\omega$ (namely, energy step size $\boxed{2\phi\hbar\omega}$) ?

Any help in settling this idea of uniqueness would be appreciated.

A: Your argument is right, of course: there's no guarantee there won't be many more states that our ladder operators don't reach. The simplest possibility is another equivalent ladder in parallel, but states in between the ladder states can occur too.
In the case of the quantum harmonic oscillator, there are more specific arguments you can make. Valter Moretti points out here that if you assume the Hilbert space is $L^2(\mathbb{R})$, you know the standard ladder of states is enough because it gives a complete basis. I think that rules out your proposal with fractional derivatives, but you can still get a hidden ladder if the Hilbert space is actually larger, like $L^2(\mathbb{R}) \otimes L^2(\mathbb{R})$. An explicit model here is two parallel ladders both with spacing $\hbar \omega/2$, where the raising operator we've given raises on both simultaneously.
But from a phenomenological view this is beside the point. Of course there are many models you can use; the key is finding what fits experiment. We know that a transition between states with energy difference $\hbar \Delta \omega$ releases a photon of frequency $\Delta \omega$. We also know that a classical particle oscillating with frequency $\omega$ emits radiation of frequency $\omega$ (and harmonics thereof). That tells us that our quantum model needs energy spacings of $\hbar \omega$ to fit with experiment, and no smaller.
Of course you can postulate other states and make some rule that they can never radiate, but Occam's razor means such a model is worse. Experiment pushes us towards the Hilbert space $L^2(\mathbb{R})$ and the Hamiltonian $H = p^2/2m + kx^2/2$, where the ladder is complete.

A: The operator (observable) factorization into a product does not lead necessarily to ladder operators. Suppose the Hamiltonian operator, for example, is written as $H=XY$, then
$$
[H,X]=[XY,X]=X[Y,X].
$$
Unless $[X,Y]$ is a constant, as for the traditional ladder operators for the simple harmonic oscillator, $X$ and $Y$ are not ladder operators. In fact, an operator $M$ is a ladder operator for an operator $H$ when it is an eigenoperator for the adjoint action $\text{ad}(H)$:
$$
\text{ad}(H)M=[H,M]=\lambda M,
$$
where $\lambda$ is a complex number. Suppose $|\psi\rangle$ is an eigenstate for $H$ with eigenvalue $c$, then
$$
HM|\psi\rangle=(\lambda M+MH)|\psi\rangle=(\lambda+c)M|\psi>.
$$
It does not matter if $M$ "divides" $H$. Obviously $\lambda$ must be real if the eigenvalues are to be interpreted as the possible observable measurements. Notice that this definition of ladder operator as an eigenoperator for $\text{ad}(H)$ is limited to spectra with equaly spaced eigenvalues. For general spectra $\lambda_0<\lambda_1<\ldots<\lambda_n<\ldots$ and associated eigenstates $\psi_0,\psi_1,\ldots,\psi_n,\ldots$, a ladder operator $M$ (no relation with the former $M$) is defined by $M_{\pm}|\psi_n\rangle\propto |\psi_{n\pm 1}\rangle$ for all $n$. The two definitions coincide for the simple harmonic oscillator, but not for the Hydrogen atom, where only the last one is applicable.
As you noticed, not only $a_+$  and $a_-$ are eigenoperators for $\text{ad}(H)$ and, simultaneously, for the number operator $\text{ad}(N)$, where $N=a_+a_-$ is the number operator, but any power of them. More generally, defining the grade of a monomial $a_+^na_-^m$ as
$$
\text{grade}(a_+^na_-^m)=n-m,
$$
any monomial is an eigenoperator for $N$ with eigenvalue equal to its grade:
$$
\text{ad}(N)(a_+^na_-^m)=(n-m)a_+^na_-^m.
$$
Any sum of same grade operators is also an eigenoperator. Even more: if inverses can be defined, the ratio between same grade operators are also eigenoperators. As an example, let $M=2a_+^7a_-^5+7a_+^3a_-$. Thus
$$
[N,M]=2M,
$$
and
$$
[N,M^{-1}]=-\frac{1}{2}M^{-1},
$$
where the fact that if $[N,M]=\lambda M$, then $[N,M^{-1}]=-\frac{1}{\lambda}M^{-1}$ was used. The last identity can be obtained from $[N,MM^{-1}]$.
Operators can be expressed as a function of the position and momentum operators or, equivalently, in terms of $a_+$ and $a_-$: the transformation between them is simply a change of coordinates. As any operator can be written as a function of $a_+$ and $a_-$ and any eigenoperator for $\text{ad}(H)$ is a sum or ratio of same grade monomials, your point 2) can be rephrased as: must the grade necessarily be an integer? The answer is no. The operator $\sqrt{a_+}$ (if it does exist), for example, is an eigenoperator for $\text{ad}(H)$:
$$
[H,\sqrt{a_+}]=[a_+a_-,\sqrt{a_+}]=a_+[a_-,\sqrt{a_+}]=\frac{1}{2}\sqrt{a_+}.
$$
It was used the formal rule $[a_-,f(a_-,a_+)]=\frac{\partial f}{\partial a_+}$. If $N|\psi\rangle=c|\psi\rangle$ then
$$
N\sqrt{a_+}|\psi\rangle=(c+\frac{1}{2})|\psi\rangle.
$$
By now should we conclude that new solutions to the quantum simple harmonic oscillator can be obtained by repeated application of an operator such as $a_+^{1/n}$, with $n$ an integer, on the ground state $|0\rangle$? No, we shouldn't because:

*

*Operators such as $\sqrt{a_-}$ could not exist. For example, the matrix  $\left({\begin{smallmatrix}\\0&1\\0&0\end{smallmatrix}}\right)$ has no square root. In fact, it is well established that the simple harmonic oscillator spectrum has a unique spetrum, thus operators with non-integer grade should not exist.

*Even if they can be defined in some way, they could (and given the spectrum uniqueness, should) produce states that are not square-integrable.
I've looked for a definition of $(x-\frac{d}{dx})^{1/2}$, but I couldn't find one. The plan was apply this operator to a Gaussian function and see if the result satisfies Schrödinger equation.
In conclusion, the spectrum uniqueness for the simple harmonic oscillator forbids the existence of non-integer grade operators. Nonetheless, it would be very instructive to have a nonexistence proof that does not resort to the spectrum.

A: Okay, time to gather all this up in an answer.

What does Griffiths show in his book? Boiled down, he shows that there exists an operator $\hat a$ such that:

*

*The SHO Hamiltonian can be written as $\hat H = A\hat a^\dagger\hat a+B$

*$[\hat a,\hat a^\dagger]=1$
The combination of these two properties imply that the Hamiltonian has a set of ladder eigenstates. These eigenstates are defined as follows:

*

*We define $|0\rangle$ to be a state satisfying $\hat{a}|0\rangle=0$.

*We define $|n\rangle\equiv\frac{1}{\sqrt{n!}}(\hat{a}^\dagger)^n|0\rangle$

*Using the two properties of $\hat a$ above, we can prove that each $|n\rangle$ is an eigenstate $\hat H$ with energy $nA+B$.
We know there exists at least ONE such $\hat{a}$, because Griffiths explicitly writes it down in his book and shows it obeys both of the required properties. The question is, can there exist TWO operators with this property?

Let's say $\bar a$ is an operator, and that $\bar{a}$ obeys both properties. I.e., we have:

*

*$\hat{H}=\bar{A}\bar{a}^\dagger\bar{a}+\bar{B}$

*$[\bar{a},\bar{a}^\dagger]=1$
We follow the identical procedure as above to develop a new set of ladder states $|\bar{n}\rangle$ with energies $\bar{A}\bar{n}+\bar{B}$. There are three possible cases here: either $A\neq\bar A$, or $B\neq \bar B$, or $A=\bar A$ and $B=\bar B$ but somehow still $a\neq \bar a$. We need to show each of these possibilities are impossible.
The proofs will be proofs by contradiction. In each case, we'll select a state, and show that by acting on the state with some operator, we can construct another state with lower energy. We'll show that this process doesn't terminate (doesn't result in the zero vector) no matter how many times we do it. Thus, if we continue long enough, we get negative-energy states. Since we know the simple harmonic oscillator does not have negative energy states, we'll reach a contradiction.

Let's start with $A\neq \bar A$. Without loss of generality, assume $A>\bar{A}$. Then for some $\bar{n}$, we'll have that $|\bar{n}\rangle$ has an energy that cannot be written as $An+B$. Then, by acting with $\hat{a}$, we can generate a whole ladder of states with lower energies. The state $|\phi_m\rangle\equiv(\hat a)^m|\bar n\rangle$ has energy $E_m=\bar A\bar n+\bar B-Am$. We know that $|\phi_m\rangle$ will never equal $|0\rangle$, because $|\phi_m\rangle$ never has the same energy as $|0\rangle$. But since $|0\rangle$ is the unique vector that satisfies $\hat a |0\rangle=0$, that means this process can never terminate; every $m$ gives a nonzero vector in Hilbert space. By making $m$ large, we can make $|\phi_m\rangle$ have negative energy. But the SHO is strictly positive, so this is impossible. We conclude that we cannot have $A\neq \bar A$.

Now, let's assume $A=\bar{A}$, but $B\neq \bar{B}$. WLOG, assume $B<\bar{B}$. Then $|0\rangle$ has energy $B$, while $|\bar{0}\rangle$ has energy $\bar{B}$. In particular, since $|\bar{0}\rangle$ is the unique state which satisfies $\bar{a}|\bar 0\rangle=0$, acting on $|0\rangle$ with $\bar{a}$ produces states of arbitrarily negative energy. The state $|\phi_m\rangle\equiv(\bar a)^m|0\rangle$ has energy $B-Am$, which can be arbitrarily negative if we pick large $m$. We thus conclude that we can't have $B\neq \bar B$.

Finally, say $A=\bar{A}$ and $B=\bar{B}$. We want to show that $a$ and $\bar{a}$ are essentially the same.
We know the matrix elements of $\hat{a}$ are given by
$$
\langle m|\hat{a}|n\rangle = \sqrt{n}\delta_{n-1,m}
$$
Because $\bar{a}$ generates the same ladder of energies, and the spectrum of $H$ is non-degenerate, $\bar{a}$ connects the same states as $a$, up to phases:
$$
\langle m|\bar{a}|n\rangle = e^{i\theta_n}\sqrt{n}\delta_{n-1,m}
$$
where $\theta_n$ possibly depends on the state $n$.
That's as good as you can do: you ARE allowed to pick some random ladder operator that adds phases to your states as you go up and down the ladder. But that's the only freedom you have. Phases aren't really important to the story, so you should consider the ladder operators essentially unique. In particular, you CAN'T have a ladder operator with a different lowest rung (different $B$), and you CAN'T have a ladder operator with a different spacing (different $A$).


text:
Q: extjs - 'Store is undefined' I'm pretty sure this a trivial problem and i'm just being a bit stupid. Your help would be hugely appreciated.
In controls/dashboard.js I have:
    Ext.ill.WCSS.controls.dashboard = {
        xtype:'portal',
        region:'center',
        margins:'35 5 5 0',
        items:[{
            columnWidth: 1,
            style:'padding:10px',
            items:[{
                title: 'My Cluster Jobs',
                layout:'fit',
                html: "test"
            }]
        },{
            columnWidth: 1,
            style:'padding:10px',
            items:[{
                title: 'All Cluster Jobs',
                iconCls: 'icon-queue',
                html: "test",
                items: new Ext.grid.GridPanel({
                        title: 'Cluster Job Queue',
                        store: Ext.ill.WCSS.stores.dashboardClusterJobs,
                        width: 791,
                        height: 333,
                        frame: true,
                        loadMask: true,
                        stateful: false,
                        autoHeight: true,
                        stripeRows: true,
                        floating: false,
                        footer: false,
                        collapsible: false,
                        animCollapse: false,
                        titleCollapse: false,
                        columns:[
                                {
                                    xtype: 'gridcolumn',
                                    header: 'Job ID',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'JB_job_number',
                                    fixed: false
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'Priority',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'JAT_prio',
                                    fixed: false
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'User',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'JB_owner'
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'State',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'state'
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'Date Submitted',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'JAT_start_time'
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'Queue',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'queue_name'
                                },
                                {
                                    xtype: 'gridcolumn',
                                    header: 'CPUs',
                                    sortable: true,
                                    resizable: true,
                                    width: 100,
                                    dataIndex: 'slots'
                                }
                            ],
                            bbar: {
                                xtype: 'paging',
                                store: 'storeClusterQueue',
                                displayInfo: true,
                                refreshText: 'Retrieving queue status...',
                                emptyMsg: 'No jobs to retrieve',
                                id: 'clusterQueuePaging'
                            }
                    })
            }]
}]
};

Simple enough, note the reference to 'Ext.ill.WCSS.stores.dashboardClusterJobs'
So in stores/dashboard.js I just have this:
Ext.ill.WCSS.stores.dashboardClusterJobs = new Ext.data.XmlStore({
    storeId: 'storeClusterJobs',
    record: 'job_list',
    autoLoad: true,
    url: 'joblist.xml',
    idPath: 'job_info',
    remoteSort: false,
    fields: [
        {
            name: 'JB_job_number'
        },
        {
            name: 'JAT_prio'
        },
        {
            name: 'JB_name'
        },
        {
            name: 'JB_owner'
        },
        {
            name: 'state'
        },
        {
            name: 'JAT_start_time'
        },
        {
            name: 'slots'
        },
        {
            name: 'queue_name'
        }
    ]
});

I run the code and I get 'store is undefined' :S It's confusing me a lot. All of the javascripts have been included in the correct order.
i.e.
<script type="text/javascript" src="/js/portal.js"></script>
<script type="text/javascript" src="/js/stores/dashboard.js"></script>
<script type="text/javascript" src="/js/controls/dashboard.js"></script>

Thanks guys!

A: It might be a namespace issue.  What do your Ext.ns declarations look like?

A: I think we need more info.  You're using an xtype of portal (code missing) and it's not obvious how this object is instantiated (code missing).

A: I figured it out. It was to do with my ordering of javascript files. (ooops!) thanks so much for your help though and apologies for the late response.

redpajama_set_name: RedPajamaStackExchange


text:
Q: moment js two datetimepicker time comperison I have 2 daettimepickers start_date_time and end_date_time
want
on $(end,start).change, I want to compare if more than 6 hours difference show alert and clear input
$('.dateTo,.dateFrom').blur(function () {
            if ($('.dateFrom').val() !== '' && $('.dateTo').val() !== '') {

                var fromTime = moment($('.dateFrom').val(),"YYYY-MM-DD HH:mm:ss");
                var toTime = moment($('.dateTo').val(), "YYYY-MM-DD HH:mm:ss");
                console.log(fromTime + ' - ' + toTime);
                //above returns 1135054800000 - 1166562000000
                //while i expect formated as above
                var duration = moment.duration(toTime.diff(fromTime));
                var hours = duration.asHours();
                console.log(hours);
                //return 8752 in meridiam is changed (from 04/12/2019 9:am to 05/12/2019 1pm)
                if (fromTime >= toTime) {
                    $(this).val('');
                    alert('ToTime should be greater than fromTime.');
                }
                var diffMs = (toTime - fromTime)
                var diffMins = Math.floor(diffMs / 60000);

                if (diffMins > (6 * 60) && $(".PermissionType").val()=="Personal") {
                    $(this).val('');
                    alert('Duration should not increase 6 hours.');
                }
            }
        });

var duration = moment.duration(toTime.diff(fromTime));
 var hours = duration.asHours();
above lines return wrong difference of hours when AM/PM is different in start and end datetime
I need difference of hours in 05/12/2019 11:00 PM and 06/12/2019 12:00 AM it is returning me 8761
while  05/12/2019 11:00 PM and 05/12/2019 11:59 PM returns 0.9833333333333333

A: I've tested this and I can't reproduce your issue. Using datetime-local inputs lets you select the time and it's getting the proper am/pm formatting.
<input type="datetime-local" id="start">
<input type="datetime-local" id="end">

here's a fiddle demonstrating https://jsfiddle.net/fLzu854x/
Looking at the console in my fiddle, I am not getting that error.


text:
Q: MVVM Cross ShowViewModel doesn't work on UWP with custom I refer from this StackOverflow question, regarding to MVVM Light:

I am trying to have a hamburger menu style navigation (see this
  sample). app by Microsoft on an example of how to do this) to:
1- have a convenient solution shared across all my pages. The sample
  mentioned above uses an AppShell Page as the root of the app instead
  of a Frame, that encapsulates the navigation menu and some behavior of
  the back button. That would be ideal.
2- Use the MVVM-Light navigation service to handle all the navigation
  from my view model conveniently.

Here is how the App.xml.Cs initializes the shell page onLaunched:
 protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        var shell = Window.Current.Content as AppShell;

        // Do not repeat app initialization when the Window already has content,
        // just ensure that the window is active
        if (shell == null)
        {
            // Create a AppShell to act as the navigation context and navigate to the first page
            shell = new AppShell();

            // Set the default language
            shell.Language = ApplicationLanguages.Languages[0];

            shell.AppFrame.NavigationFailed += OnNavigationFailed;
        }

        // Place our app shell in the current Window
        Window.Current.Content = shell;

        if (shell.AppFrame.Content == null)
        {
            // When the navigation stack isn't restored, navigate to the first page
            // suppressing the initial entrance animation.
            var setup = new Setup(shell.AppFrame);
            setup.Initialize();

            var start = Mvx.Resolve<IMvxAppStart>();
            start.Start();
        }

        // Ensure the current window is active
        Window.Current.Activate();
    }

The thing is, as long as i navigate over the menu proviced by the AppShell everything works. But the ShowViewModel from MVVM Cross doesn't have any effect.
I thought there shouldn't be any difference if pass the shell as Frame or the frame set on the AppShell.
Does anyone have an idea what I can do about this or if there is an example with a working hamburger menu with  MVVM cross?
The repository is open source on GitHub if you need an better overview or so.
https://github.com/Apply-Solutions/MoneyManager
I use MVVM Cross v4.0.0.0-beta1. Beta2 has currently another issue who prevents building in a UWP.
Thanks
NPadrutt

A: Not entirely sure what you are trying to do, but what you will probably need to navigate pages with a hamburger menu in a UWP app using MvvmCross as a framework, is a custom presenter, which handles the ShowViewModel method, and displays the associated view for the requested ViewModel in your hamburger container view.

A: Okey this embarrassing. The issue was that the View for the ViewModel couldn't be resolved. And the reason for that was that I didn't replace the inheritance from page to views:MvxWindowsPage.
With this, everything works with the default page presenter.
EDIT: in order to work with the navigation in the app shell, these pages need to be Pages. So you may either have to rewrite the navigation in the Appshell or may not adjust all Pages to MvxPage.


text:
Q: Multiple plus and minus buttons I am using - and + buttons to change the number of the text box, I am having troubles dealing with different text fields, here is my code:

var unit = 0;
var total;
// if user changes value in field
$('.field').change(function() {
  unit = this.value;
});
$('.add').click(function() {
  unit++;
  var $input = $(this).prevUntil('.sub');
  $input.val(unit);
  unit = unit;
});
$('.sub').click(function() {
  if (unit > 0) {
    unit--;
    var $input = $(this).nextUntil('.add');
    $input.val(unit);
  }
});
button {
  margin: 4px;
  cursor: pointer;
}
input {
  text-align: center;
  width: 40px;
  margin: 4px;
  color: salmon;
}

  field 1
  <button type="button" id="sub" class=sub>-</button>
  <input type="text" id="1" value=0 class=field>
  <button type="button" id="add" class=add>+</button>

  field 2
  <button type="button" id="sub2" class=sub>-</button>
  <input type="text" id="2" value=0 class=field>
  <button type="button" id="add2" class=add>+</button>

And here's the DEMO
You can see in the demo that the values change correctly only if you click buttons on the same field, but if you alternate between fields the values don't change properly.

A: This should be all you need:
$('.add').click(function () {
    $(this).prev().val(+$(this).prev().val() + 1);
});
$('.sub').click(function () {
    if ($(this).next().val() > 0) $(this).next().val(+$(this).next().val() - 1);
});

By using the unit variable you were tying both inputs together. And the plus in +$(this) is a shorthand way to take the string value from the input and convert it to a number.
jsFiddle example

A: An alternative approach is to use data attributes and have each element store its own value.  Edit: it already stores its own value.  Just access it.

var total;
// if user changes value in field
$('.field').change(function() {
  // maybe update the total here?
}).trigger('change');

$('.add').click(function() {
  var target = $('.field', this.parentNode)[0];
  target.value = +target.value + 1;
});

$('.sub').click(function() {
  var target = $('.field', this.parentNode)[0];
  if (target.value > 0) {
    target.value = +target.value - 1;
  }
});
button {
  margin: 4px;
  cursor: pointer;
}
input {
  text-align: center;
  width: 40px;
  margin: 4px;
  color: salmon;
}

  field 1
  <button type="button" id="sub" class=sub>-</button>
  <input type="text" id="1" value=0 class=field>
  <button type="button" id="add" class=add>+</button>

  field 2
  <button type="button" id="sub2" class=sub>-</button>
  <input type="text" id="2" value=0 class=field>
  <button type="button" id="add2" class=add>+</button>

A: You're using the same variable to hold the values of your two inputs. One simple option would be to use two variables instead of one:
var unit_1 = 0;
$('#add1').click(function() {
   unit_1++;
   var $input = $(this).prev();
   $input.val(unit_1);
});
/* Same idea for sub1 */

var unit_2 = 0;
$('#add2').click(function() {
   unit_2++;
   var $input = $(this).prev();
   $input.val(unit_2);
});
/* Same idea for sub2 */

and unit = unit just assigns the value of unit to itself, so that's no very useful and you can certainly leave it out.


text:
Q: Ubuntu 16.04 wireless connection I am trying to set up wireless with my newly installed Ubuntu 16.04 on my laptop.
 ifconfig -a
ens5      Link encap:Ethernet  HWaddr 00:25:b3:42:05:5c
          inet addr:10.2.102.195  Bcast:10.2.102.255  Mask:255.255.255.0
          inet6 addr: 2001:12f0:784:df66:35a5:5e8b:1dc4:3539/64 Scope:Global
          inet6 addr: fe80::9056:fc9a:b94:6345/64 Scope:Link
          inet6 addr: 2001:12f0:784:df66:755f:d4c1:3e0:cb66/64 Scope:Global
          inet6 addr: 2001:12f0:784:df66::d8f/128 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:402616 errors:0 dropped:76 overruns:0 frame:0
          TX packets:209969 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:335161688 (335.1 MB)  TX bytes:34790938 (34.7 MB)
          Interrupt:17

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:80137 errors:0 dropped:0 overruns:0 frame:0
          TX packets:80137 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1
          RX bytes:7796613 (7.7 MB)  TX bytes:7796613 (7.7 MB)

wlp3s0    Link encap:Ethernet  HWaddr 00:21:00:b2:16:48
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:17

But
nmcli d wifi list
*  SSID  MODE  CHAN  RATE  SIGNAL  BARS  SECURITY

My interface
ls /sys/class/net
ens5  lo  wlp3s0

cat /etc/network/interfaces
# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback

iwconfig
wlp3s0    IEEE 802.11abg  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated
          Retry short limit:7   RTS thr:off   Fragment thr:off
          Power Management:off

lo        no wireless extensions.

ens5      no wireless extensions.
rfkill list all
0: hci0: Bluetooth
    Soft blocked: no
    Hard blocked: no
1: phy0: Wireless LAN
    Soft blocked: no
    Hard blocked: no
2: brcmwl-0: Wireless LAN
    Soft blocked: no
    Hard blocked: yes

All friends in lab use wireless connection without any problem.What should I try?


text:
Q: Parse CSV file in C Is there a library I can use to parse CSV files in C. I am on a Linux system. I know about this but it is in C++ and I need something in C. Don't want to go through the pain of debugging and testing if someone has already done it.

A: There's a simple CSV parser library that's described in the excellent book The Practice of Programming by
Kernighan and Pike, and the source is available from the site linked to.

A: Take a look at libcsv, which is a CSV library written in ANSI C89.

A: Parsing a CSV is no too much complicated, depend of the CSV structure, take a look at the  strtok function.


text:
Q: PMD Apex ExcessiveClassLength & ExcessivePublicCount Rule error Getting the following error message when I Ran the PMD scripts for Apex Class.
ExcessiveClassLength -- Avoid really long classes.
ExcessivePublicCount -- This class has a bunch of public methods and attributes
Both PMD Errors Occurs in Wrapper Class.
ExcessiveClassLength  Code Below:
    public Class StudentProgramTypeWrapper{
        @AuraEnabled
        public Id programRecordTypeId {get;set;}
        @AuraEnabled
        public string programTypeName {get;set;}
        @AuraEnabled
        public string programTypekey {get;set;}
    }

ExcessivePublicCount Code Below:
    public Class ParentProgramWrapper{
        @AuraEnabled
        public Id parentProgramId {get;set;}
        @AuraEnabled
        public String parentProgramName {get;set;}
        @AuraEnabled
        public String parentProgramDesc {get;set;}
        @AuraEnabled
        public string qualifiedName {get;set;}
        @AuraEnabled
        public boolean showdatatable {get;set;}
        @AuraEnabled
        public boolean isstudntProgramAssigned {get;set;}
        @AuraEnabled
        public string minNumberOfProgramDesc {get;set;}
        @AuraEnabled
        public string maxNumberOfProgramDesc {get;set;}
        @AuraEnabled
        public decimal minNumberOfProgram {get;set;}
        @AuraEnabled
        public decimal maxNumberOfProgram {get;set;}
        @AuraEnabled
        public decimal numberOfProgramSeleted {get;set;}
    }

Can anyone please guide me to solve this error.


text:
Q: Why is the number of partitions after groupBy 200? Why is this 200 not some other number? It's Spark 2.2.0-SNAPSHOT.
Why is the number of partitions after groupBy transformation 200 in the following example?
scala> spark.range(5).groupByKey(_ % 5).count.rdd.getNumPartitions
res0: Int = 200

What's so special about 200? Why not some other number like 1024?
I've been told about Why does groupByKey operation have always 200 tasks? that asks specifically about groupByKey, but the question is about the "mystery" behind picking 200 as the default not why there are 200 partitions by default.

A: This is set by spark.sql.shuffle.partitions
In general whenever you do a spark sql aggregation or join which shuffles data this is the number of resulting partitions.
It is constant for your entire action (i.e. it is not possible to change it for one transformation and then again for another).
See http://spark.apache.org/docs/latest/sql-programming-guide.html#other-configuration-options for more information


text:
Q: Pulling result from XComArgs I'm new to Airflow and experimenting to understanding the mechanics :)
I see how easy it is to chain python functions with Airflow 2.0 Task Flow API - using @task decorator. What confuses me, is how to pass data from @task decorated functions to custom operators - this is happening automatically when @task decorated functions are chained.
def tutorial_taskflow_blob():

   data_path = download_azure_blob_file(blob_file_name, download_dir)
   model_path = xgboost_learner(data_path, model_dir)
   UploadAzureBlobOperator(task_id = "Upload_To_Azure", path_to_file = model_path)

lets say that download_azure_blob_file and xgboost_learner are @task decorated functions and UploadAzureBlobOperator is my custom operator. xgboost_learner takes data_path as argument and works well. but UploadAzureBlobOperator doesnt take model_path. I'm getting error that instead of string that xgboost_learner should be returning, the type of model_path is XComArgs.
How can I extract data most optimally from model_path ? Even if I want to take large dataframe?


text:
Q: Changing src on img tag, can't make it work I have been trying to change a image in a webpage using jquery and httprequest, without any luck... after research a lot I decide to ask for help.
The code is pasted bellow and I first try to ask for the json (what works fine) and then update the scr on the image... didn't work.
For a final test I use a mouseover and mouse out function and didn't work as well, funny thing is that other property like, show and hide works fine, the only problem is with the attr('scr','').
Thanks
<!DOCTYPE html>

A: Looks like a typo, scr should be src when assigning the attribute for a1

A: There are several problems I found and wrestled with, but finally got some working code:
<!DOCTYPE html>

You can see it work here:
http://www.sanbarcomputing.com/flat/forumPosts/imgSrcType/imgSrcTypeNoComments.html
This code uses a service called "JSONTest" to get properly formatted JSON code.  This returns an object (data) of key/value {ip: "xxx.xxx.xxx.xxx"} which shows your ip address.  Here is the services website that I use to get the JSON response:
http://teamaqua.github.com/JSONTest/
To see the console log output, just open a console in your browser (hit the F12 key, for instance, or open the FireBug plugin for FireFox.  Drill down into the object to see the key/value pair properly formatted in the console.
I fixed your code with the scr->src typo fix and some other things needing fixing:
<!DOCTYPE html>

You can see it (possibly) fail here:
http://www.sanbarcomputing.com/flat/forumPosts/imgSrcType/imgSrcType.html
I get a cross-domain error in Chrome, and it seems to fail silently in IE and FireFox:

XMLHttpRequest cannot load
  http://www.containernurseries.co.nz/json/jsonPlantDetails.php?plantSelected=ARGYRANTHEMUM-POLLY.
  Origin http://www.sanbarcomputing.com is not allowed by
  Access-Control-Allow-Origin.

Here is a good post that talks about one way to fix this (changing it to JSONP), but since your server returns JSON, not JSONP, it does not work either (I tried):
stackoverflow: access-control-allow-origin-not-allowed-by
You would need to return the result in the form of a JSONP JavaScript executable function from the server, I believe.  To get a JSONP request sent, you would change this line:
$.getJSON("http://www.containernurseries.co.nz/json/jsonPlantDetails.php",

To this:
$.getJSON("http://www.containernurseries.co.nz/json/jsonPlantDetails.php?callback=?",

jQuery then would automatically produce a JSONP request for you.  It works, but since the result is not executable JavaScript, you get the following error in Chrome:

Uncaught SyntaxError: Unexpected token :

Since I think Chrome is trying to execute the JSON as a function, which it is not.
Changes need to be made to the server, I believe, to get this working cross-domain, if you need that.
Here is a good article on cross-domain issues:
https://developer.mozilla.org/en-US/docs/HTTP_access_control


text:
Q: Is there any command line tool that can be used to edit environment variables in Windows? Is there any command line tool that can be used to edit environment variables in Windows?
It would be nice if this was smart tool, for example:

*

*When adding some path to let's say the PATH variable and this path is already there it shouldn't double this entry.

*Inserting a new path to the PATH variable should be possible before/after some other path or in specific order (the first, the 7th, the last etc.).

*It should be possible to change only part of variable's value (in case of the PATH a given path from a list of all paths).

And the last but not the least - I want my changes to persist between sessions so simple SET is out of question...
There's very nice GUI tool for this called Path Editor and I need something like this but for command line.

A: If you need a generic way to set any environment variable and have the changes persist, then setx.exe would be the tool to use.  It cannot do the "smart" things you are asking for, though...
setx.exe is included with Windows Vista or later; if you use an earlier version of Windows, you can use the above download link to get it.

A: For the current program, there is path:

Displays or sets a search path for executable files.
PATH [[drive:]path[;...][;%PATH%]
PATH ;

Type PATH ; to clear all search-path settings and direct cmd.exe to search only in the current directory.
Type PATH without parameters to display the current path.
  Including %PATH% in the new path setting causes the old path to be
  appended to the new setting.

However, this is pretty much the same as set PATH.
For environment variables to persist you have to edit the registry or use setx.

A: I just discovered the ability to allow the users to run the Environment Variables edit dialog without elevated privileges.
From the Start menu, run the following:
rundll32 sysdm.cpl,EditEnvironmentVariables

A: You might wanna check out pathed of the gtools collection:
http://www.p-nand-q.com/gtools.html
It provides a set of commands for the command promt like
pathed /APPEND %CD% /USER

to append the current path for example. I haven't really checked it out to be honest, as I'm totally fine with using a GUI.
Other options are:
  /MACHINE: print machine PATH
     /USER: print user PATH
      /ADD: add variable at the head
   /APPEND: add variable at the tail
   /REMOVE: remove path / index
     /SLIM: strip duplicate vars
      /ENV: environment variable, defaults to PATH

Together with which of the same collection, you got yourself some good tools, I suppose. Which  "locates executable files on the PATH".
 /EXTENSION: search for extension , can be a ; separated list
       /DIR: add directory , can be a ; separated list
 /RECURSIVE: search directories recursively
    /SINGLE: stop after the first find result
       /ENV: environment variable, defaults to PATH
FILE {FILE}: one or more files to find

Source: http://op111.net/82/

A: set PATH
(help set)

A: I don't know any tool that does this, but maybe you can use the regcommand:
reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path

to read the current path, and
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /d "newPath" /f

to write your new value.
You need admin rights for hsving right acccess in HKLM. If that is a problem, consider modifying the user specific path setting in  HKCU\Environment instead.

A: I wrote a set of batch scripts for this.  addpath.bat adds elements to the path, rmpath.bat  removes elements from the path, and lpath.bat just lists the path. But then I needed some support scripts, so there is also chkpath.bat .
It ended up being not trivial and required tr.exe and cat.exe, a couple of unix-style utilities.  The reason its not trivial:  no backticks in cmd.exe (though you can use for loops for this), and short names versus long names.
addpath.bat:
@echo off
setlocal
set cwd=%~dps0

goto testit

:loopy

call %cwd%chkpath "%~1"
if %errorlevel%==2 (
  set path=%path%;%~1
)

shift

:testit
if not _%1==_ goto loopy

call %cwd%lpath.bat

endlocal & set path=%path%

ChkPath.bat:
@echo off
goto START

-------------------------------------------------------
chkpath.bat

checks path for existence of the given segment.
Returns 1 if present, 2 if not present, 0 if not checked.

The matching and checking complicated by case sensitivity and "short pathnames".

created sometime in 2003 and lovingly maintained since then.

-------------------------------------------------------

:START
setlocal enabledelayedExpansion
set rc=0
set cwd=%~dps0
set curdrive=%~d0
set tr=%curdrive%\bin\tr.exe
set regexe=%windir%\system32\reg.exe

if _%1==_ goto Usage

@REM convert arg 1 to a fully-qualified, short path name,
@REM and then convert to uppercase.
set toupper=%~fs1
call :ToUpper
set tocheck=%toupper%

if not _%TEMP%==_ goto GotTemp
call :gettemp

:GotTemp
set d=%DATE:~4%
set stamp=%d:~6%%d:~3,2%%d:~0,2%%TIME::=%
set d=
set tempfile1=%TEMP%\chkpath1-%stamp%.tmp

echo %path% | %tr% ; \n  >  %tempfile1%

@REM check each element in the path for the match:
for /f  "delims=^" %%I in (%tempfile1%) do (
  if !rc!==0 (
call :CheckElt "%%I"
  )
)

if %rc%==0 set rc=2
goto END

--------------------------------------------
* checkelt
*
* check one element in the path to see if it is the same
* as the TOCHECK string. The element is first canonicalized.
*

:CheckElt
@REM remove surrounding quotes
set ERF=%1
if [x%ERF%]==[x] goto CheckEltDone
@REM convert to fully-qualified, short paths, uppercase
set TOUPPER=%~fs1%
call :ToUpper
if _%TOCHECK% == _%TOUPPER% set rc=1
:CheckEltDone
goto:EOF
--------------------------------------------

--------------------------------------------
* backtick
*
* invoke a command and return the result as a string.
* This is like backtick in csh or bash.
* To call, set variable BACKTICK to the command to be run.
* The result will be stored in the env variable of the same name.
*

:backtick
FOR /F "usebackq delims=" %%i IN (`%backtick%`) DO (
  SET backtick=%%i
)
goto backtick_done
:backtick_none
  SET backtick=nothing to exec
:backtick_done
goto:EOF
--------------------------------------------

--------------------------------------------
* gettemp
*
* get the temporary directory, as stored in the registry.
* Relies on backtick.
*
* The result set TEMP.
*

:gettemp
set regkey=HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders
set regvalname=Local AppData
set backtick=%regexe% query "%regkey%" /v "%regvalname%"
call :backtick
for /f "tokens=4" %%a in ("%backtick%") do (
  set temp=%%a
)
goto:EOF
--------------------------------------------

--------------------------------------------
* ToUpper
*
* Convert a string to all uppercase.
* To call, set variable TOUPPER to the thing to be converted.
* The result will be stored in the env variable of the same name.
*

:ToUpper
  FOR /F "usebackq delims=" %%I IN (`echo %toupper% ^| %tr% a-z A-Z`) DO (
SET toupper=%%I
  )
goto:EOF
--------------------------------------------

--------------------------------------------
:CleanUp
  if _%tempfile1%==_ goto CleanUpDone
  if exist %tempfile1% del %tempfile1%
  :CleanUpDone
goto:EOF
--------------------------------------------

--------------------------------------------
:Usage
echo.
echo Usage: chkpath ^<path^>
echo checks if path element is included in path variable.
echo returns 1 if yes, 2 if no, 0 if not checked.
echo.
goto END
--------------------------------------------

:END
call :CleanUp

:ReallyEnd

endlocal & set errorlevel=%rc%
@REM set errorlevel=%rc%
@REM echo %errorlevel%

lpath.bat:
@echo.
@set curdrive=%~d0

@REM This form post-fixes a | at the end of each path element. Useful for debugging trailing spaces.
@REM @path | %curdrive%\cygwin\bin\sed.exe -e s/PATH=// -e 's/;/^|\n/g' -e 's/$/^|/g'

@REM This form shows bare path elements.
@REM @path | %curdrive%\cygwin\bin\sed.exe -e 's/PATH=//' -e 's/;/^\n/g'
@path | %curdrive%\utils\sed -e "s/PATH=//" | %curdrive%\utils\tr ; \n
@echo.

A: This is really easy, environment variables are stored in registry, specifically user environment variables are stored in HKEY_CURRENT_USER\Environment, system environment variables are stored in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
You don't need any third party software, you can achieve this I recommend you to use PowerShell, you can use Get-ItemProperty to query registry values and use Set-ItemProperty to modify registry values, New-Item to add registry keys, Remove-Item to delete registry keys and Remove-ItemProperty to delete registry values.
Now for example, to edit the PATH environment variable, you can use these:
If you want to edit the user PATH, you can use $Env:PATH to get its value;
Otherwise use (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" -Name PATH).PATH to get value of system PATH.
Now this is a script example that modifies system PATH:
$directory=Read-Host "Please input directory that needs to be added to PATH"
$path=(Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).PATH.Split(';')
if ($directory -notin $path) {$path+=$directory}
$path=$path -join ";"
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Type String -Value $path

Save as a *.ps1 file and run it with PowerShell, it will add the directory you typed to PATH if it isn't already in PATH.

A: Path Manager (pathman.exe) from Windows Server 2003 Resource Kit Tools is the closest match I could find. It was already available in NT Resource Kit.

A: How to check if directory exists in %PATH%? on Stack Overflow has an outstanding description of what makes Windows PATH editing difficult along with a batch file to overcome them. Figuring out how to properly use addpath.bat took a bit of practice as it's calling structure was new to me, but this works:
set _path=C:\new\directory\to\add\to\path
call addpath.bat _path
set _path=

and repeated firings won't add the new directory if it's already present. This doesn't address making the edits persistent across sessions.

A: I realize this is a late answer, but there is also EditPath.exe available in the release package for PathMgr.dll.
EditPath.exe is a command-line tool you can use to update the system and user Path values in the registry. It can also test whether a directory exists in the system and user Path (determined by an exit code -- see the documentation).
Alternatively, you can use editenv if you want to interactively edit the value of an environment variable (such as Path) for the current process.


text:
Q: How to give sketch effect on image in iphone? I am implementing an iPhone application, in which I have implemented the following functionalities:

*

*Select photo

*Capture photo

*Now I want to give a sketch effect to that photo like this one.
How could I do this?

A: If I may once again recommend it, my open source GPUImage framework has a built in filter that does just this. The GPUImageSketchFilter uses Sobel edge detection to highlight edges in black on images or video, leading to the exact same effect as seen in that application:

The above image was drawn from this answer, where I describe how that filter works, as well as show a couple other filter examples.
In fact, the SimplePhotoFilter example application that comes with the framework does exactly what you describe (capture a photo, apply a sketch filter to it, and save it to the photo library), so I'd start there if you want to get this up and running quickly.

A: OpenCV can be used  to give sketch effect on image in iphone.
Refer iphone-how-to-convert-a-photo-into-a-pencil-drawing link and get helped.

A: Core Image filters are probably the best way to go.
http://developer.apple.com/library/ios/#documentation/GraphicsImaging/Reference/CoreImageFilterReference/.


text:
Q: Passing a pointer to template class as a parameter I am having trouble passing a template class as a parameter to a another function.
I am using VS2012 c++/cli on a Windows 8.1 machine compiling for x64.
The compiler keeps telling me:
 void Channel::TestFunc(SynchQueue<T> *)' : overloaded member function not found in 'Channel'

SynchQueue is a template class for a multi-threaded queue.  I created it with another class I will call Images.
In my main.cpp, I have:
 QPtr = new SynchQueue<Images>;

Also in main.cpp, I created a class called WorkerThread to which I passed QPtr.
No problems with that.
Now I want WorkerThread to pass QPtr to another class that is instantiated in WorkerThread.
So I defined the function as:
Channel.h
public ref class Channel
{
public:
    // other definition stuff
    void TestFunc(SynchQueue<Images> *tQPtr);
}

Channel.cpp
void Channel::TestFunc(SynchQueue<Images> *tQPtr)
{
    int x;
    x++;
}

I keep getting the error above.  What am I doing wrong?
Any help appreciated.

A: You need:
template<typename T>
void TestFunc(SynchQueue<T> *tQPtr);


text:
Q: The type 'xxxx' already contains a definion for 'xxx' I am working in Asp.net 2010 C#
Inside my web page,
public partial class NewStore : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    public class Item()
    {
       public int ItemID;
       public string ItemName;
    }
}

The Problem is that When I rebuild the Project then an error occurs 'The type 'NewStore' already contains a definion for 'Item'.
I didnt find any other class Item inside the Page... Will u please help me..

A: Remove parenthesis after class name Item.
public class Item
{
   public int ItemID;
   public string ItemName;
}


text:
Q: how to set php variable to html input tag in php I need how to set variable value to html input tag,i have a variable value i need to pass html tag please help.
my mysql code:
<?php
//error_reporting(0);
include('db_connection.php');
 if (isset($_POST['submit1'])) {
        $skills = $_POST["skills"];
        //print_r($skills);die;
    }
$sql ="SELECT * FROM `tbl_master_property` WHERE `name` ='$skills'";
  $result=$conn->query($sql);
   while( $row = $result->fetch_assoc() ) {
    $project[] = $row;
}
foreach ($project as $value) {
  $pg_address = $value['pg_address'];
  $pg_owner = $value['pg_incharge_name'];
}
?>

Html code:

            Address
            <input class="border col-lg-12" type="text" name= "address" value ="<?php echo $value['pg_address']; ?>" required/>

            PG Owner Name
            <input class="border" type="text" name= "pg_owner_name" value ="<?php echo $value['pg_owner']; ?>"  required />

A: Try this,
It will echo out Address and Project owner name in inputboxes, for each row in your table,
 <?php
//error_reporting(0);
include('db_connection.php');
 if (isset($_POST['submit1'])) {
        $skills = $_POST["skills"];
        //print_r($skills);die;
    }
$sql ="SELECT * FROM `tbl_master_property` WHERE `name` ='$skills'";
  $result=$conn->query($sql);
   while( $row = $result->fetch_assoc() ) {
    $project[] = $row;
}
foreach ($project as $value) {
  $pg_address = $value['pg_address'];
  $pg_owner = $value['pg_incharge_name'];
  echo '

            Address
            <input class="border col-lg-12" type="text" name= "address" value ="'.$pg_address.'" required/>

            PG Owner Name
            <input class="border" type="text" name= "pg_owner_name" value ="'.$pg_owner.'"  required />

';
}
?>

A: <?php
if (isset($_POST['submit1'])) {
    $skills = $_POST["skills"];
    $sql ="SELECT * FROM `tbl_master_property` WHERE `name` ='$skills'";
    $result=$conn->query($sql);
    $row = $result->fetch_assoc();
    $value= $row[0];
}
?>

<input type="text" name="address" value="<?php echo $value['pg_address'];?>">
<input type="text" name="pg_owner_name" value="<?php echo $value['pg_owner'];?>">


text:
Q: Migrating from .travis CI to GITHUB action migrating to the GitHub action from Travis CI,
there is a line
'git diff --name-only "$TRAVIS_COMMIT_RANGE"'
but it is for Travis and while running on GitHub action not getting the value of this variable "$TRAVIS_COMMIT_RANGE"
what should we use instead of this variable to get the value

A: COMMIT_RANGE: ${{ github.event.before}}...${{ github.event.after}}

In github.event we have all the details so, we can use before and after to get the "$COMMIT_RANGE" same as in travis "$TRAVIS_COMMIT_RANGE" variable


text:
Q: text extraction with sublime text Lets say i have a form with the following fragment:

  First Name

    <input id="FirstName" name="FirstName" type="text" class="input-xlarge" required="">

  Last Name

    <input id="LastName" name="LastName" type="text" class="input-xlarge" required="">

I would like to extract the field names to a file so that my file looks like
FirstName
LastName

Is there a way to do this with ST3 ?

A: Trying to use regex with html can be a real pain — many people cringe at the thought of it; some people may even laugh at you for trying it, then direct you to the infamous question. However, that is not to say it can't be done, because it certainly can be. What it really requires more than anything is an effort to understand why html is unpredictable and how you can possibly tame it. From the looks of things you haven't even scratched the surface on that front, or even breathed on it perhaps. Fortunately as the cosmos aligned today I happened to be extracting field names from html while stumbling upon your sorrow.
Pattern:
<.*>|\n.*\s.*\sid="(\w*)".*\n+|.*>\n|\n.+

Replace:
$1

Result:
FirstName
LastName

Unless you take the time to understand the full complexity behind this somewhat simple pattern you'll likely never appreciate why you should learn what it's doing. In short the pattern finds the name of the input and puts it in a group ($1). The rest of it deals with all the unpredictability that goes with trying to use regex on html (finding <, >, carriage returns \n, spaces \s and all the other crap you don't want.


text:
Q: EF Core with xunit, Function behaviour different than in controller I have set up a little test with xunit to test if a certain row in my test database is not there when I query for it. Here is the test:
        [Fact]
        public async Task GetApplication_ResultEmpty()
        {

            Application application = await _applicationFunctions.GetApplicationByIdAsync(1010);
            Console.WriteLine("Application:" + application);
            Console.WriteLine("ApplicationID: " + application.Id);

            Assert.Null(application);
        }

The GetApplicationById function returns null if it doesnt find anything in the database. Here is a short version of it:
        public async Task<Application> GetApplicationByIdAsync(int id)
        {
            using(var dbContext = _dbContextFactory.CreateDbContext())
            {
                List<Application> ApplicationList = await dbContext.Applications.FromSqlRaw("Exec dbo.GetApplication {0}", id).ToListAsync();
                if (ApplicationList.Any())
                {

                    //call some stored procedures...
                    return Application;
                }
            }
            return null;
        }

I return null if the result is empty. When I debug the Object of type Application inside my controller is set to null correctly. In my test the Assert.Null fails and says that the actual value is this:
Actual:
Application
{
Applicants = null,
ApplicationComments = null,
ApplicationNumber = null,
ApplicationRelStates = null,
ApplicationUuid = null, ...
}

What am I doing wrong here? Sepcifically I want to test if the Object itself is null.


text:
Q: I can't change the position of a UIView I can't change the positions of a UIView as you can see in the following screenshot.
http://i.stack.imgur.com/fkvcw.png
The positions of the UIView are static - x:-20, y:16
How can I change the values?
Thanks.

A: if you want do this from IB then delete it and make again or do it prog.
Programmaticaly you can do like  this
 CGRect viewFrame=self.view.frame;
    viewFrame.origin.x=0;
    viewFrame.origin.y=0;

//also you set height and width
    viewFrame.size.height=460;
    viewFrame.size.width=320;
    self.view.frame=viewFrame;

A: I figured out playing with the size values and the layout position.
Click on the lowest-right dot in the dotted square. You will notice that both position values change. Now enter in the width field the new 'x' value and in the height field the new 'y' value. Click now on the upper-left dot and both 'x' and 'y' will reset to zero. You can now enter a new size and the view will be centered to its size.


text:
Q: Evaluating $ 1+\frac{\cos(\theta)}{1!}+\frac{\cos(2\theta)}{2!}+\frac{\cos(3\theta)}{3!}+\cdots $ Problem: We are asked to evaluate the infinite sum
$$
1+\frac{\cos(\theta)}{1!}+\frac{\cos(2\theta)}{2!}+\frac{\cos(3\theta)}{3!}+\cdots
$$
Thoughts on the problem: At first the infinite sum looks very similar to the power series expansion of the exponential function. However, instead of $\cos(\theta)^n$, we have $\cos(n\theta)$. I tried to use trig identities for $\cos(n\theta)$, but nothing seemed to jump out at first.
I know that $\cos(n\theta)$ is the $n$th Chebyshev polynomial evaluated at $\cos(\theta)$, and I was hoping that would allow us to simplify the expression somewhat. However, I do not know of any identities relating sums of these polynomials, so this did not get me very far.
Can anyone share a useful way to use the Chebyshev polynomials or give a reason why we should not use them? If not, what would be another good starting point? Thanks.

A: Hint
$$\cos(n\theta)+i\sin(n\theta)=e^{in\theta}$$


text:
Q: why is not reading the variable in pl sql? Please can you guide me on where im wrong. What i want to achieve is if the database name is either DEV or QA, run the dir creation.  It should skip the deployment on other envs like PRD_DEV, PRD_QA etc
set serveroutput on;
declare
lv_create_dir_sql varchar2(400) := 'CREATE OR REPLACE DIRECTORY REFRESH as ''/mnt/refresh'';'
lc_s_db_name    CONSTANT VARCHAR2(30) := 'DEV';
lc_p_db_name    CONSTANT VARCHAR2(30) := 'QA';

begin

    select name into lv_db_name from v$database;
 begin

     if (lv_db_name <> lc_s_db_name) or
        (lv_db_name <> lc_p_db_name) then

        execute immediate lv_create_dir_sql;
    end if;
 end;
/

A: You have not declared variable lv_db_name anywhere.
set serveroutput on;
declare
lv_create_dir_sql varchar2(400) := 'CREATE OR REPLACE DIRECTORY REFRESH as ''/mnt/refresh'';'
lc_s_db_name    CONSTANT VARCHAR2(30) := 'DEV';
lc_p_db_name    CONSTANT VARCHAR2(30) := 'QA';
lv_db_name      VARCHAR2(100);
begin

    select name into lv_db_name from v$database;
 begin

     if (lv_db_name <> lc_s_db_name) or
        (lv_db_name <> lc_p_db_name) then

        execute immediate lv_create_dir_sql;
    end if;
 end;
/

A: You have
(lv_db_name <> lc_s_db_name)
or (lv_db_name <> lc_p_db_name)

which means it will always create the directory, because 'DEV' <> 'QA'!
You should say
(lv_db_name = lc_s_db_name)
or (lv_db_name = lc_p_db_name)

or more smoothly:
lv_db_name in (lc_s_db_name, lc_p_db_name)

A: There are some things wrong in the code

*

*You are using 2 begin, but only one end. The second begin is not needed.

*If you are creating a directory, you will need to grant privileges over that directory to someone I guess

*The ; in the statement that creates the directory must be outside.

*It is not clear whether you want or not to create the directory when the database is either DEV or QA. If you want use in , if not use not in

*replace user1 and user2 for the users you want to grant privileges over.

So
set serveroutput on
declare
lv_create_dir_sql varchar2(400) := 'CREATE OR REPLACE DIRECTORY REFRESH as ''/mnt/refresh'' ';
lv_create_dir_grt varchar2(400) := 'grant read,write on directory REFRESH to user1, user2 '  ;
lc_s_db_name      varchar2(30)  := 'DEV';
lc_p_db_name      varchar2(30)  := 'QA';
begin
    select name into lv_db_name from v$database;
    if lv_db_name in ( lc_s_db_name , lc_p_db_name ) -- if you want to create the directory when the db is any of the two. If not, use not in
    then
         execute immediate lv_create_dir_sql;
         execute immediate lv_create_dir_grt;
    end if;
end;
/


text:
Q: Invalid object name 'DQM.dbo.ST_0043_BLANK_CONSENT_SAP_SIEBEL' Hi all, Yes same person from an earlier question... I'm really bad when it comes to Cursors/SQL
I have been using the below stored procedure/cursor that I have made.. It compiles properly, the problem comes when i try to execute it I get this error:
Msg 208, Level 16, State 1, Line 1
Invalid object name 'DQM.dbo.ST_0043_BLANK_CONSENT_SAP_SIEBEL'.
(0 row(s) affected)
Msg 208, Level 16, State 1, Line 1
Invalid object name 'DQM.dbo.ST_0044_CONSENT_SIEBEL_SAP_DIFF'.
(0 row(s) affected)
Msg 208, Level 16, State 1, Line 1
Invalid object name 'DQM.dbo.ST_0045_CONSENT_SIEBEL_BANNER_DIFF'.
Now I know for a fact all of these objects exist as when I do a select all, i get rows returned. Any help would be appreciated.
    USE [Adhoc_datafix]
GO
/****** Object:  StoredProcedure [dbo].[CostTest_02]    Script Date: 01/10/2013 15:43:32 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[CostTest_02]
AS
BEGIN

DECLARE @Issue_id int;
DECLARE @Master_id int;
DECLARE @Issue_table varchar(255);
DECLARE @price real;
DECLARE @rowcount bigint;
DECLARE @sql varchar(3000)

DECLARE cost_cursor cursor FOR
SELECT [Issue Id], [Master Issue Id], [Issue Table], [Price]
from Adhoc_datafix..[IssueTable]
FOR UPDATE OF [Issue Id];

OPEN cost_cursor;
FETCH NEXT FROM cost_cursor into @Issue_ID, @Master_id, @Issue_table, @Price

WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @sql = 'Select count(*) from DQM.' + quotename(@Issue_table)
EXEC(@sql)
set @Rowcount = @@rowcount

UPDATE ADHOC_DATAFIX..[Issue Cost]
set [Issue Id] = @Issue_ID ,
    [Master Issue Id] = @Master_ID ,
    [Row Count] = @Rowcount,
    [Cost] = CAST(@Rowcount * @price as money)

--WHERE CURRENT OF cost_cursor;
FETCH NEXT FROM cost_cursor into @Issue_ID, @Master_id, @Issue_table, @Price
END

close cost_cursor;

DEALLOCATE cost_cursor;
END

A: The problem seems to be that you are using QUOTENAME() to quote the schema and table name together:
select quotename('dbo.ST_0045_CONSENT_SIEBEL_BANNER_DIFF')
-- returns [dbo.ST_0045_CONSENT_SIEBEL_BANNER_DIFF]

So SQL Server thinks you are trying to query a table called [dbo.ST_0045_CONSENT_SIEBEL_BANNER_DIFF] in the DQM schema:
select * from DQM.[dbo.ST_0045_CONSENT_SIEBEL_BANNER_DIFF]

But you really want to query a table called [ST_0045_CONSENT_SIEBEL_BANNER_DIFF] in the dbo schema:
select * from DQM.dbo.[ST_0045_CONSENT_SIEBEL_BANNER_DIFF]

To fix this, either remove the dbo. prefix from the start of the @Issue_Table string and hard-code it after DQM, or if you want to support different schemas use PARSENAME() to get the schema and table name separately:
SELECT @sql = 'Select count(*) from DQM.' + quotename(parsename(@Issue_table, 2)) + N'.' + quotename(parsename(@Issue_table, 1))

And as a general suggestion, any time you work with dynamic SQL, give yourself an easy way to PRINTor SELECT the final string so you can see if the query you constructed is really correct.


text:
Q: Screen rotation keeps getting cancelled I am trying to create pwa that is locked in portrait-primary mode the whole time and gets into landscape primary if someone tries to open a youtube iframe in the app. I am using screen.orientation.lock("landscape-primary") to switch orientation when someone enters fullscreen mode in youtube. But it keeps getting overridden everytime.
DOMException: A call to screen.orientation.lock() or screen.orientation.unlock() canceled this call.


text:
Q: Graph API - how to move email to sub folder in Inbox Hi im try to move email from inbox to inbox/processed folder. i have written bellow code but it doesn't work
$dataar = array("destinationId" => "Inbox/processed");
$postdata = json_encode($dataar);
$chmove = curl_init();
curl_setopt_array($chmove, array(
                CURLOPT_URL => $urlsendgetattidmove,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'POST',
                CURLOPT_POSTFIELDS => $postdata,
                CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                 'Authorization: Bearer '.$access_token.''
               ),
  ));
$responsemove = curl_exec($chmove);
curl_close($chmove);

but if i put folder outside inbox then it works
 $dataar = array("destinationId" => "Archive");

A: i was able to do it by providing the folder id instead of name
  $dataar = array("destinationId" =>
  "J5RI79oYT8ILx0AQB2ou16VKQgQbgSOmYTxqIIAAdL44EXAAA=");


text:
Q: add two or more time strings in php I have an array with times (string) e.g "2:23", "3:2:22" etc.
$times = array("2:33", "4:2:22", "3:22") //loner

I want to find the total sum of all array.
Is there a way that I could add times like "2:33" and "3:33" ("i:s")
thanks

A: You might want to look at the PHP date/time functions - one option would be to use something like strtotime():
$midnight = strtotime("0:00");

// ssm = seconds since midnight
$ssm1 = strtotime("2:33") - $midnight;
$ssm2 = strtotime("3:33") - $midnight;

// This gives you the total seconds since midnight resulting from the sum of the two
$totalseconds = $ssm1 + $ssm2; // will be 21960 (6 hours and 6 minutes worth of seconds)

// If you want an output in a time format again, this will format the output in
// 24-hour time:
$formattedTime = date("G:i", $midnight + totalseconds);

// $formattedTime winds up as "6:06"

A: There is no builtin way of doing this - all time functions operate on times,
not on durations. In your case, you can explode() and add the parts
separately. I would recommend writing a class. Simple example:
class Duration {

    public static function fromString($string) {
        $parts = explode(':', $string);
        $object = new self();
        if (count($parts) === 2) {
            $object->minutes = $parts[0];
            $object->seconds = $parts[1];
        } elseif (count($parts) === 3) {
            $object->hours = $parts[0];
            $object->minutes = $parts[1];
            $object->seconds = $parts[2];
        } else {
            // handle error
        }
        return $object;
    }

    private $hours;
    private $minutes;
    private $seconds;

    public function getHours() {
        return $this->hours;
    }

    public function getMinutes() {
        return $this->minutes;
    }

    public function getSeconds() {
        return $this->seconds;
    }

    public function add(Duration $d) {
        $this->hours += $d->hours;
        $this->minutes += $d->minutes;
        $this->seconds += $d->seconds;
        while ($this->seconds >= 60) {
            $this->seconds -= 60;
            $this->minutes++;
        }
        while ($this->minutes >= 60) {
            $this->minutes -= 60;
            $this->hours++;
        }
    }

    public function __toString() {
        return implode(':', array($this->hours, $this->minutes, $this->seconds));
    }

}

$d1 = Duration::fromString('2:22');
$d1->add(Duration::fromString('3:33'));
echo $d1; // should print 5:55

A: So you want to add a duration to a time, meaning add a number of hours, minutes and seconds to a time?
Perhaps you might use Dav's strtotime to get the seconds from midnight for the time, then add the duration using an sscanf, thus:
$midnight = strtotime("0:00");

// ssm = seconds since midnight
$ssm1 = strtotime("2:33") - $midnight;

// sscanf the time string... you might need to include the possibility of seconds
list($hour, $minute) = sscanf("3:33", "%d:%d");

// a
$answer_ssm = $ssm + $hour * 3600 + $minute * 60;

echo strftime("%H:%M:%S", $answer_ssm);
Can't test this from where I am so pls excuse any syntax errors... just trying to give an example.  You'll also need to iterate across your array of course.


text:
Q: Melhor forma de recuperar dados para um Datagridview? Qual a melhor forma de recuperar os dados de uma tabela direto para um DataGridView ?
Estou com várias dúvidas, pois, muita gente não recomenda usar UnitOfWork o que facilita bastante e deixa o código bem mais limpo.
    var unitOfWork = new UnitOfWork(new DBConecta());
    var _registros = unitOfWork.RepoPaises.Get();
    BindingListView<CNAES> _DataView = new BindingListView<CNAES>(_registros);
    dbGride.DataSource = _DataView;

Após ver aqui no forum pessoas dizendo que não faz sentido usar UoW, já que o Entity Framework já é a camada de acesso, voltei para o modo normal, mas estou achando tudo muito estranho
        _context = new DBConecta();

        var registros = _context.CNAES.
            Select(c => new
            {
                id = c.id,
                nome = c.nome,
                ativo = c.ativo,
                usuarioNome = c.usuario.primeiro_nome + " " + c.usuario.segundo_nome,
                created_at = c.created_at,
                updated_at = c.updated_at,
                usuario_id = c.usuario_id
            }).ToList();

        this.dbGride.DataSource = registros;
        AfterRetrieve();
        _context.Dispose();

Como nunca trabalhei em equipes de .NET não sei quais as melhores práticas, gostaria de uma orientação. Obrigado.

A: Da maneira que você fez não está errado.
Como sugestão, na sua entidade CNAES vc poderia criar uma propriedade chamada usuarioNome que retorna o nome e o sobrenome
public usuarioNome
{
    get {
        if (usuario == null) return "";
        return usuario.primeiro_nome + " " + usuario.segundo_nome
    }
}

Assim vc pode simplificar seu código para popular seu combo dbGride.DataSource = _context.CNAES.ToList();
Uma boa prática seria também fazer a paginação dos seus dados utilizando os metodos Take e Skip
dbGride.DataSource = _context.CNAES.Skip(100).Take(50).ToList();

A: Bom pessoal, o melhor modo de fazer este select, envolvendo uma entidade e a tabela de usuários (para buscar o usuário que trabalhou por último no registro) que eu encontrei, foi este :
    protected override void Retrieve()
    {
        base.Retrieve();
        _context = new DBConecta(this.strConecta);

        var _query = from r in _context.CNAES
                     from u in _context.Usuarios
                     where u.id == r.usuario_id
                     select new { r.id, r.nome, r.ativo, r.created_at, r.updated_at, r.usuario_id, usuarioNome = r.usuario.login };

        dbGride.DataSource = _query.ToList();
        AfterRetrieve();
    }

Fazendo assim, ele não traz todos os campos da tabela de usuários e sim apenas o campo que eu pedi. Isto é muito importante visto que uma tabela grande, trazer todos os dados de outra tabela referenciada pode ter um custo !
SELECT

Extent1.id,
Extent1.nome,
Extent1.ativo,
Extent1.created_at,
Extent1.updated_at,
Extent1.usuario_id,
Extent2.primeiro_nome
FROM cnaes AS Extent1 INNER JOIN Usuarios AS Extent2 ON Extent1.usuario_id = Extent2.id
-- Executing at 13/03/2016 16:54:36 -03:00
-- Completed in 0 ms with result: EFMySqlDataReader
Para mim esta foi a melhor solução.


text:
Q: Is Empire Total War compatible with 64-bit OS? ETW is an old game so I was wondering if it runs on Windows 7 Ultimate 64-bit OS.

A: The answer to your question is Yes.  Empire Total War should be compatible with Windows 7 64-bit OS.  There have been some issues with crashes and some other issues that I believe have been solved, but just in case you run into some crash problem you can visit here.


text:
Q: How to write test case for if else statement in Angular (Jasmine) I'm writing the test cases for custom directive in angular. Here is my code in stackblitz. Can anyone let me know how I can covered highlighted if else statement.
if (trimmedValue.length > 14) {
  // how to cover this statement
  trimmedValue = trimmedValue.substr(0, 14);
}

if (trimmedValue.substr(6, 2) !== '') {
  // how to cover this statement
  nricNumber.push(trimmedValue.substr(6, 2));
}

A: First you want to change the hostlistener in your directive to be like this or something similar depending on what the event you want to listen for is:
@HostListener('keydown', ['$event'])

Since you are putting the directive on an input you don't need to look for input in your directive, this will also make it only watch for 'keydown' on the host element. The first parameter of HostListener is supposed to be the event that you are listening for not just the name of the element.
So now if you change your test to emit a keydown event with the value in the input having a length greater than 14 you should hit that first if statement like the following:
it('should input value length > 14', () => {
    fixture = TestBed.createComponent(TestAutoDashNricComponent);
    const input = fixture.debugElement.query(By.directive(AutoDashNricDirective));

    // set value of input to something longer than 14
    input.nativeElement.value = '85060135229900000000123';

    const event = ({
      // set target to the input so you don't need to get it from the directive itself
      target: input.nativeElement,
    } as unknown) as KeyboardEvent;

    // trigger keydown with created event
    input.triggerEventHandler('keydown', event);

    // check length of input value
    expect(input.nativeElement.value.length).toBe(14);
});

Also note that I set the target to point to the input that is calling the directive. That way you don't need to look for 'input' inside of the directive itself.
With this example you should be able to hit the other if else statements by doing something similar.


text:
Q: Converting a string with commas into int, in swift let y = "1,312,000.99"
let z = (y as NSString).intValue
I want to get z to be equal to 1312000. So basically:

*

*String should get converted to int

*The integer should not have commas

*Anything after the decimal should be ignored.

A:

*

*String should get converted to int

*The integer should not have commas

*Anything after the decimal should be ignored.

I would argue that you need to do those in reverse:

*

*Get rid of everything after the decimal place

*Remove the none-numerical values

*Convert it to an Int
There are a number of ways you might do this
You could use CharacterSet.decimalDigits, something like...
"1,312,000.99".components(separatedBy: CharacterSet.decimalDigits.inverted).joined()

this is kind of messy, as the one thing I've not done, is remove the .99, but that could be done something like...
var value = "1,312,000.99"
value = String(value[value.startIndex..<value.firstIndex(of: ".")!])

note: I'm not checking to see if firstIndex is nil which it might be, so you'll need to compensate for that.
Another, possibly better, solution would be to make use of a NumberFormatter
let formater = NumberFormatter()
formater.numberStyle = .decimal
formater.locale = Locale(identifier: "en_AU")
let number = formater.number(from: "1,312,000.99")

Then you could just cast it to an Int value
let intValue = Int(number!)

Again, check number as it may be nil

A: Try code like this:
//Create a NumberFormatter that takes input strings with comma thousands separators and at least 1 decimal place
let inputFormatter = NumberFormatter()
inputFormatter.format = "###,###,###,###.#"
inputFormatter.locale = Locale(identifier:  "en_US_POSIX")

var numberString = "1,234,567.88"

//Convert the input string to an Int (which truncates the decimal portion)
if let value = inputFormatter.number(from: numberString)?.intValue {
    print(value)
    //print( outputString)
} else {
    print("Can't convert")
}


text:
Q: HAProxy backend sessions limits to 5000 by default. How to change it? Loadbalancing between 2 servers.
global part already has maxconn 75000
First server has maxconn 30000 and second server has maxconn 40000
On the Statistics Report page, on the backend table, Sessions Limit shows correctly for both server. However, it is set to 5000 for the backend line.
The number of current connections is relatively low at this time, but what would happen if the total for both servers exceed that limit of 5000?
What setting changes that limit for backend?


text:
Q: Spring AbstractSecurityWebApplicationInitializer doesn't start in integration test I have custom initialzer which extends AbstractSecurityWebApplicationInitializer. It adds couple filters to the beginning of the filter chain.
@Order(2)
public class SecurityApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
    @Override
    protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding(StandardCharsets.UTF_8.name());
        characterEncodingFilter.setForceEncoding(true);
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        insertFilters(servletContext, characterEncodingFilter, hiddenHttpMethodFilter);
    }
}

In production it works as expected. But I can't make it start (or better to say: make Spring load it) in integration test environment.
Here is the snippet of the test:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfiguration.class, FakeInMemoryMongoConfiguration.class, WebConfiguration.class})
@ActiveProfiles("test")
public class CarPartControllerIntegrationTest {
    @Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = webAppContextSetup(wac).build();
    }
    ...
}

I.e., SecurityApplicationInitializer.beforeSpringSecurityFilterChain() is not called during the test. For now I decided to manually add filters in the test's filter chain. But I think there should be a better solution.
Please help make the world a bit better :) Thanks!

A: You need to configure Spring Security for your your tests if you are using MockMvc.  You can inject the filter chain and then add it using the builder pattern.
This blog post describes in detail how to set this up and the different testing options with Spring Security.  http://spring.io/blog/2014/05/23/preview-spring-security-test-web-security
For your specific example you could do this:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = {ApplicationConfiguration.class, FakeInMemoryMongoConfiguration.class, WebConfiguration.class})
@ActiveProfiles("test")
public class CarPartControllerIntegrationTest {
    @Autowired
    private WebApplicationContext wac;

    @Autowired
    private Filter springSecurityFilterChain;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
          mockMvc = MockMvcBuilders
                  .webAppContextSetup(wac)
                  .addFilters(springSecurityFilterChain)
                  .build();
    }
}


text:
Q: [UIMenuController locationInView:]: unrecognized selector sent to instance 0x7f41ca0 When longpress on UIWebView I am displaying UIMenuController menuitem for click action. I have a note on UIMenuItem. When I click the note I need to store location coordinates to database. Before I used UILongPressGesture for storing coordinate values to database. But it was working. Why the UIMenuItem action is not working?
- (void)note:(id)sender   {

    NSLog(@"Note");

  //  UILongPressGestureRecognizer *sn=(UILongPressGestureRecognizer *)sender;

    xcor = [sender locationInView:wbCont.scrollView].x;
    ycor = [sender locationInView:wbCont.scrollView].y;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"db.sqlite"];
    NSLog(@"filepath %@",path);

    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) {

        const char *sql = [[NSString stringWithFormat:@"SELECT xcoor FROM touch where xcoor = '%f' AND ycoor = '%f' AND artt_id='%@'",xcor,ycor,artID] cStringUsingEncoding:NSUTF8StringEncoding];

        NSLog(@"sql is %s",sql);

        BOOL favExist = false;

        sqlite3_stmt *statement, *addStmt;

        if (sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK) {
            // We "step" through the results - once for each row.
            while (sqlite3_step(statement) == SQLITE_ROW) {

                favExist = true;
            }
        }

        if(!favExist){

            //Changes

            universal_button_tag = arc4random() % 99;

            NSLog(@"Universal Button tag: %d",universal_button_tag);

            const char *sqlInsert = [[NSString stringWithFormat:@"insert into touch (xcoor,ycoor,artt_id,button_tag) values ('%f','%f','%@','%d')", xcor,ycor,artID,universal_button_tag] cStringUsingEncoding:NSUTF8StringEncoding];

            //----

            NSLog(@"sql insert is %s",sqlInsert);

            // [catID release];

            if(sqlite3_prepare_v2(database, sqlInsert, -1, &addStmt, NULL) != SQLITE_OK)
                NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));

            NSLog(@"error is %s",sqlite3_errmsg(database));

            if(SQLITE_DONE != sqlite3_step(addStmt))
                NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));

        }

    }

A: If I understand correctly you are using https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIMenuItem_Class/Reference/MenuItem.html that is subclass of NSObject and do not have methods locationInView (gestures have that method), so you got unrecognized selector


text:
Q: Regarding scope in C++ with new operator If I declare an object in main, then call that class's member function (While inside the function I use the operator new to declare an object of another class), will that nested object still remain in scope after the member function call? in other other words, can I use that object still throughout main? I was going to create a vector of pointers and assign to each position a new object created by the class's function call.
Thankyou in advance! Please let me know if my question is vague.
P.S. If I must define the destructor in the .h file to delete what was created with new, correct? This is not automatically done by the compiler?
int main()
{
  Ship *list[5] = { 0, 0, 0, 0, 0 };
  char ch;
  int x1,y1,x2,y2;
  int n = 0;

  cin >> ch >> x1 >> y1 >> x2 >> y2;
  while ( cin )
  {
    try
    {
      Ship *p = Ship::makeShip(ch,x1,y1,x2,y2);
      list[n++] = p;
    }

In my program, makeShip returns a pointer to a new Ship Object. How come I can use the Ship object throughout my main()? I thought it goes out of scope after the second } ending brace for try? Thanks!!

A: Anything created with new remains live untill you destroy it with a delete. So object remains in scope and as long as you have a reference to refer the object, you can access it.
Only automatic variables go out of scope after the }. In your case you can access Ship objects via list.
Although I would recommend std::array<Ship> or std::vector<Ship> instead of Ship *[]
EDITAfter your question is edited and some code section is added, whether scope of Ship objects would end after } or not depends on what and how does Ship::makeShip return.

A: In this case it depends on implementation of Ship::makeShip.

*

*If makeShip stores pointer into some storage (for example static std::vector of std::unique_ptr pointers) then memory will be cleared after exit from program.
In this case you do not need to delete list manually, because you have only references.

*Ship::makeShip returns a pointer which you need to delete manually. In this case for all list items delete operator should be called.

And the last one,
It is bad practice to return raw pointers, it is really unclear how deal with it, when to delete, who owns and so on.
It will be better to return for example std::unique_ptr or std::shared_ptr.
In the first case it is clear that you becomes an owner of the pointer. In the second case it does not matter who owns, because ownership is shared