text:
Q: Decoupling Backbone views where one triggers change in other view I have a page which contains two Backbone Views. A view for list of contacts ContactsListView and a view for navigating NavView.
ContactsListView has collection of Contact models. My list of contacts collections is quite bigger so I don't want to display all of them on page load.
So I have implemented contacts collection to fetch only a range (initially 0 to 50) of contacts from server and ContactsListView displays it. And use NavView to display the range of contacts ContactsListView is displaying currently. It also has next and previous buttons on click of which ContactsListView should display next or previous range of contacts.
Here my NavView is actually controlling what range of contacts ContactsListView should be displaying. But I want to decouple ContactsListView from NavView.
I realized I can do this with creating a Range model (with from and to attributes with default set to 0 and 50) and passing it to ContactsListView and NavView. While ContactsListView adds a listener, ContactsListView.show(from, to), to change event on Range model and NavView is updating the Range model when clicked on next or previous button. As the Range model changes ContactsListView listener would fetch contacts to update it's view.
Or
I can create a Range model and pass it to NavView. NavView then updates the range on click of prev or next button and triggers an event rangeUpdated with range values on (NavView) itself.  I add listener on NavView in some additional code piece (probably my own controller object) and invoke ContactsListView.show(from, to) explicitly.
Which one is better way to decouple ContactsListView and NavView? Or is there other way to decouple them?

A: Initialize both views with Range model.
In Contact List view listen to Range model change event to request new data from Contacts collection and show them.
When click on Nav view just set the Range model with new values (it will trigger change event and your Contact List view will be updated).

A: As long as your question is tagged with backbone.marionette, I assume you are using it, or thinking about using it.
One option could be using the marionette.compositeview, that lets you define both a model and a collection in the same view, so you wouldn't need to share models between views.
But maybe, that could not the best approach if you really want to decouple both views. For decoupling them, your second option using your own controller (or marionette.controller) is the one I like more, as you don't need the range number as explicit data contained in a model within the ContactListView (you already have that information in NavView).
Lastly, I like to do the fetching/saving data from the Controller, and not from within the view. The View in MVC patterns just show things, getting information from the model. Retrieving data from server that will be stored in the model seems more a Controller operation. I don't know how are you binding the data with the view, but maybe the ideal will be fetching the data from the Controller, and let the view render itself when the change of model is detected.


text:
Q: Bootstrap tabs with Datatables TableTools I am using Datatable TableTools version 2.2.4. and Bootstrap v3.0.0. I am trying to export table in Bootstrap tab to CSV, XLS and PDF. I am using this code:
 tableTools: {
                "sSwfPath": instance.SwfUrl,
                "aButtons": ["csv", "xls", {
                    "sExtends": "pdf",
                    "mColumns": [ 1, 2, 3, 4,5,6]
                }]
             },

The problem is, that the table is in tab, which means it is not visible during initialization. If I put table out of tabs, it is working like a charm.
I googled this problem and the solutions were like this:
$('.nav-tabs a').on('shown.bs.tab', function (event) {
        var table = $.fn.dataTable.fnTables(true);
        if (table.length > 0) {
            $(table).dataTable().fnAdjustColumnSizing();
            var oTableTools = TableTools.fnGetInstance(table[0]);
            if (oTableTools != null && oTableTools.fnResizeRequired()) {
                oTableTools.fnResizeButtons();
            }
        }
    });

I am sure, that this event is fired but it didn't solve my problem.

A: Try this
JS
if ($('#TableID').is(':visible')) {
    InitTableTools($(this))
    // $(this) --> passes the table object if visible.
    //So that you can initialize table tools for that particular visible table only
}
else
{
DestroyTableTools($(this))// $(this) --> passes the table object if visible
}

function InitTableTools(Table)
{
 // code to initialize table tools
}
funtion DestroyTableTools()
{
// code to destroy the initialised table tools , if destroy option is available in plugin
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: What symmetry causes the Runge-Lenz vector to be conserved? Noether's theorem relates symmetries to conserved quantities.  For a central potential $V \propto \frac{1}{r}$, the Laplace-Runge-Lenz vector is conserved.  What is the symmetry associated with the conservation of this vector?

A: Conservation of the Runge-Lenz vector does not correspond to a symmetry of the Lagrangian itself. It arises from an invariance of the integral of the Lagrangian with respect to time, the classical action integral. Some time ago I wrote up a derivation of the conserved vector for any spherically symmetric potential:
http://analyticphysics.com/Runge Vector/The Symmetry Corresponding to the Runge Vector.htm
The derivation is at the level of Goldstein and is meant to fill in the gap left by its omission from graduate-level classical mechanics texts.

A: *

*Hamiltonian Problem. The Kepler problem has Hamiltonian
$$\begin{align} H~=~&T+V, \cr
T~:=~& \frac{p^2}{2m}, \cr
V~:=~& -\frac{k}{q}, \end{align}\tag{1} $$
where $m$ is the 2-body reduced mass. The Laplace–Runge–Lenz vector is (up to an irrelevant normalization)
$$\begin{align} A^j ~:=~&a^j  + km\frac{q^j}{q}, \cr
a^j~:=~&({\bf L} \times {\bf p})^j\cr
~=~&{\bf q}\cdot{\bf p}~p^j- p^2~q^j, \cr
\cr {\bf L}~:=~& {\bf q} \times {\bf p}.\end{align} \tag{2}$$

*Action. The Hamiltonian Lagrangian is
$$  L_H~:=~ \dot{\bf q}\cdot{\bf p} - H,\tag{3} $$
and the action is
$$ S[{\bf q},{\bf p}]~=~ \int {\rm d}t~L_H .\tag{4}$$
The non-zero fundamental canonical Poisson brackets are
$$ \{ q^i , p^j\}~=~ \delta^{ij}. \tag{5}$$

*Inverse Noether's Theorem. Quite generally in the Hamiltonian formulation, given a constant of motion $Q$, then the infinitesimal variation
$$\delta
~=~ -\varepsilon \{Q,\cdot\}\tag{6}$$
is a global off-shell symmetry of the action $S$ (modulo boundary terms). Here $\varepsilon$ is an infinitesimal global parameter, and $X_Q=\{Q,\cdot\}$ is a Hamiltonian vector field with Hamiltonian generator $Q$. The full Noether charge is $Q$, see e.g. my answer to this question. (The words on-shell and off-shell refer to whether the equations of motion are satisfied or not. The minus is conventional.)

*Variation. Let us check that the three Laplace–Runge–Lenz components $A^j$ are Hamiltonian generators of three continuous global off-shell symmetries of the action $S$. In detail, the infinitesimal variations $\delta= \varepsilon_j \{A^j,\cdot\}$ read
$$\begin{align} \delta  q^i
~=~&  \varepsilon_j  \{A^j,q^i\}   , \cr
 \{A^j,q^i\} ~=~& 2 p^i q^j - q^i p^j - {\bf q}\cdot{\bf p}~\delta^{ij}, \cr
 \delta  p^i ~=~&  \varepsilon_j  \{A^j,p^i\}   , \cr
\{A^j,p^i\}~=~& p^i p^j - p^2~\delta^{ij} +km\left(\frac{\delta^{ij}}{q}- \frac{q^i q^j}{q^3}\right), \cr
 \delta  t ~=~&0,\end{align} \tag{7}$$
where $\varepsilon_j$ are three infinitesimal parameters.

*Notice for later that
$$ {\bf q}\cdot\delta {\bf q}~=~\varepsilon_j({\bf q}\cdot{\bf p}~q^j - q^2~p^j), \tag{8} $$
$$\begin{align} {\bf p}\cdot\delta {\bf p}
~=~&\varepsilon_j km(\frac{p^j}{q}-\frac{{\bf q}\cdot{\bf p}~q^j}{q^3})\cr
~=~& -\frac{km}{q^3}{\bf q}\cdot\delta {\bf q},\end{align} \tag{9} $$
$$\begin{align} {\bf q}\cdot\delta {\bf p}~=~&\varepsilon_j({\bf q}\cdot{\bf p}~p^j - p^2~q^j )\cr
~=~&\varepsilon_j a^j, \end{align} \tag{10} $$
$$\begin{align} {\bf p}\cdot\delta {\bf q}~=~&2\varepsilon_j( p^2~q^j - {\bf q}\cdot{\bf p}~p^j)\cr
~=~&-2\varepsilon_j a^j~.\end{align} \tag{11} $$

*The Hamiltonian is invariant
$$ \delta  H ~=~ \frac{1}{m}{\bf p}\cdot\delta {\bf p} + \frac{k}{q^3}{\bf q}\cdot\delta {\bf q}~=~0, \tag{12}$$
showing that the Laplace–Runge–Lenz vector $A^j$ is classically a constant of motion
$$\frac{dA^j}{dt} ~\approx~ \{ A^j, H\}+\frac{\partial A^j}{\partial t} ~=~  0.\tag{13}$$
(We will use the $\approx$ sign to stress that an equation is an on-shell equation.)

*The variation of the Hamiltonian Lagrangian $L_H$ is a total time derivative
$$\begin{align} \delta L_H
~=~& \delta  (\dot{\bf q}\cdot{\bf p}) \cr
~=~& \dot{\bf q}\cdot\delta {\bf p} - \dot{\bf p}\cdot\delta {\bf q} + \frac{d({\bf p}\cdot\delta {\bf q})}{dt} \cr
~=~& \varepsilon_j\left( \dot{\bf q}\cdot{\bf p}~p^j - p^2~\dot{q}^j +  km\left( \frac{\dot{q}^j}{q} -  \frac{{\bf q} \cdot \dot{\bf q}~q^j}{q^3}\right)\right)    \cr
~-~&\varepsilon_j\left(2 \dot{\bf p}\cdot{\bf p}~q^j - \dot{\bf p}\cdot{\bf q}~p^j- {\bf p}\cdot{\bf q}~\dot{p}^j  \right) - 2\varepsilon_j\frac{da^j}{dt}\cr
~=~&\varepsilon_j\frac{df^j}{dt}, \cr
 f^j ~:=~& A^j-2a^j, \end{align} \tag{14}$$
and hence the action $S$ is invariant off-shell up to boundary terms.

*Noether charge. The bare Noether charge $Q_{(0)}^j$ is
$$\begin{align} Q_{(0)}^j~:=~& \frac{\partial L_H}{\partial \dot{q}^i}  \{A^j,q^i\}+\frac{\partial L_H}{\partial \dot{p}^i}  \{A^j,p^i\} \cr
~=~& p^i\{A^j,q^i\}\cr
~=~& -2a^j.\end{align} \tag{15}$$
The full Noether charge $Q^j$ (which takes the total time-derivative into account) becomes (minus) the Laplace–Runge–Lenz vector
$$\begin{align} Q^j~:=~&Q_{(0)}^j-f^j\cr
~=~& -2a^j-(A^j-2a^j)\cr
~=~& -A^j.\end{align}\tag{16}$$
$Q^j$ is conserved on-shell
$$\frac{dQ^j}{dt} ~\approx~  0,\tag{17}$$
due to Noether's first Theorem. Here $j$ is an index that labels the three symmetries.

*Lagrangian Problem. The Kepler problem has Lagrangian
$$\begin{align} L~=~&T-V, \cr
T~:=~& \frac{m}{2}\dot{q}^2, \cr
V~:=~& -\frac{k}{q}. \end{align} \tag{18} $$
The Lagrangian  momentum is
$$ {\bf p}~:=~\frac{\partial L}{\partial \dot{\bf q}}~=~m\dot{\bf q} \tag{19} . $$
Let us project the infinitesimal symmetry transformation (7) to the Lagrangian configuration space
$$\begin{align} \delta  q^i ~=~&  \varepsilon_j m \left( 2 \dot{q}^i q^j - q^i \dot{q}^j - {\bf q}\cdot\dot{\bf q}~\delta^{ij}\right), \cr
\delta  t ~=~&0.\end{align}\tag{20}$$
It would have been difficult to guess the infinitesimal symmetry transformation (20) without using the corresponding Hamiltonian formulation (7). But once we know it we can proceed within the Lagrangian formalism. The variation of the Lagrangian is a total time derivative
$$\begin{align} \delta L~=~&\varepsilon_j\frac{df^j}{dt}, \cr
f_j~:=~& m\left(m\dot{q}^2q^j- m{\bf q}\cdot\dot{\bf q}~\dot{q}^j +k
\frac{q^j}{q}\right)\cr
~=~&A^j-2 a^j
 . \end{align}\tag{21}$$
The bare Noether charge $Q_{(0)}^j$ is again
$$Q_{(0)}^j~:=~2m^2\left(\dot{q}^2q^j- {\bf q}\cdot\dot{\bf q}~\dot{q}^j\right) ~=~-2a^j . \tag{22}$$
The full Noether charge $Q^j$ becomes (minus) the Laplace–Runge–Lenz vector
$$\begin{align} Q^j~:=~&Q_{(0)}^j-f^j \cr
~=~& -2a^j-(A^j-2a^j)\cr
~=~& -A^j,\end{align}\tag{23}$$
similar to the Hamiltonian formulation (16).

A: While Kepler second law is simply a statement of the conservation of angular momentum (and as such it holds for all systems described by central forces), the first and the third laws are special and are linked with the unique form of the newtonian potential $-k/r$. In particular, Bertrand theorem assures that only the newtonian potential and the harmonic potential $kr^2$ give rise to closed orbits (no precession). It is natural to think that this must be due to some kind of symmetry of the problem. In fact, the particular symmetry of the newtonian potential is described exactly by the conservation of the RL vector (it can be shown that the RL vector is conserved iff the potential is central and newtonian). This, in turn, is due to a more general symmetry: if conservation of angular momentum is linked to the group of special orthogonal transformations in 3-dimensional space $SO(3)$, conservation of the RL vector must be linked to a 6-dimensional group of symmetries, since in this case there are apparently six conserved quantities (3 components of $L$ and 3 components of $\mathcal A$). In the case of bound orbits, this group is $SO(4)$, the group of rotations in 4-dimensional space.
Just to fix the notation, the RL vector is:
\begin{equation} \mathcal{A}=\textbf{p}\times\textbf{L}-\frac{km}{r}\textbf{x} \end{equation}
Calculate its total derivative:
\begin{equation}\frac{d\mathcal{A}}{dt}=-\nabla U\times(\textbf{x}\times\textbf{p})+\textbf{p}\times\frac{d\textbf{L}}{dt}-\frac{k\textbf{p}}{r}+\frac{k(\textbf{p}\cdot \textbf{x})}{r^3}\textbf{x} \end{equation}
Make use of Levi-Civita symbol to develop the cross terms:
\begin{equation}\epsilon_{sjk}\epsilon_{sil}=\delta_{ji}\delta_{kl}-\delta_{jl}\delta_{ki}   \end{equation}
Finally:
\begin{equation}
\frac{d\mathcal{A}}{dt}=\left(\textbf{x}\cdot\nabla U-\frac{k}{r}\right)\textbf{p}+\left[(\textbf{p}\cdot\textbf{x})\frac{k}{r^3}-2\textbf{p}\cdot\nabla U\right]\textbf{x}+(\textbf{p}\cdot\textbf{x})\nabla U
\end{equation}
Now, if the potential $U=U(r)$ is central:
\begin{equation}
(\nabla U)_j=\frac{\partial U}{\partial x_j}=\frac{dU}{dr}\frac{\partial r}{\partial x_j}=\frac{dU}{dr}\frac{x_j}{r}
\end{equation}
so
\begin{equation} \nabla U=\frac{dU}{dr}\frac{\textbf{x}}{r}\end{equation}
Substituting back:
\begin{equation}\frac{d\mathcal A}{dt}=\frac{1}{r}\left(\frac{dU}{dr}-\frac{k}{r^2}\right)[r^2\textbf{p}-(\textbf{x}\cdot\textbf{p})\textbf{x}]\end{equation}
Now, you see that if $U$ has exactly the newtonian form then the first parenthesis is zero and so the RL vector is conserved.
Maybe there's some slicker way to see it (Poisson brackets?), but this works anyway.

A: The symmetry is an example of an open symmetry, i.e. a symmetry group which varies from group  action orbit to orbit. For bound trajectories, it's SO(4). For parabolic ones, it's SE(3). For hyperbolic ones, it's SO(3,1). Such cases are better handled by groupoids.

A: (This post may be old, but we can add some precisions) The conservation of the RL vector is not trifling, it goes with the fact that you consider a central force, lead here by a Newtonian potential $\frac{1}{r}$ which has the property to be invariant under rotations (as $\frac{1}{r^n}$ but it works only for $n=1$ as shown by @quark1245).
Therefore, the S0(3) which has not 6 conserved quantities as said before but 3, the 3 generators of the symmetry $J_i$, i=1..3 such that the symmetry transformation under an infinitesimal change $x \rightarrow x + \epsilon$ is given in the canonical formalism by
$$
\delta_i X = \{X, J_i(\epsilon) \}
$$
and the algebra is
$$
\{ J_i, J_j \} = \epsilon_{ij}^k J_k.
$$
They are conserved because, at least for the Kepler problem, the system is invariant w.r.t a time translation, and the Hamiltonian is also conserved, and the calculations show that
$$
\{H,J_i\}= 0.
$$
Before their redefinition as shown on Wikipedia to see that the previous algebra is fulfilled, the generators of the rotations are : one is the angular momentum $L$ which shows that the movement is planar, therefore invariant under rotation around $L$, one is the RL vector which is in the plan, therefore perpendicular to $L$ and parallel to the major axis of the ellipse, and the third one has a name I don't remember, but is parallel to the minor axis.
We can see that their are only 3 degrees of freedom if we take place in the referential such that $\vec{J}_1 = \vec{L} = (0,0,L_z)$, then the planar generators are $A = (A_x,0,0)$ and $B = (0,B_y,0)$.
It has been shown that they can be constructed from the Killing-Yano tensors (which mean symmetry), and it works also at dimensions greater than 3. A nice review about the LRL vector derivation can be found in HeckmanVanHaalten

A: Looking at https://arxiv.org/abs/1207.5001 one gets a very nice solution. If one is not very keen into mathematics, their basic idea is to use the infinitesimal transformation
$$\delta x^i=\epsilon L^{ik}$$
where $L^{ik}=\dot{x}^ix^k-\dot{x}^k x^i$. Since angular momentum is conserved, kinetic energy won't change. On the other hand, the potential changes up to order $\epsilon^2$ like
$$\frac{k}{r+\delta r}=\frac{k}{((x^i+\delta x^i)(x_i+\delta x_i))^{1/2}}=\frac{k}{r}\left(1-\frac{x_i\delta x^i}{r^2}\right)=\frac{k}{r}-\epsilon\frac{kx_iL^{ik}}{r^3}=\frac{k}{r}-\epsilon\frac{d}{dt}\left(\frac{kx^k}{r}\right).$$
Therefore, the change in the action is
$$\epsilon\left[m\dot{x}_iL^{ik}\right]=[m\dot{x}_i\delta x^i]_{t_1}^{t_2}=\delta S=\epsilon\left[\frac{kx^k}{r}\right]_{t_1}^{t_2}.$$
This gives the conservation of the vector
$$m\dot{x}_iL^{ik}-\frac{kx^k}{r},$$
which can be easily shown to be the Runge-Lenz vector.

EDIT: In case someone prefers an index free notation, the symmetry is $\delta\vec{r}=\vec{\epsilon}\times\vec{L}$. Allowing for a time dependent $\vec{\epsilon}$, the variation in the action is then
$$\delta S=\int dt\left(m\vec{v}\cdot\delta\vec{v}-\frac{k}{\|\vec{r}\|^3}\vec{r}\cdot\delta\vec{r}\right)=\int dt\left(m\vec{v}\cdot(\dot{\vec{\epsilon}}\times\vec{L})+m\vec{v}\cdot(\vec{\epsilon}\times\dot{\vec{L}})-\frac{k}{\|\vec{r}\|^3}\vec{r}\cdot(\vec{\epsilon}\times\vec{L})\right).$$
When the equations of motion are valid, the second term vanishes due to conservation of momentum. Moreover, the third term would be a total derivative if $\vec{\epsilon}$ was constant
$$\frac{k}{\|\vec{r}\|^3}\vec{r}\cdot(\vec{\epsilon}\times\vec{L})=\frac{k}{\|\vec{r}\|^3}\vec{\epsilon}\cdot(\vec{L}\times\vec{r})=\frac{km}{\|\vec{r}\|^3}\vec{\epsilon}\cdot((\vec{r}\times\vec{v})\times\vec{r})=\frac{km}{\|\vec{r}\|^3}\vec{\epsilon}\cdot(-\vec{r}(\vec{v}\cdot\vec{r})+\vec{v}\|\vec{r}\|^2)=km\vec{\epsilon}\cdot\frac{d}{dt}\frac{\vec{r}}{\|\vec{r}\|}=km\vec{\epsilon}\cdot\frac{d\hat{r}}{dt}$$.
We conclude that when the equations of motion are valid
$$\delta S=\int dt\left(m\vec{v}\cdot(\dot{\vec{\epsilon}}\times\vec{L})-\vec{\epsilon}\cdot\frac{d}{dt}(mk\hat{r})\right).$$
We then see that when $\vec{\epsilon}$ is constant, the first term vanishes and the remaining term is a total derivative. We thus have a true symmetry of the system. On the other hand, allowing $\epsilon$ to be an arbitrary function of time which however vanishes at the endpoints, we can integrate by parts the first term to obtain
$$\delta S=\int dt\left(m\dot{\vec{\epsilon}}\cdot(\vec{L}\times\vec{v})-\vec{\epsilon}\cdot\frac{d}{dt}(mk\hat{r})\right)=\int dt\left(\dot{\vec{\epsilon}}\cdot(\vec{L}\times\vec{p})-\vec{\epsilon}\cdot\frac{d}{dt}(mk\hat{r})\right)\\=\int dt\vec{\epsilon}\cdot\frac{d}{dt}\left(\vec{p}\times\vec{L}-mk\hat{r}\right).$$
Since this is a variation vanishing at the endpoints, on the equations of motion it must be zero. Since $\vec{\epsilon}$ is otherwise arbitrary, we conclude that the following vector is conserved
$$\vec{p}\times\vec{L}-mk\hat{r}.$$
This the Runge-Lenz vector


text:
Q: AWK - request for clarification example I have 3 examples of using gsub:
1.
echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$1); print $1 "\t" $2}'
    A
B   B
    C

2.
$ echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$2); print $1 "\t" $2}'
A
B   B
C

3.
$ echo -e "A A\nB B\nC C" | awk '{gsub($(!/B/),"",$0); print $1 "\t" $2}'

.

Why in the 3 example awk nothing printed? Does awk should not print?:
B   B

Please explain 3 examples.
Thank you for your help.

A: The key point for me is this: $(!/B/). Very awkward. What does it mean (or at least I guess it means)?

*

*/B/: It tries to match the letter B in the whole line. If it matches returns 1, otherwise 0.

*!: Negates the previous result code.

*$(): It returns the whole line ($0) or the first field ($1) after resolving previous instructions.

The third case is ok.

*

*When B matches the instruction is gsub( $0, "", $0 ), an empty line. That's clear.

*When B doesn't match the instruction is gsub( $1, "", $0 ). So, as both letters are the same and gsub replaces many times by line, it deletes all characters. Add another different character and you will see the difference.

For example:
echo -e "A A 1\nB B 1\nC C 1" | awk '{gsub($(!/B/),"",$0); print $1 "\t" $2}'

That yields:
1

1


text:
Q: Setting type dynamically at run time in of clause in .Net I'm using LINQ to Entities to generate typed result sets in VB.Net.  I've got a generic Report class as follows:
Public Class Report
    Public Property Name As String
    Public Property SQL As String
    Public Property Type As String
End Class

Then in the calling scope I want to have code that does something like:
' create my data context
Dim context As New MyAppEntities
' get a report object out of a dropdown list
Dim rpt as Report = CType(aComboBox.SelectedItem, Report)
' create a result object based on the type stored in the object
Dim res As ObjectResult(Of rpt.Type) = context.ExecuteStoreQuery(Of rpt.Type)(rpt.SQL)

So far I'm finding that .Net won't let me set the type in the (Of Type) clause on the fly at runtime.
Does anyone know how to do this?
I've tried changing the Type property of the Report class to an object of type Type, but that doesn't work either.
BTW, I know there are alternative ways to accomplish the same thing, but I'm working with external constraints that make this what I've got to work with right now.  And anyway, intuitively something like this should work and I'd like to figure out how.

A: Here's the answer in C#:
Creating a Generic<T> type instance with a variable containing the Type
The relevant methods and code:
var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);

In this case, you'd use ObjectResult instead of List.  Hope that helps.

A: With option strict on you can't do that. Strict enforces static typing. With static typing you'll have to stick with Object but if you remove the strict option you can accomplish dynamic typing in vb.net
see this question


text:
Q: How resize/drag/drop image over a youtube video? I am working on a fiddle in which I want to resize/drag/drop an image over a youtube video.
In the above fiddle, I cannot resize the image at fast pace over the youtube video. I am not sure what are the reasons behind it. I can resize/drop/drag but not at a very fast pace.
The HTML/JS I have used in order to achieve the above fiddle is:
HTML:

JS(JQuery):
$(function() {
$('#wrapper').draggable();
$('#image').resizable();
});

Problem Statement:
I am wondering what changes I should make in the HTML code so that I am able to resize the Google Image properly. At this moment, it seems like I am not able to resize the image at fast pace.

A: youtube video complicates it, so create an overlay over video and make it visible when resize event starts, and hide when resize stops.
$('#image').resizable({
start: function( event, ui ) {
 $('#overlay').show();
},

stop: function( event, ui ) {
 $('#overlay').hide();
 }
 }
);
});

working code: https://jsfiddle.net/obn4yph0/


text:
Q: Firebase RT returns 4 objects but only 3 are available If there is anything I could add to assist please let me know. Trying to obtain the key for the items, but trying to first tackle retrieving the data and displaying it.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList, AngularFireObject } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  coursesRef: AngularFireObject<any>;
  courses: Observable<any>;

  constructor(db: AngularFireDatabase) {
    this.coursesRef = db.object('/courses');
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}

app.component.html
<ul>
  <li *ngFor="let course of courses | async">
    {{ course | json }}
  </li>
</ul>

this returns a 4 objects although the database only contains 3.

A: I believe the answer is that the object should be called in the ngOnInit function.
app.component.ts
import { Component, OnInit } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  coursesRef: AngularFireList<any>;
  courses: Observable<any[]>;

  constructor(private db: AngularFireDatabase) {
    this.coursesRef = db.list('/courses');
  }

  ngOnInit() {
    this.courses = this.coursesRef.valueChanges();

    this.courses.subscribe(course => console.log(course));
  }
}


text:
Q: WARNING: did not receive ack of last datagram after 10 tries I try making network performance measurement using iperf in UDP option. I perform all the operations in Ubuntu Terminal. I have two computer and I have number of interfaces on each of my computers. Interfaces other than Loopback and Local Host are created using high-gain antennas connected to computers. I create server side with the line of sudo iperf -s -u -B 192.168.2.2. For client side I use the line of sudo iperf -u -B 172.16.25.125 -c 192.168.2.2 -b 1M -t 15 -i -f m. It seems that interfaces are connected (the message is displayed only on the client side) to each other and client side shows Internal, Transfer and Bandwidth statistics for 15 seconds (comes from -t 15). However, in the end I expect Server Report to be displayed, but it is not displayed. Instead, I have WARNING: did not receive ack of last datagram after 10 tries, which is displayed only on the client side. In Server side, even "connected" message is not displayed. In server side basically nothing changes before, during, and after the iperf test. Thus, my question is why do I get this WARNING? How can I fix this? I appreciate your help.

A: If you're not seeing anything at all on the server side, it's likely not receiving anything at all from the client. I noticed your client and server appear to be on different networks, so I'd first ensure there's a path between them and that they can communicate with each other (can they ping?). Another possibility is a firewall exists in between them (default iperf port is 5001), so double-check to make sure the traffic isn't being blocked.
One way to quickly check is to use nc to see if you can pass UDP datagrams back and forth. On the server side, run:
nc -l -u 5001
On the client side, run:
nc -u 192.168.2.2 5001
Then type something into the client side and see if it appears on the server side.


text:
Q: Navigate to child component in Angular 2
How to navigate correctly to a child component in angular 4?

Here i have the route object:
{
    path: ':name',
    component: parentComponent,
    data: {
        title: 'string_title'
    },
    children: [
        {
            path: 'child/:id',
            component: childComponent,
            resolve: {
                data: DataResolver
            },
            data: {
                title: null
            }
        }
    ]
}

trying to navigate to child component by this way:
this.router.navigate(['child', item], {relativeTo: this.route});

After navigating url should be something like this:
parent/child/3

At the moment it redirects me to home page when i'm trying to navigate to child component. What's wrong in this logic?
Thanks!


text:
Q: Dynamic continued content load with AJAX What I am trying to achieve is a similar thing that most large pages do when there is a ton of content to display, but you just want to show a small portion of it and later continue loading more content (take for example the feed from Facebook, it just load the first 20 items and after scrolldown it loads the next ten or so). In my mind there are two approaches that come to mind (using PHP MySQL AJAX combination)

*

*AJAX request, find all all results, return data, use data in javascript and handle logic.

*AJAX request, find all results limit to a few, return data, users wants more data, AJAX request, find all results limit interval [few, few + few].

Maybe to clarify, the data that I want to get with the request are not really big, i just thought that reducing the number of queries is always a good idea when it comes to AJAX requests done by a user.
Both approaches do not really seem pretty and I am sure that there will be a much more elegant solution to this.

A: I can't really think of any other options and actually your second option is how a lot of websites handle this sort of thing. It all depends on how much data is 'a ton of content'.
The easiest option (IMHO) is your first one, however it's pretty clear that you you have as much data as facebook it's just not feasible to fetch and store it all (imagine the page loading times!).
But afterall those are only two options: fetch it all at once, or fetch it in bits as required.


text:
Q: Binary Heap Height In a Binary Heap with N nodes and a height of h:
1 + 2^1 + 2^2 + … + 2^(h-1) + 1 <= N <= 1 + 2^1 + 2^2 + … + 2^(h-1) + 2^h
2^h <= N < 2^(h+1)
h  <= log2(N)  <  h+1

In the last line:
The first inequality implies that h is O(log N).
But how come that the second second inequality implies that h is Ω(log N) ?
If it was "log2(N)  <  h", I would understand it, but my problem is with the "1" in "h+1".

A: From the second inequality, you have that
h + 1 > log(N) ↠ h > log(N) - 1,
Therefore,
h  = Ω(log(N) - 1).
However,
log(N) - 1 = Θ(log(N)),
and you can use the transitive rule that
f(N) = Ω(g(N)) and g(N) = Θ(h(N)) implies that f(N) = Ω(h(N)).


text:
Q: Trying to read oplog, but got empty result I'm trying to take a look at the oplog, so I downloaded mongodb-4.0.3 for Linux, created a config file:
replSet = rs0
dbpath = /data

And started mongodb with ./bin/mongod --config db.conf, and initialize replication:
> rs.initiate({_id:"rs0", members: [{"_id":1, "host":"127.0.0.1:27017"}]})
{
    "ok" : 1,
    "operationTime" : Timestamp(1599312413, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1599312413, 1),
        "signature" : {
            "hash" : BinData(0,"AAAAAAAAAAAAAAAAAAAAAAAAAAA="),
            "keyId" : NumberLong(0)
        }
    }
}

Then I tried to created some collection:
use books
db.users.create()
db.users.insert({id:2, name: "whatever"})

But no oplog is available:
rs0:PRIMARY> db.oplog.rs.find()

What was wrong?

A: You need to use the local database
use local;
db.oplog.rs.find()


text:
Q: divide an array to create multidimensional array I'm looking for a method to divide a one dimensional array by a number n to create a multidimensional array with each element having (at most) length n.
For example
[1,2,3,4,5,6] / 3

should result in:
[[1,2,3],[4,5,6]]

A: This should do it...
chunkedArr = arr.each_slice(3).to_a;


text:
Q: Young's Double Slit Experiment: Angle between incoming waves Consider the experimental setup for Young's Double Slit Experiment:

Here there is an angle between the directions of propagation of waves ,i.e., $\angle S_1PS_2$ - the angle between the electric and magnetic field vectors at that point other than the phase difference.
My question is:
Why is this angle never taken into account while analysing this experiment or the diffraction experiments?

Source of the image: https://www.embibe.com/study/effect-of-placing-thin-transparent-film-in-ydse-in-front-of-slits-concept

A: Typically we assume that the distance to the screen is much larger than the width of the slits or the separation of the slits. The light that emerges from the two slits at an angle of theta are almost parallel. Thus, theoretically and approximately there is no angle $S_1 P S_2$.


text:
Q: Law's of Mechanics are Galilean invariant In my current physics book one line reads:

"The laws of mechanics are Galilean invariant.",

with corollary:

"No mechanical experiment can be used to tell whether an inertial frame is moving or at rest (with respect to any other frame).".

I understand that you cannot tell whether you are moving with respect to something else or whether that something else is moving with respect to you, or that you cannot tell whether you are being accelerated with respect to another frame or vice versa. But does the corollary basically imply that since you can take both reference frames at rest and have the other move with respect to your chosen frame, that either can be moving with respect to the other?

A: Galileian relativity tell us about inertial reference frames, systems in which Newton's second law is valid: $\vec{F} = m\vec{a} $. We are in the realm of Newtonian mechanincs.
This principle of relativity tell us that the law of physics are the same in all inertial reference frame (r.f), meaning that the structure of the equations are the same in systems that move with constant velocity one respect each other. Constant means that the magnitude and also the direction doesn't change.
This implies that if we have say three r.f: A, B and C; if A is moving at constant velocity with respect to r.f B and C, means that B are moving with constant velocity respect to C.
So, mechanical experiments performed in A, doesn't tell you if A is moving respect to B or C. You can immagine to do such an experiment like characterizing simple pendulum, or the collisions of balls, and you are closed in a boat or in a train moving at constant velocity respect to the ground. Without can't seeing outside, you cannot say if you are moving respect to the ground or not, watching the results of these experiments.

A: The additional remark is not a corollary.
The expression 'galilean invariant' is abstract, which allows it to be short.
The text that follows is an attempt at stating what the expression 'galilean invariant' stands for.
That is surprisingly difficult; it is an attempt to express an abstract concept in concrete words. Whatever you try, it will always be awkward.
I prefer the following assertion of galilean invariance:
(Yeah, it's longer.)
There is an equivalence class of inertial frames of reference. Each member of the equivalence class has a uniform velocity with respect to any other member of the equivalence class. A local mechanical experiment cannot find the magnitude of velocity with respect to any other member of the equivalence class.

Velocity is a vector quantity, so for any single member of the equivalence class you can think of the set of all velocites of the other members as a space. An abstract velocity space. But it is a space that doesn't have a zero point. When describing what galilean invariance stands for you have to accommodate that not-having-a-zero-point. You cannot single out a member; the very property that you cannot single out a member is fundamental.

A:
You cannot tell whether you are moving with respect to something else

This is true with a proviso, that you are moving at constant velocity, here meaning that you aren't accelerating. This is the content of Galilean relativity. Which is why your later statement:

You cannot tell whether you are being accelerated wrt another frame or vice-versa

is false.
Hence:

That either can be moving wrt the other

is ambiguous, as you haven't specified how they are moving. That acceleration isn't Galilean invariant was partly demonstrated by Newtons bucket experiment where a bucket partially filled with water is rotated at constant speed. Here, we see that the surface of the water becomes concave and so thos motion can't be Galilean relative. Now, although it is rotating at constant speed, it's not constant linear velocity, and so this is acceleration and hence this is why Galilean relativity doesn't apply.


text:
Q: iPhone UIView animation until stop pressing i have two views and one viewcontroller: one contains UIImageView with image, second have touchesBegan and touchesEnded method:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [viewcontroller moveMethod];
}

How to make moveMethod method to make the animation (eg. moving the x-axis) repeat smoothly until I stop to push the view?

A: try this code to move your view on x-axis
CGRect frame=view.frame;
frame.origin.x=frame.origin.x+200;
[UIView beginAnimations:@"" context:nil];
[UIView setAnimationDuration:2];
[UIView setAnimationDelegate:self];
view.frame=frame;
[UIView commitAnimations];


text: Q: Reverting python back to stock I have created a mess of Python packages. I have installed some packages with pip and others with apt, and then I have got 3 different versions of Python: python2.7, python3, python3.8. I am now getting errors every now and then that I often spend hours Googling and trying to fix only to find out that it was the packages clashing or something. So, today, I finally decided to nuke everything-python and do a clean install of Python, but since Linux itself depends on Python, I decided to do some Googling to find out the safest way to do that; but I have not found any. There is advice online ranging from "sudo apt purge python" to "DO NOT TOUCH IT", and I was really confused. I want Python to be in the state it was when I first installed Ubuntu. But if there is no safe way of doing that, I will take however much of the junk I can get rid of safely. Also, there is some advice online that package managers like conda are non-intrusive, and if I install one, the packages I install there won't interfere with the ones installed with pip and apt, and life will be happy everafter. How true is this?


text:
Q: ArrayListModel will not sync with JList I have combed through SO, and have found many questions on the topic of my problem but do not answer it.
I am setting up an MVC, I have set up things correctly to best of my knowledge but I cannot get the Controller to show in my view. I am working on an assignment that essentially is a program for a Video Rental Store.
First, In a class called RentalStoreGUI, I set up my panels and everything looks good when I run.
RentalStoreEngine model = new RentalStoreEngine();
    JList<DVD> list = new JList<DVD>();
    list.setModel(model);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    list.setVisible(true);

    list.setSelectedIndex(0);
    jScrollPane = new JScrollPane(list);

    add(jScrollPane, BorderLayout.CENTER);
    add(buttonPanel, BorderLayout.SOUTH);

As you can see I set my model for the list based on another class called RentalStoreEngine() and it implements AbstractListModel. The Abstract List model is functioning when I do class specific testing and all of the necessary methods are implemented. Here is an example of my add method from that class:
public  void add(DVD d){
    if (d != null){
        rentals.add(d);//rentals is an arrayList<DVD> instantiated earlier
        fireIntervalAdded(this, rentals.size() - 1, rentals.size() - 1);
    }
}

Here is the actionPerformed method, it runs DVD_Dialog which simply gets some input from the user and creates a new DVD object from that.
public void actionPerformed(ActionEvent event) {

    if(event.getSource() == rentDVD){

        DVD_Dialog = new RentDVDDialog(this, null);
        DVD_Dialog.clear();
        DVD_Dialog.setVisible(true);
        dvd = new DVD(DVD_Dialog.getTitleText(),DVD_Dialog.getRenterText(),
                DVD_Dialog.getRentedOnText(), DVD_Dialog.getDueBackText());

        if(DVD_Dialog.closeStatus() == true){
        model.add(dvd);

        }
    }

Eclipse gives me no errors, until I run it. I then receive a nullPointerException at the line model.add(dvd); Based on all my research the list.setModel(model) and the fireIntervalAdded method line should update the Jlist on its own. But it does not. And as I said, class specific testing for both the GUI and the Model are producing the desired results, but when it comes to integrating them I am at a loss.


text:
Q: Delete not complete I use spring boot 2, jpa and hibernate.
Db is postgres
I try to delete an object with child
@Entity
@IdClass(SamplingsPK.class)
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Samplings {

    @Id
    private int year; //only last 2 number 2018 -> 18

    @Id
    @GeneratedValue
    private Integer sequenceId;

    @OneToOne
    private Colors color;

    @OneToMany(mappedBy = "sampling", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Samples> samples = new ArrayList<>();

    @Embedded
    private TestSamplings testSamplings;

    ...
}

public class SamplingsPK implements Serializable {

    private int year;

    private Integer sequenceId;

    public SamplingsPK(int year, Integer sequenceId) {
        this.sequenceId = sequenceId;
        this.year = year;
    }

    private SamplingsPK() {

    }
    ...
}

@Entity
@IdClass(SamplesPK.class)
public class Samples{

    @Id
    private String sampleLetter;

    @Id
    @ManyToOne(optional = false)
    @JoinColumns({
        @JoinColumn(name = "sampling_id", referencedColumnName = "sequenceId"),
        @JoinColumn(name = "sampling_year", referencedColumnName = "year")})
    private Samplings sampling;

    @OneToOne(mappedBy = "sample", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private TestSamples testSamples;
    ...
}

@Entity
public class TestSamples {

    @Id
    @SequenceGenerator(name = "test_samples_id_seq", sequenceName = "test_samples_id_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "test_samples_id_seq")
    private Integer id;

    @OneToOne(fetch = FetchType.LAZY)
    private Samples sample;

    @OneToOne(mappedBy = "testSample", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private Compressions compressionTest;
    ....
}

@Repository
public interface SamplingsRepository extends JpaRepository<Samplings, SamplingsPK> {
}

If i delete Samplings, Samples, TestSamples, and Compressions should be deleted.
My delete
@Transactional
public void deleteSamplings(int year, Integer id) {
    samplingsRepository.deleteById(new SamplingsPK(year, id));

}

When this method is called I see

delete
      from
          samples
      where
          sample_letter=?
          and sampling_id=?
          and sampling_year=?
2018-10-03 22:21:05.832 ERROR 14511 --- [nio-8080-exec-9]
  o.h.i.ExceptionMapperStandardImpl        : HHH000346: Error during
  managed flush [Batch update returned unexpected row count from update
  [0]; actual row count: 0; expected: 1] 2018-10-03 22:21:05.834  INFO
  14511 --- [nio-8080-exec-9] o.h.e.j.b.internal.AbstractBatchImpl     :
  HHH000010: On release of batch it still contained JDBC statements
  2018-10-03 22:21:05.848 ERROR 14511 --- [nio-8080-exec-9]
  o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for
  servlet [dispatcherServlet] in context with path [] threw exception
  [Request processing failed; nested exception is
  org.springframework.orm.ObjectOptimisticLockingFailureException: Batch
  update returned unexpected row count from update [0]; actual row
  count: 0; expected: 1; nested exception is
  org.hibernate.StaleStateException: Batch update returned unexpected
  row count from update [0]; actual row count: 0; expected: 1] with root
  cause
      at com.lcm.service.SamplingsService$$EnhancerBySpringCGLIB$$d589edcb.deleteSamplings()
  ~[main/:na]

there are no query for sample and others
just search a way to delete every thing...

A: This is probably because you are trying to update/delete something that has no difference or doesn't exist anymore.
Besides that, the ID property should not be set explicitly using setters (this seems not to be your case), if you use any generator class.
If you set the value of the Id property explicitly, it will cause this error. Check in the Hibernate mapping file the field generator="native" or "incremental" and in your DATABASE the table mapped is not auto_incremented.
Also try to update your table to set auto_increment

A: Generated delete query is kind of suspicious.
delete from samples where sample_letter=? and sampling_id=? and sampling_year=?
Considering you are deleting by id, the where clause should not include condition sample_letter = ?. This is because new SamplingsPK(year, id) has no information about sample_letter. I would investigate what value is being passed for sample_letter parameter.
Also, having two fields annotated as @Id in Samplings class doesn't seem semantically correct with @IdClass(SamplesPK.class).
I would advise to either remove @Id from the field sampleLetter or create another IdClass with keys sampleLetter year, and sequenceId.


text:
Q: Android TextInputEditText flooding logs with requestLayout() warnings when using endIconMode attribute I have a layout with two text input fields, which disappear & re-appear as options change.
However, when I use attribute app:endIconMode="clear_text", these two warnings flood the logs without end, for both of the text fields.

W/View: requestLayout() improperly called by
  com.google.android.material.textfield.TextInputEditText{ba3099c
  VFED..CL. ......ID 0,0-1244,272 #7f0a00c6 app:id/homeInput} during
  layout: running second layout pass
W/View: requestLayout() improperly called by
  com.google.android.material.textfield.TextInputEditText{f641714
  VFED..CL. ......ID 0,0-1244,224 #7f0a00e6 app:id/lockInput} during
  layout: running second layout pass

The text fields that are visible depends on RadioButton selections
Snippet of one of the text field XMLs:
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/alt_sub"
    style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="24dp"
    android:layout_marginEnd="40dp"
    android:animateLayoutChanges="true"
    app:boxCornerRadiusTopEnd="8dp"
    app:boxCornerRadiusTopStart="8dp"
    app:boxStrokeColor="@color/colorAccent"
    app:endIconMode="clear_text"
    app:hintTextColor="@color/colorAccent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/main_sub">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/lockInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_+"
        android:fontFamily="@font/opensansregular"
        android:inputType="textNoSuggestions" />
</com.google.android.material.textfield.TextInputLayout>

Whenever I call setText() or setHint() in the Activity class, the warning starts to pop up. The warnings only stop when the text field is empty.
I feel that this may be related to the attribute app:endIconMode="clear_text", but I can't find a way to use it without getting these warnings.

A: I had the same issue with different endIconModes and didn't find any solution on the internet so I opened a defect with google:
https://issuetracker.google.com/issues/132651327
The issue was fixed today and it should work properly in com.google.android.material v1.1.0-alpha07 when it will be released this week.


text:
Q: What does the raised $^2$ stand for? What does the raised $2$ stand for? My first guess was: $4^2$ is $2\times 4=8$?
Note: Am not really good at math

A: It is called 'exponent' or 'power'.
Here $4^2$ means $4$ multiplied twice or in other words product of two $4's$. So:
$$4^2 = 4*4 = 16$$
Similarly $7^3$ means $7$ multiplied thrice or in other words product of three $7's$. So:
$$7^3 = 7*7*7 = 343$$
Since you are a starter, you can get more information about it here.


text:
Q: Join two Tables based on id order by time I need to combine two tables and order by the two tables date..
Medicine
| Id | Patientid | Name | Quantity |  medicine name | Takingtype | Epoch     |
===============================================================================
|  1 |       12  | raja | 20       | Ampicillin     |    1-1-1   | 1420446675|

Surgical
| Id | Patientid | Name | medicine name | Quantity | Epoch      |
=======================================================================
|  1 |       12  | raja | Mucinex oral  | 10       | 1420446675 |

Can any one help me?
The Result should be like  this,
|s.no| Date     | Name | Quantity  |  medicine name | Takingtype |
=================================================================
|  1 | 1-5-2015 | raja |  20       | Ampicillin     |    1-1-1   |
|  2 | 1-5-2015 | raja |  10       |Mucinex oral    |            |

Please help me join the tables like the result showed above. I'm looking for a mysql query..
(I have changed the epoch time in to date in php..)

A: Are you looking for UNION in MySQL?
SELECT name, quantity, medicine, Takingtype FROM Medicine
UNION ALL
SELECT name, quantity, medicine, NULL FROM Surgical

A: If I understand your question right, then what you want is not a join, it's a union.
select * from (
    select Name, Quantity, MedicineName, Epoch, Takingtype From Medicine
        union all
    select Name, Quantity, MedicineName, Epoch, NULL From Surgical
) x order by epoch;

I also assume that you want s.no to be a column that contains row ordinals. To my best knowledge you cannot really achieve that in MySQL without a temporary table (experts might correct me here).
Finally, if your datetime is indeed a time from the epoch, you need to use a FROM_UNIXTIMESTAMP builtin, something along the lines of
select * from (
    select FROM_UNIXTIMESTAMP(Epoch) AS Date, Name, Quantity, MedicineName, Epoch, Takingtype From Medicine
        union all
    select FROM_UNIXTIMESTAMP(Epoch) AS Date, Name, Quantity, MedicineName, Epoch, NULL From Surgical
) x order by epoch;


text:
Q: Mapping MySQL ENUM with AttributeConverter in InheritanceType.JOINED throwing IllegalArgumentExceptionon Hibernate 5.3.6 (JPA 2.1+): No enum constant I am mapping an inheritance hierarchy as shown here:

The thing here is, that the DB contains the single-char ENUM values 'P', 'C', and 'A' for persons, clubs and arenas respectively, but the Java enum values to work with are supposed to be PERSON, CLUB and ARENA.
This requires an AttributeConverter to be used to perform the DB value - Java enum conversion (see mappings below):
Contact entity:
@Entity
@Table(name="Contacts")
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class Contact extends BaseIdEntity
{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column
    protected Integer id;

    @Convert(converter=ContactTypeConverter.class)  // <-- !!! ... see below
    @Enumerated(EnumType.STRING)
    @Basic(optional=false)
    @Column
    protected ContactType type;  // actually a discriminator, but for JOINED inheritance, it is not required to annotate the class with @DiscriminatorColumn

    ...
}

ContactType ENUM:
public enum ContactType
{
    PERSON,  <-- fully written, but data is single-char
    CLUB,
    ARENA;
}

Person entity:
@Entity
@Table(name="Persons")
public class Person extends Contact
{
    private static final long serialVersionUID = 1L;

    @Basic(optional=false)
    @Column(name="first_name")
    private String firstName;

    @Basic(optional=false)
    @Column(name="last_name")
    private String lastName;

    ...
}

Club entity:
@Entity
@Table(name="Clubs")
public class Club extends Contact
{
    private static final long serialVersionUID = 1L;

    @Basic(optional=false)
    @Column
    private String name;

    @Basic(optional=false)
    @Column
    private String code;

    @Basic
    @Column(name="website_url")
    private String websiteUrl;

    ...
}

Arena entity:
@Entity
@Table(name="Arenas")
public class Arena extends Contact
{
    private static final long serialVersionUID = 1L;

    @Basic(optional=false)
    @Column
    private String name;

    @Basic
    @Column
    private Integer capacity;

    ...
}

Attribute converter for ContactType:
@Converter( autoApply = false )
public class ContactTypeConverter implements AttributeConverter<ContactType, String>
{
    @Override
    public String convertToDatabaseColumn( ContactType contactType )
    {
        System.out.println( "convertToEntityAttribute(" + contactType + ")" );

        switch ( contactType )
        {
            case PERSON:
                return "P";

            case CLUB:
                return "C";

            case ARENA:
                return "A";

            default:
                throw new IllegalArgumentException( "Unknown enum value: " + contactType );
        }
    }

    @Override
    public ContactType convertToEntityAttribute( String value )
    {
        System.out.println( "convertToEntityAttribute(\"" + value + "\")" );

        switch ( value )
        {
            case "P":
                return PERSON;

            case "C":
                return CLUB;

            case "A":
                return ARENA;

            default:
                throw new IllegalArgumentException( "Unknown DB value: " + value );
        }
    }
}

Here's the DDL + data for MySQL:
CREATE TABLE `Contacts`(
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `type` ENUM('P', 'C', 'A') NOT NULL,
  PRIMARY KEY (`id`));

CREATE TABLE `Arenas` (
  `id` INT(11) NOT NULL,
  `name` VARCHAR(50) NOT NULL,
  `capacity` INT(11) NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `arenas_contacts_fk`
    FOREIGN KEY (`id`)
    REFERENCES `Contacts` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

CREATE TABLE `Clubs` (
  `id` INT(11) NOT NULL,
  `name` VARCHAR(50) NOT NULL,
  `code` VARCHAR(5) NOT NULL,
  `website_url` VARCHAR(64) NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `clubs_contacts_fk`
    FOREIGN KEY (`id`)
    REFERENCES `Contacts` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

CREATE TABLE `Persons` (
  `id` INT(11) NOT NULL,
  `first_name` VARCHAR(50) NOT NULL,
  `last_name` VARCHAR(50) NOT NULL,
  PRIMARY KEY (`id`),
  CONSTRAINT `persons_contacts_fk`
    FOREIGN KEY (`id`)
    REFERENCES `Contacts` (`id`)
    ON DELETE CASCADE
    ON UPDATE CASCADE);

Data:
INSERT INTO `Contacts` (`id`, `type`) VALUES
(  1, 'P'),
(  2, 'P'),
(  3, 'P'),
( 26, 'P'),
( 99, 'P'),
(101, 'C'),
(102, 'C'),
(103, 'C'),
(201, 'A'),
(202, 'A'),
(203, 'A');

INSERT INTO `Persons` (`id`, `first_name`, `last_name`) VALUES
(  1, 'Kay', 'Wundrak'),
(  2, 'Joe', 'Locke'),
(  3, 'Ahmed', 'Thiab'),
( 26, 'Seb', 'Gottwalk'),
( 99, 'Test', 'Test');

INSERT IGNORE INTO `Clubs` (`id`, `name`, `code`) VALUES
(101, 'TV Dieburg', 'DIEB'),
(102, 'SC Rist Wedel', 'RIST'),
(103, 'BBG Herford', 'HERF');

INSERT IGNORE INTO `Arenas` (`id`, `name`, `capacity`) VALUES
(201, 'Schlossgartenhalle', NULL),
(202, 'Steinberghalle', NULL),
(203, 'Halle am Gymnasium', NULL);

I have consulted many sources, e.g.
https://www.nurkiewicz.com/2013/06/mapping-enums-done-right-with-convert.html [MAIN]
https://thoughts-on-java.org/jpa-21-type-converter-better-way-to/
https://thoughts-on-java.org/jpa-21-how-to-implement-type-converter/
https://www.baeldung.com/jpa-persisting-enums-in-jpa
http://eloquentdeveloper.com/2016/07/18/persisting-enums-using-jpa-attribute-converter/
All say the same, but it doesn't work. When loading a list of persons I get:
Caused by: java.lang.IllegalArgumentException: No enum constant net.bbstats.entity.ContactType.P
    at java.lang.Enum.valueOf(Enum.java:238)
    at org.hibernate.type.descriptor.java.EnumJavaTypeDescriptor.fromName(EnumJavaTypeDescriptor.java:84)
    at org.hibernate.metamodel.model.convert.internal.NamedEnumValueConverter.toDomainValue(NamedEnumValueConverter.java:39)
    at org.hibernate.metamodel.model.convert.internal.NamedEnumValueConverter.readValue(NamedEnumValueConverter.java:69)
    at org.hibernate.type.EnumType.nullSafeGet(EnumType.java:250)
    at org.hibernate.type.CustomType.nullSafeGet(CustomType.java:119)
    at org.hibernate.type.AbstractType.hydrate(AbstractType.java:91)
    at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3007)
    at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1746)
    at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1672)
    at org.hibernate.loader.Loader.getRow(Loader.java:1561)
    at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:731)
    at org.hibernate.loader.Loader.processResultSet(Loader.java:990)
    at org.hibernate.loader.Loader.doQuery(Loader.java:948)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:340)
    at org.hibernate.loader.Loader.doList(Loader.java:2689)
    at org.hibernate.loader.Loader.doList(Loader.java:2672)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2506)
    at org.hibernate.loader.Loader.list(Loader.java:2501)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:504)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:395)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:220)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1508)
    at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1537)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1505)
    at org.hibernate.query.Query.getResultList(Query.java:135)
    at net.bbstats.framework.service.Repository.findByNamedQuery(Repository.java:184)
    at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:382)
    at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:368)
    at net.bbstats.framework.service.BaseEntityService.findByNamedQuery(BaseEntityService.java:344)
    at net.bbstats.framework.service.BaseEntityService.findAllByQueryWithFetchGraph(BaseEntityService.java:300)
    ... 179 more

Look at line:
java.lang.IllegalArgumentException: No enum constant net.bbstats.entity.ContactType.P
Not really converting correctly or not at all...?
QUESTION:
What's wrong here? I am nearly 100% sure, that the mappings are correct...
-> Is it a Hibernate bug? Is it because of the inheritance mappings? Maybe not working with InheritanceType.JOINED?
In any case, one observation is, that no matter what, the attribute converter is never called, that is no breakpoints are ever reached in ContactTypeConverter and no sysouts are ever printed to the console/log.
Setup: WildFly 14.0.1.Final, Hibernate 5.3.6.Final

A: According to this.

JPA explicitly disallows the use of an AttributeConverter with an attribute marked as @Enumerated. So, when using the AttributeConverter approach, be sure not to mark the attribute as @Enumerated.


text:
Q: How can I get access to object of `QQmlApplicationEngine` inside a `QQuickItem` derived class? The variable engine in the following typical main function of a QtApp is a valid instance of QQmlApplicationEngine.
int main(int argc, char *argv[])
{
  QGuiApplication app(argc, argv);

  QQmlApplicationEngine engine;
  engine.load(QUrl(QStringLiteral("qrc:/qml/main.qml")));

  return app.exec();
}

Is it possible to get access to object of QQmlApplicationEngine inside a function of a QQuickItem derived class? If yes, how?
class TestItem : public QQuickItem {
public:
  TestItem();
  SomeMethod() {
     // Is it possible to get access to QQmlApplicationEngine here somehow ?
  }
}

Note that TestItem is registered on the qml side & displayed on the main window. I know that I can pass the QQmlApplicationEngine from main method. But, I have a hunch that because my TestItem is part of the window & holds the context. There should be a way to get an object or pointer to QQmlApplicationEngine without having to pass from main method ?
The objective: Using QQmlApplicationEngine I can get access to QQuickItems in my main.qml by doing so:
QQuickItem *some_quick_item = qml_engine->rootObjects()[0]->findChild<QQuickItem*>("SomeQuickItem");

So for doing this, I want to the QQmlApplicationEngine. If theres a way to get access to other QQuickItems from inside of one then please suggest.

A: You can use this static function:
QQmlEngine::contextForObject(this)->engine();

Of course, it might be a good idea whether contextForObject() returns a valid pointer before you try and invoke engine() for it.
Then you can use qobject_cast<QQmlApplicationEngine*>(engine) which should give you the desired pointer as long as your application is indeed a QQmlApplicationEngine based one.


text:
Q: C free() invalid next size (normal) I'm fairly new to C and I can't seem to figure out what seems to be a pretty simple pointer problem.  My program adds line numbers to a file.  It reads in the file line by line and then adds a line number to the beginning of each line. It works fine on each file individually as you can see below:
soccer@soccer-Dell-DV051:~/code C$ ./a.out test.c
soccer@soccer-Dell-DV051:~/code C$ ./a.out miscellaneousHeader.h
soccer@soccer-Dell-DV051:~/code C$ ./a.out test.c miscellaneousHeader.h
*** Error in `./a.out': free(): invalid next size (normal): 0x08648170 ***
Segmentation fault (core dumped)
soccer@soccer-Dell-DV051:~/code C$

but when I run them together I get the above error.  The following code is my program.
Compiler.c:
#include <stdio.h>
#include "lineNumAdderHeader.h"
#include "miscellaneousHeader.h"

int main(int argc, char *argv[]){
    if (argc < 2)
        fatal("in main(). Invalid number of arguments");

    int i = 1;
    while (i < argc){
        lineNumAdder(argv[i]);
        i++;
    }
}

I have narrowed the problem to the lineNumPtr. The error occurs when lineNumPtr is freed after the second file. If lineNumPtr is not freed, which I know is bad programming, the program works just fine.
lineNumAdder.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miscellaneousHeader.h"
#include "lineNumAdderHeader.h"

int lineSizeChecker(FILE*, int);
int lineNumChecker(char*);
int fileSizeChecker(FILE*);

void lineNumAdder(char* filename){
    int lineSpace, position, lineNumCheckerBoolean, numOfDigits, fileSpace;
    int lineNum = 1;
    char *lineNumPtr = NULL;
    char *numberedFile = NULL;
    char *nonNumberedLine = NULL;
    char *originalLine = NULL;
    FILE *file = errorCheckedFopen(filename, "r+w");

    while(1){
        position = ftell(file);

        if (position == 0){
            fileSpace = fileSizeChecker(file);
            numberedFile = errorCheckedMalloc(fileSpace);
        }

        lineSpace = lineSizeChecker(file, position);
        if (position == 0)
            originalLine = errorCheckedMalloc(lineSpace);
        else
            originalLine = realloc(originalLine, lineSpace);

        if (fgets(originalLine, lineSpace, file) == NULL)
            break;

        lineNumCheckerBoolean = lineNumChecker(originalLine);

        if (lineNumCheckerBoolean == 0){
            if (position == 0)
                nonNumberedLine = errorCheckedMalloc(lineSpace - 9);
            else
                nonNumberedLine = realloc(nonNumberedLine, lineSpace - 9);

            strcpy(nonNumberedLine, &originalLine[9]);
        }
        else{
            if (position == 0)
                nonNumberedLine = errorCheckedMalloc(lineSpace);
            else
                nonNumberedLine = realloc(nonNumberedLine, lineSpace);

            strcpy(nonNumberedLine, originalLine);

            fileSpace += 8;
            numberedFile = realloc(numberedFile, fileSpace);
        }

        numOfDigits = intDigitFinder(lineNum);
        if (position == 0)
            lineNumPtr = errorCheckedMalloc(numOfDigits);
        else
            lineNumPtr = realloc(lineNumPtr, numOfDigits);
        sprintf(lineNumPtr, "%d", lineNum);

        strcat(numberedFile, "/*");
        strcat(numberedFile, lineNumPtr);
        strcat(numberedFile, "*/");
        if (lineNum < 10)
            strcat(numberedFile, "    ");
        else if (lineNum >= 10 && lineNum < 100)
            strcat(numberedFile, "   ");
        else if (lineNum >= 100 && lineNum < 1000)
            strcat(numberedFile, "  ");
        else if (lineNum >= 1000 && lineNum < 10000)
            strcat(numberedFile, " ");
        strcat(numberedFile, nonNumberedLine);
        lineNum++;
    }

    fclose(file);
    free(originalLine);
    free(nonNumberedLine);
    free(lineNumPtr);
    free(numberedFile);
}

int lineNumChecker(char *comment){
    if (sizeOf(comment) < 8)
        return 1;

    if (comment[7] == '/' || comment[6] == '/' || comment[5] == '/' || comment[4] == '/')
        return 0;
    else
        return 1;
}

int lineSizeChecker(FILE *file, int position){
    int i = 2;
    int ch;

    while ((ch = fgetc(file)) != '\n' && ch != EOF)
        i++;

    fseek(file, position, SEEK_SET);

    return i;
}

int fileSizeChecker(FILE *file){
    int i = 2;

    while (fgetc(file) != EOF)
        i++;

    fseek(file, 0, SEEK_SET);

    return i;
}

miscellaneous.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miscellaneousHeader.h"

void fatal(char*);

int sizeOf(char *data){
    int i = 1;

    while(data[i-1] != '\n')
        i++;

    return i;
}

void *errorCheckedMalloc(size_t size){
    void *ptr = malloc(size);

    if (ptr == NULL)
        fatal("in errorCheckedMalloc(). Memory Allocation Failure\n");
    else
        return ptr;
}

FILE *errorCheckedFopen(char *filename, char *mode){
    FILE *file = fopen(filename, mode);

    if (file == NULL)
        fatal("in errorCheckedFopen(). File Opening Failure\n");
    else
        return file;
}

void fatal(char *errorMessage){
    char* completedErrorMessage = errorCheckedMalloc(sizeOf(errorMessage)+17);

    strcpy(completedErrorMessage, "[!!] Fatal Error ");
    strcat(completedErrorMessage, errorMessage);

    perror(completedErrorMessage);

    free(completedErrorMessage);

    exit(-1);
}

int intDigitFinder(int num){
    int digits = 0;

    do {
        num /= 10;
        digits++;
    } while (num != 0);

    return digits;
}

void *reMalloc(void *ptr, size_t size){
    char buf[strlen(ptr) + 1];
    strcpy(buf, ptr);

    free(ptr);

    ptr = errorCheckedMalloc(size);

    if(size >= strlen(buf))
        strcpy(ptr, buf);

    return ptr;
}

I apologize for the length. This is my first post and I wanted to make sure that I provided enough information for you guys to give me the best answers possible. Thank you for any and all answers.  They are much appriciated.

A: Ok guys, so I have gotten it to work.  I have tweaked the lineNumAdder.c file.  The program now increases numberedFile's size by the line each time it is read in. Also the error was occuring on the second file because when I would strcat the line number into the malloced area junk was already stored there, so numberedFile would overflow. I have fixed this by using calloc instead of malloc. Thank you to all who gave answers and commented. They all helped tremendously.
Here is the completed lineNumAdder.c file:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "miscellaneousHeader.h"
#include "lineNumAdderHeader.h"

int lineSizeChecker(FILE*, int);
int lineNumChecker(char*);
int fileSizeChecker(FILE*);

void lineNumAdder(char* filename){
    int lineSpace, filePosition, lineNumCheckerBoolean, numOfDigits;
    int fileSpace = 0;
    int lineNum = 1;
    char *lineNumPtr = NULL;
    char *numberedFile = NULL;
    char *nonNumberedLine = NULL;
    char *originalLine = NULL;
    FILE *file = errorCheckedFopen(filename, "r+w");

    while(1){
        filePosition = ftell(file);

        lineSpace = lineSizeChecker(file, filePosition);
        if (filePosition == 0)
            originalLine = calloc(1, lineSpace);
        else
            originalLine = realloc(originalLine, lineSpace);

        if (fgets(originalLine, lineSpace, file) == NULL)
            break;

        lineNumCheckerBoolean = lineNumChecker(originalLine);
        if (lineNumCheckerBoolean == 0){
            fileSpace += lineSpace;
            if (filePosition == 0){
                nonNumberedLine = calloc(1, lineSpace - 8);

                numberedFile = calloc(1, fileSpace);
            }
            else{
                nonNumberedLine = realloc(nonNumberedLine, lineSpace - 8);

                numberedFile = realloc(numberedFile, fileSpace);
            }

            strcpy(nonNumberedLine, &originalLine[9]);
        }
        else{
            fileSpace += lineSpace + 9;
            if (filePosition == 0){
                nonNumberedLine = calloc(1, lineSpace);

                numberedFile = calloc(1, fileSpace);
            }
            else{
                nonNumberedLine = realloc(nonNumberedLine, lineSpace);

                numberedFile = realloc(numberedFile, fileSpace);
            }

            strcpy(nonNumberedLine, originalLine);
        }

        numOfDigits = intDigitFinder(lineNum);
        if(filePosition == 0)
            lineNumPtr = calloc(1, numOfDigits);
        else
            lineNumPtr = realloc(lineNumPtr, numOfDigits);
        sprintf(lineNumPtr, "%d", lineNum);

        strcat(numberedFile, "/*");
        strcat(numberedFile, lineNumPtr);
        strcat(numberedFile, "*/");
        if (lineNum < 10)
            strcat(numberedFile, "    ");
        else if (lineNum >= 10 && lineNum < 100)
            strcat(numberedFile, "   ");
        else if (lineNum >= 100 && lineNum < 1000)
            strcat(numberedFile, "  ");
        else if (lineNum >= 1000 && lineNum < 10000)
            strcat(numberedFile, " ");
        strcat(numberedFile, nonNumberedLine);
        lineNum++;
    }

    fclose(file);
    free(originalLine);
    free(nonNumberedLine);
    free(lineNumPtr);
    free(numberedFile);
}

int lineNumChecker(char *comment){
    if (sizeOf(comment) < 8)
        return 1;

    if (comment[7] == '/' || comment[6] == '/' || comment[5] == '/' || comment[4] == '/')
        return 0;
    else
        return 1;
 }

 int lineSizeChecker(FILE *file, int position){
    int i = 2;
    int ch;

    while ((ch = fgetc(file)) != '\n' && ch != EOF)
        i++;

    fseek(file, position, SEEK_SET);

    return i;
}

int fileSizeChecker(FILE *file){
    int i = 2;

    while (fgetc(file) != EOF)
        i++;

fseek(file, 0, SEEK_SET);

    return i;
}

A: So, it's difficult to debug this... But at the very least:
int sizeOf(char *data) {
    int i = 1;

    while(data[i-1] != '\n' && data[i-1] != '\0')
        i++;

    return i;
}


text:
Q: md Raid6 array disapeered on reboot my raid6 array disappeared on reboot after I grew it. I believe the issue was growing 2x with the full disk not partition. It has been suggested a possible other reason the drives were not correctly recognized is I didn't zero the superblocks before readding to a new array. It could be a combination of both? Here are the commands issued (pulled from history, formatted to have consistent drive letters):
mdadm --create --verbose /dev/md0 --level=0 --raid-devices=2 /dev/sd[b-c]1

#Full backup of ROC raid 10 onto these drives, after having copied most files to other drives, check to make sure worked through reboot.
mdadm --create /dev/md1 --level=6 --raid-devices=4 /dev/sd[d-g]1

#Time passed to sync drives, and then rsync data from md0, reboots fine.
mdadm -S /dev/md0
mdadm /dev/md0 -r /dev/sd[b-c]

#NOTICE THE MISSING PARTITION NUMBER BELOW.
mdadm /dev/md1 --add /dev/sdb
mdadm /dev/md1 --add /dev/sdc
mdadm -list
mdadm --detail /dev/md1
mdadm --grow --raid-devices=6 --backup-file=/media/FastRaid/md1_grow.bak /dev/md1

After a reboot, the raid6 disapeered and is replaced by 2 raid0 arrays, one active (sdb/sdc) and one inactive (sdd-sdg). The the following is what I get from examining the superblocks:
/dev/sdb1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
    Array UUID : 501c08da:5069a3d8:b2982a5d:ab56c37c
        Name : tim-server:0  (local to host tim-server)
Creation Time : Tue Dec 13 22:01:10 2022
    Raid Level : raid0
Raid Devices : 2

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=0 sectors
        State : clean
    Device UUID : e8db27d6:0dbd1ac5:4456c304:0b43f09c

    Update Time : Tue Dec 13 22:01:10 2022
Bad Block Log : 512 entries available at offset 8 sectors
    Checksum : dfd187c0 - correct
        Events : 0

    Chunk Size : 512K

Device Role : Active device 0
Array State : AA ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdc1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x0
    Array UUID : 501c08da:5069a3d8:b2982a5d:ab56c37c
        Name : tim-server:0  (local to host tim-server)
Creation Time : Tue Dec 13 22:01:10 2022
    Raid Level : raid0
Raid Devices : 2

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=0 sectors
        State : clean
    Device UUID : 3ce84b05:607f8565:456e7f83:88b83052

    Update Time : Tue Dec 13 22:01:10 2022
Bad Block Log : 512 entries available at offset 8 sectors
    Checksum : e35ce3e5 - correct
        Events : 0

    Chunk Size : 512K

Device Role : Active device 1
Array State : AA ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdd1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
    Array UUID : 929a14c9:adaf502a:53658e03:90a19fce
        Name : tim-server:0  (local to host tim-server)
Creation Time : Wed Dec 14 11:18:57 2022
    Raid Level : raid6
Raid Devices : 6

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Array Size : 15627540480 (14903.58 GiB 16002.60 GB)
Used Dev Size : 7813770240 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=655 sectors
        State : clean
    Device UUID : eaf10189:940aeaf8:947efe82:5d0e4aea

Internal Bitmap : 8 sectors from superblock
    Update Time : Sun Dec 18 06:31:11 2022
Bad Block Log : 512 entries available at offset 24 sectors
    Checksum : e38a1bd9 - correct
        Events : 26630

        Layout : left-symmetric
    Chunk Size : 512K

Device Role : Active device 1
Array State : AAAAAA ('A' == active, '.' == missing, 'R' == replacing)
/dev/sde1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
    Array UUID : 929a14c9:adaf502a:53658e03:90a19fce
        Name : tim-server:0  (local to host tim-server)
Creation Time : Wed Dec 14 11:18:57 2022
    Raid Level : raid6
Raid Devices : 6

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Array Size : 15627540480 (14903.58 GiB 16002.60 GB)
Used Dev Size : 7813770240 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=655 sectors
        State : clean
    Device UUID : 5c34a9c7:bcc3f190:d1719a9c:8aa2b722

Internal Bitmap : 8 sectors from superblock
    Update Time : Sun Dec 18 06:31:11 2022
Bad Block Log : 512 entries available at offset 24 sectors
    Checksum : c429edf - correct
        Events : 26630

        Layout : left-symmetric
    Chunk Size : 512K

Device Role : Active device 3
Array State : AAAAAA ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdf1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
    Array UUID : 929a14c9:adaf502a:53658e03:90a19fce
        Name : tim-server:0  (local to host tim-server)
Creation Time : Wed Dec 14 11:18:57 2022
    Raid Level : raid6
Raid Devices : 6

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Array Size : 15627540480 (14903.58 GiB 16002.60 GB)
Used Dev Size : 7813770240 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=655 sectors
        State : clean
    Device UUID : 12d1e3a8:b8749f59:654bcca4:4f4750df

Internal Bitmap : 8 sectors from superblock
    Update Time : Sun Dec 18 06:31:11 2022
Bad Block Log : 512 entries available at offset 24 sectors
    Checksum : 7af56ae7 - correct
        Events : 26630

        Layout : left-symmetric
    Chunk Size : 512K

Device Role : Active device 0
Array State : AAAAAA ('A' == active, '.' == missing, 'R' == replacing)
/dev/sdg1:
        Magic : a92b4efc
        Version : 1.2
    Feature Map : 0x1
    Array UUID : 929a14c9:adaf502a:53658e03:90a19fce
        Name : tim-server:0  (local to host tim-server)
Creation Time : Wed Dec 14 11:18:57 2022
    Raid Level : raid6
Raid Devices : 6

Avail Dev Size : 7813770895 (3725.90 GiB 4000.65 GB)
    Array Size : 15627540480 (14903.58 GiB 16002.60 GB)
Used Dev Size : 7813770240 (3725.90 GiB 4000.65 GB)
    Data Offset : 264192 sectors
Super Offset : 8 sectors
Unused Space : before=264112 sectors, after=655 sectors
        State : clean
    Device UUID : 72085967:835efe92:cb268a64:4d192b52

Internal Bitmap : 8 sectors from superblock
    Update Time : Sun Dec 18 06:31:11 2022
Bad Block Log : 512 entries available at offset 24 sectors
    Checksum : a5623977 - correct
        Events : 26630

        Layout : left-symmetric
    Chunk Size : 512K

Device Role : Active device 2
Array State : AAAAAA ('A' == active, '.' == missing, 'R' == replacing)

I had inactivated md0 at some point, so I recreated with mdadm -A -o /dev/md0 /dev/sdb1 /dev/sdc1. This is a /proc/mdstat now:
cat /proc/mdstat

Personalities : [raid0] [linear] [multipath] [raid1] [raid6] [raid5] [raid4] [raid10]
md0 : active (read-only) raid0 sdb1[0] sdc1[1]
  7813770240 blocks super 1.2 512k chunks

md1 : inactive sdf1[0](S) sde1[3](S) sdd1[1](S) sdg1[2](S)
    15627541790 blocks super 1.2

unused devices: <none>

If I try to mount /dev/md0 /media/tmp_md_raid I get: mount: /media/tmp_md_raid: wrong fs type, bad option, bad superblock on /dev/md126, missing codepage or helper program, or other error.. If I try: mdadm -A -o /dev/md1 /dev/sdf1 /dev/sde1 /dev/sdd1 /dev/sdg1 I get:
mdadm: /dev/sdf1 is busy - skipping
mdadm: /dev/sde1 is busy - skipping
mdadm: /dev/sdd1 is busy - skipping
mdadm: /dev/sdg1 is busy - skipping

All of the smartctl's say all the drives are fine. I am not sure if I should try an mdadm --assemble --force first or an mdadm --create --assume-clean first. Should I try the 2nd with -o set to see if I can recreate the array and view the data without possibly destroying the recovery? Thanks for any advice.

A: It seems you have 6-device array (AAAAAA), but only 4 component devices are available (/dev/sd[defg]1). The capacity calculation confirms this: one needs 6 disks of 4TB to create 16TB RAID6 array.
Since this is RAID6 and all 4 available devices seem to be in sync, it can be run, but only in so called fully degraded mode. In this mode to read any block it needs to read a stripe from all drives (which is I/O intensive) and perform a reconstruction (it uses both parity syndroms which involves CPU-intensive Galois field calculations), and to write a block it needs to do read the whole stripe, calculate new parity syndroms and write to at least three devices (which is even more I/O-intensive overall).
Linux has no other way to go but fall back to this if the array was running and some device failed in the middle of the use, that's the whole point of having a RAID array. As you may have guessed, the performance in this state is very bad and the risk of losing data is very high, which is why you shouldn't run an array in this state for long stretches of time. Ideally you supply a hot spare in addition to working devices so it will be able to start reconstruction immediately it detects the failure of any component.
But during the boot it doesn't know are some devices permanently missing or are they just not available yet due to staggered spin-up or other initialization delays. Activating array early will kick late devices out of sync and force a time-lengthy resync, during which the array will experience the worst performance characteristic as described above. This motivates to wait for late appearing devices. Linux will not activate partially-available array by default automatically, even if there are enough devices to run it at least in some degraded mode.
But you, an administrator, can force it to do so. For this, reassemble the array with --force:
mdadm --stop /dev/md1
mdadm --force --assemble /dev/md1 /dev/sd[defg]1

More precisely, it won't automatically assemble the array if there are less devices available than are recorded in superblocks of present devices (in your case it is recorded that all devices were available last time); when you remove a device properly with mdadm -f/ mdadm -r sequence, or when force assembling it, it records that and the array will then be auto-assembled in same degraded state automatically.
If this array doesn't contain valuable data, better re-create it. Initialization feels faster than adding devices and suffering reconstruction.


text:
Q: Best practices when starting a new project When you first fire up Visual Studio, or even before that (Hopefully)
What do you consider best practices when starting a new project?
Different things I have done in the past

*

*Consider the technology choices

*Attempt to identify the potential bottlenecks/brickwalls

*Throw away the specification

*Ask lots and lots of questions

*Launched straight into code! (who hasn't?)

As programmers we should be methodical in our approach.
What do you do when starting a new project?

A: Start using version control right away.
It is always frustrating building prototype "throwaway code" that eventually gets thrown away - and then realizing that some of that code would be really really useful to have.

A: (If applicable) Figure out whether you are building a throwaway prototype, an expandable prototype, or a final production system.
I think that a major problem with a lot of projects is that people don't get this one figured out to begin with. They either over-engineer and the project doesn't deliver on time, or they write throwaway code that later becomes too expensive to throw away.

A: I do the following when building for others.  WHen I build myself using more agile dev concepts, I still cycle through these steps.   It makes it very easy to involve others as well.
Analyze: What do we need to do and why.  Aka feature spec.
Design: what are we going to build, how will it work, and why?  aka. Technical Spec.
Plan: What and who do we need, when, to do what
Implement: Build, test, repeat.
Launch: Almost there.
Support/Document/Train, etc: In case you get hit by a bus, or someone arranges for it.

A: Scrum
++

*

*Requirements Gathering

*Scope

*Out of Scope

*Pick Platform to deliver on and appropriate Development Environment

*Calculate Expenses, Make budget

*Schedule

*Review at each stage and educate the end user of what is being made throughout

easy tips

A: Create my first test project.

A: One main thing I always like to know is, who exactly is doing what! even from the starting point. Stops alot of time being lost.


text:
Q: Passport/Express: Unable to Authenticate User after creating a New User on register I have a NodeJS/Express server running. I am using PassportJS from Authentication.
I have successfully created login capability. I am able to successfully login in a user that already exists in the server when it is started.
I am unable to successfully authenticate a new user. The user is created successfully, and passport authentication seems to go through. But when redirected and isAuthenticated is called. It returns false.
I have tried using exactly what I am using in the login auth. I have tried the simplest version of the passport auth. I have researched many SO answers and consulted the documentation
Current relevant code:
passport.use(
  new localStrategy(
    { usernameField: "userName" },
    (userName, password, done) => {
      const userList = getUsersByUserName(userName);

      if (!userList[0]) {
        return done(null, false, {
          message: "Invalid Username or Password.\n",
        });
      }
      if (password !== userList[0].password) {
        return done(null, false, {
          message: "Invalid Username or Password.\n",
        });
      }

      return done(null, userList[0]);
    }
  )
);

passport.serializeUser((user: User, done) => {
  done(null, user.userID);
});

passport.deserializeUser((id, done) => {
  const user = users[0].userID === id ? users[0] : false;
  done(null, user);
});

app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/login", (req, res, next) => {
  passport.authenticate("local", (perr, user, info) => {
    if (info) {
      return res.send("Invalid Username or Password.");
    }
    if (perr) {
      return next(perr);
    }
    if (!user) {
      return res.redirect("/");
    }
    req.login(user, (lerr) => {
      if (lerr) {
        return next(lerr);
      }

      return res.send(user); // I am redirecting in the client code
    });
  })(req, res, next);
});

app.post("/register", (req, res, next) => {
  const userName = req.body.userName;
  const name = req.body.name;
  const email = req.body.email;
  const password = req.body.password;
  const cpassword = req.body.cpassword;

  if (!name) {
    return res.send("Please enter a Name");
  }
  if (!userName) {
    return res.send("Please enter a Username");
  }
  if (!email) {
    return res.send("Please enter an Email");
  }
  if (password !== cpassword) {
    return res.send("Passwords do not Match");
  }
  if (password.length < 4) {
    return res.send("Password must be at least 4 characters");
  }
  const userList: User[] = getUsersByUserName(userName);

  if (userList.length > 0) {
    return res.send("That username is already taken");
  }

  const newUser: User = {
    userID: uuid(),
    userName,
    password,
    email,
    name,
  };

  users.push(newUser);

  passport.authenticate("local", (perr, user, info) => {
    if (info || !user) {
      return res.send("Invalid Username or Password.");
    }
    if (perr) {
      return next(perr);
    }
    req.login(user, (lerr) => {
      if (lerr) {
        return next(lerr);
      }

      return res.send(user);
    });
  })(req, res, next);
});

function isAuthenticated(req: any, res: any, next: any) {
  if (req.isAuthenticated()) {
    return next();
  }

  return res.redirect("/");
}

When following the register passport auth. I am seeing results that would make me believe that the user should be authenticated. But when the user is redirected and the isAuthenticated is called. I receive false
Update
I am storing my sessions using session-file-store. The session is stored without the userID...
Logging in: {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"__lastAccess":1564192764406,"passport":{"user":"7fa35b71-8733-441e-afcd-ed68defa68bf"}}

Registering a new user: {"cookie":{"originalMaxAge":null,"expires":null,"httpOnly":true,"path":"/"},"__lastAccess":1564193852150,"passport":{}}

A: passport.deserializeUser((id, done) => {

  const user = getUser(id as string);
  // const user = users[0].userID === id ? users[0] : false;
  done(null, user);
});

I was comparing the first user instead of finding the user using the id.... Big Fail.


text:
Q: Convert an associative array to a simple of its values in php I would like to convert the array:
Array
(
    [0] => Array
        (
            [send_to] => 9891616884
        )

    [1] => Array
        (
            [send_to] => 9891616884
        )

)

to
$value = 9891616884, 9891616884

A: Try this:

//example array
$array = array(
    array('send_to'=>3243423434),
    array('send_to'=>11111111)
);

$value = implode(', ',array_column($array, 'send_to'));

echo $value; //prints "3243423434, 11111111"

A: You can use array_map:
$input = array(
  array(
    'send_to' => '9891616884'
  ),
  array(
    'send_to' => '9891616884'
  )
);

echo implode(', ', array_map(function ($entry) {
  return $entry['tag_name'];
}, $input));

A: Quite simple, try this:
// initialize and empty string
$str = '';

// Loop through each array index
foreach ($array as $arr) {
   $str .= $arr["send_to"] . ", ";
}

//removes the final comma and whitespace
$str = trim($str, ", ");


text:
Q: Avoid cleaning canvas in updateOptions call I am working in a signals plot program trying to simulate the 'persistence' feature as available in many oscilloscopes.
I would like to prevent dygraph canvas to clean for every updateOptions call. Instead of that, my plot should be preserved until an explicit call for cleaning. This feature will allow me to check if a signal preserves its phase during a certain amount of time.
I tried to use block_redraw parameter set to false in updateOptions function without no success.
Any ideas?

A: This isn't really something dygraphs is designed to do. You're asking it to render the full history of its data source, rather than the current state of its data source.
That being said, here's the code that clears the plotting canvas:
DygraphCanvasRenderer.prototype.clear = function() {
  this.elementContext.clearRect(0, 0, this.width, this.height);
};

So if you override that, it might do what you want:
DygraphCanvasRenderer.prototype.clear = function() {};

That being said, this is liable to break lots of things (like zooming and panning) in addition to giving you the behavior you want. You can see this if you visit the live random data demo page and copy that snippet into the JS console.
Good luck!


text:
Q: Access Master Page/Child Page Controls from My Class I have a div on my master page and I want to use it for showing page errors. I have an error display class and it works fine. My problem is that in some instances, the error gets displayed even before the  tag resulting in (non)-display of the message. This is mostly with code that has response.redirect.
I want to counter this by having the error shown on a div within my master page (hoep it helps).
How can I access <div id="errorSegment" runat="server">?

A: You can use the FindControl method on any class that inherits from System.Web.UI.Control.  This includes Master Pages, Pages and UserControls.  For instance, from a page class, you could do:
HtmlGenericControl errorDiv = (HtmlGenericControl)Master.FindControl("errorSegment");

The other thing to remember about using FindControl is that controls in an ASP page are arranged in a control tree structure.  This means that you need to call FindControl on the right node in the tree (typically the Page or the MasterPage).

A: You can create a public property on your master page that exposes the div:
public HtmlGenericControl ErrorSegment
{
    get { return errorSegment; }
}

Your pages that use that master page will have a reference to the master page through the Page.Master property, but the type of this property will be the base master page class, not your specific class with the public property.  Therefore, add this tag to your pages' aspx markup to generate a Master property with your specific master page type:
<%@ MasterType VirtualPath="~/AccessManager.Master" %>

You can then access it from the page using the page's reference to the master page:
    this.Master.ErrorSegment

A: Your MasterPage can have a public property to expose the div:
public HtmlGenericControl ErrorSegment
{
    get { return errorSegment; }
}

As you will probably use ErrorSegment property on many pages it might be good to declare a base class for your pages and include the following declaration:
public class MyBasePage : System.Web.UI.Page
{
    // This declaration "forces" the Master property to be of your preferred type.
    public new MyMasterPage Master
    {
        get
        {
            return ((MyMasterPage)(base.Master));
        }
    }
}

Now you can access ErrorSegment on any page deriving from MyBasePage (also indirectly) with the following code:
this.Master.ErrorSegment

The advantage of this solution over the <%@ MasterType %> tag is that you can move this declaration along your class hierachy and then access the ErrorSegment on any level that you need.


text:
Q: Install and use tensorflow_docs with Jupyter Notebook I am trying to follow this tutorial https://www.tensorflow.org/tutorials/keras/regression but I get some error when I try to import tenroflow_docs.
As mentioned in the tutorial, I installed tensorflow_docs with the following command: !pip install -q git+https://github.com/tensorflow/docs. The installation seemed to have worked as I get the message: "Successfully built tensorflow-docs".
However, when I want to import the package by writing (as per the tutorial) import tensorflow_docs as tfdocs I get the error message shown in the picture below.
How can I correct this? Thanks for the help.

A: I have noticed that this message appeared during your installation "Defaulting to user installation because normal site-packages is not writeable"
The problem is that a default install location is a place where you do not have write permissions. The solution is to use an install location where you do have write permissions.
Have you tried using a virtual environment instead? this is a better practice and might be an easier solution.


text:
Q: How can I get generic type of PsiClassReferenceType public class RestControllerExample {

    @GetMapping("/test")
    public Test<String, Integer> req() {
        return null;
    }

    static class Test<T, V> {

        private T fieldT;

        private V fieldV;

        public T getFieldT() {
            return fieldT;
        }

        public void setFieldT(T fieldT) {
            this.fieldT = fieldT;
        }

        public V getFieldV() {
            return fieldV;
        }

        public void setFieldV(V fieldV) {
            this.fieldV = fieldV;
        }
    }
}

PsiClassReferenceType is Test<String, Integer>. How can I know fieldT is String and fieldV is Integer?
class Test<T, V> just a demo, I can't use the getParameters() method to get the type because the order of the fields is not fixed. It is possible that fieldT is declared after fieldV

A: field.getType().substitute(classReferenceType.resolveGenerics().getSubstitutor()) should do the job.

*

*fieldT.getType() in your example must return T

*classReferenceType.resolveGenerics() (returns a pair of class and its substitutor), in your example Test and T -> String, V -> Integer

*method substitute would replace T in the type with a String, V with an Integer


text:
Q: generating entity from cs file code in edmx I started a sample entity framework project. I've the EntityModel.edmx file, when I clicked the EntityModel.Designer.cs file, it opens a file written:
// T4 code generation is enabled for model 'c:\users\scala\documents\visual studio 2013\Projects\entityFramework\entityFramework\EntityModel.edmx'.
// To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
// property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
// is open in the designer.

// If no context and entity classes have been generated, it may be because you created an empty model but
// have not yet chosen which version of Entity Framework to use. To generate a context class and entity
// classes for your model, open the model in the designer, right-click on the designer surface, and
// select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
// Item...'.

I cannot get the entity code. How can I get the entity code? I can not change the 'Code Generation Strategy' designer
property to 'Legacy ObjectContext' in the property window.

A: Read carefully what is written in the comments:

To generate a context class and entity classes for your model, open the model in the designer, right-click on the designer surface, and select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation Item...'.

'Add Code Generation Item...' will do the trick. You should basically choose and add one or more T4 templates to actually generate the entities. More info here. Also take a look at this answer. It might help to make things clear.


text:
Q: An error in the HTML "upgrade-insecure-requests" The Content Security Policy 'upgrade-insecure-requests' was delivered via a  element outside the document's , which is disallowed. The policy has been ignored.
I got this while adding bootstrap in balzor. please anyone can help.
I added
<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />

A: <meta http-equiv="Content-Security-Policy" content="block-all-mixed-content">

try to add this meta tag inside your head tag. and if still getting the same issue then share a screenshot of the error.